栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在循环中使用量角器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在循环中使用量角器

发生这种情况的原因是因为量角器使用了诺言。

阅读https://github.com/angular/protractor/blob/master/docs/control-
flow.md

当基础值准备就绪时

element(by...)
,承诺(即
element.all(by...)
)执行其
then
功能。这意味着首先对所有承诺进行调度,然后
then
在结果准备就绪时运行功能。

当您运行以下命令时:

for (var i = 0; i < 3; ++i) {  console.log('1) i is: ', i);  getPromise().then(function() {    console.log('2) i is: ', i);    someArray[i] // 'i' always takes the value of 3  })}console.log('*  finished looping. i is: ', i);

发生的情况是

getPromise().then(function(){...})
,在答应准备就绪之前立即返回,而没有在内部执行函数
then
。因此,首先循环运行3次,调度所有
getPromise()
调用。然后,随着承诺解决,将
then
运行相应的。

控制台看起来像这样:

1) i is: 0 // schedules first `getPromise()`1) i is: 1 // schedules second `getPromise()`1) i is: 2 // schedules third `getPromise()`*  finished looping. i is: 32) i is: 3 // first `then` function runs, but i is already 3 now.2) i is: 3 // second `then` function runs, but i is already 3 now.2) i is: 3 // third `then` function runs, but i is already 3 now.

那么,如何循环运行量角器?通用的解决方案是关闭。

for (var i = 0; i < 3; ++i) {  console.log('1) i is: ', i);  var func = (function() {    var j = i;     return function() {      console.log('2) j is: ', j);      someArray[j] // 'j' takes the values of 0..2    }  })();  getPromise().then(func);}console.log('*  finished looping. i is: ', i);

但这不是那么好读。幸运的是,你还可以用量角器功能

filter(fn)
get(i)
first()
last()
,和这样一个事实
expect
修补采取的承诺,来处理这个。

回到前面提供的示例。第一个示例可以重写为:

var expected = ['expect1', 'expect2', 'expect3'];var els = element.all(by.css('selector'));for (var i = 0; i < expected.length; ++i) {  expect(els.get(i).getText()).toEqual(expected[i]); // note, the i is no longer in a `then` function and take the correct values.}

第二个和第三个示例可以重写为:

var els = element.all(by.css('selector'));els.filter(function(elem) {  return elem.getText().then(function(text) {    return text === 'should click';  });}).click(); // note here we first used a 'filter' to select the appropriate elements, and used the fact that actions like `click` can act on an array to click all matching elements. The result is that we can stop using a for loop altogether.

换句话说,量角器有很多方法可以迭代或访问元素,

i
因此您无需使用循环和
i
。但是,如果必须使用for循环和
i
,则可以使用闭包解决方案。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/426903.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号