什么是browser.ignore量角器中的同步



我看过很多次人们建议使用的地方:

browser.ignoreSynchronization=true;  // or false

但我不明白我们为什么需要它?

简单的答案是,它使量角器不必等待Angular承诺,例如$http$timeout中的承诺来解决,如果您正在测试$http$timeout期间的行为(例如,"加载"消息),或者测试非Angular站点或页面,例如单独的登录页面,则可能需要这样做。

例如,要测试在请求期间设置加载消息的按钮,可以在获取元素+检查其内容时将其设置为true

element(by.css('button[type="submit"]')).click();
browser.ignoreSynchronization = true;
expect(element(by.css('.message')).getText().toBe('Loading...');    
browser.ignoreSynchronization = false;
expect(element(by.css('.message')).getText().toBe('Loaded'); 

一个更复杂的答案是,将其设置为true意味着对控制流的后续添加/注入不会同时添加browser.waitForAngular。在某些情况下,理解控制流以及何时/如何向其中添加/注入内容很重要。例如,如果使用browser.wait测试多阶段流程,则在测试中的其他函数添加到控制流之后,传递给wait的函数将被注入到控制流中。

element(by.css('button[type="submit"]')).click();
browser.ignoreSynchronization = true;
expect(element(by.css('.message')).getText().toBe('Stage 1');
browser.wait(function () {
   // This function is added to the control flow after the final
   // browser.ignoreSynchronization = false in the test
   // so we need to set it again here 
   browser.ignoreSynchronization = true;
   return element(by.cssContainingText('.message', 'Stage 2')).isPresent().then(function(isPresent) { 
     // Cleanup so later tests have the default value of false
     browser.ignoreSynchronization = false;
     return !isPresent;
   });
});
expect(element(by.css('.message')).getText().toBe('Stage 2');
browser.ignoreSynchronization = false;
expect(element(by.css('.message')).getText().toBe('Stage 3');

使用browser.ignoreSynchronization的一个替代方案是直接访问标准网络驱动程序API

element(by.css('button[type="submit"]')).click();
expect(browser.driver.findElement(by.css('.message')).getText().toBe('Loading...');    
expect(element(by.css('.message')).getText().toBe('Loaded'); 

直接使用驱动程序方法来查找元素意味着系统将尝试查找它们,而无需等待任何正在进行的$http请求完成,就像设置browser.ignoreSynchronization = true一样。

此设置控制量角器是否应等待页面上的角度。它没有被正确地记录下来,但这是代码中的文档字符串:

/**
   * If true, Protractor will not attempt to synchronize with the page before
   * performing actions. This can be harmful because Protractor will not wait
   * until $timeouts and $http calls have been processed, which can cause
   * tests to become flaky. This should be used only when necessary, such as
   * when a page continuously polls an API using $timeout.
   *
   * @type {boolean}
   */

换句话说,如果您针对非角度站点进行测试,请将ignoreSynchronization设置为true。作为一个现实世界的例子,看看我在从有角度的页面打开无角度页面时遇到的一个挑战:点击后打开的无角度页面。

2021答案

browser.ignoreSynchronization现在什么都不是。字面意思是

2018年1月25日,量角器v5.3.0发布时,该命令已被弃用

应使用browser.waitForAngularEnabled()

但它的功能和ignoreSynchronization过去的功能,使Protractor能够内置处理角度应用程序的等待。想象一下,你点击登录按钮,你不需要使用"睡眠10秒"命令,或者"等待加载动画结束"等。所有这些理论上都应该由量角器开箱即用处理

但在现实中,有太多的边缘情况下,你不能依赖它,必须禁用这个功能,因为它会使脚本挂起。这就是await browser.waitForAngularEnabled(false)发挥作用的时候。或await browser.waitForAngularEnabled(true),用于启用

阅读如何使用

最新更新