量角器变量重用效率

protractor variables reuse efficiency

本文关键字:效率 变量 量角器      更新时间:2023-09-26

我在某处读到(我再也找不到这篇文章),当多次调用一个元素时,最好(花费更少的时间和更少的资源)使用这样的变量:

var proceed = element(by.className('proceed');
browser.wait(EC.presenceOf(proceed).click()), timeout, 'no proceed found!');
browser.wait(EC.presenceOf(proceed).click()), timeout, 'no proceed found!');

而不是像这样调用元素:

browser.wait(EC.presenceOf(element(by.className('proceed')).click()), timeout, 'no proceed found!');
browser.wait(EC.presenceOf(element(by.className('proceed')).click()), timeout, 'no proceed found!');

因为在调用变量时,它只需要在 DOM 中搜索一次元素,之后它会保存它以供以后使用。如果这是真的,这如何工作以及如何"强制"量角器搜索元素?

在量角器中,没有效率增益。量角器不实现任何缓存策略。每次对元素调用某些操作(如 click() 方法)时,它每次都会出去并找到该元素。不过,当您声明变量而不是每次都重复它时,它看起来更好,并且使您的测试更易于维护。

如果您好奇,量角器中的缓存版本如下所示:

element(by.className('proceed')).getWebElement().then(function(proceed) {
    proceed.click().then(function() {
        console.log('clicked proceed the first time');
    }, function() {
        console.log('unable to find proceed the first time (this should not happen)');
    });
    proceed.click().then(function() {
        console.log('clicked proceed the second time (this should not happen)');
    }, function() {
        console.log('unable to find proceed the second time (stale element)');
    });
});