问题来自sn-p下面,第一个console.log()是同步执行的,但是第二个console.log()会异步执行,因为它在getText().then()里面,我们知道所有的Protractor api都是异步并返回一个 Promise。
for (var i in fields) {
console.log(i);
fields[i].getText().then(function(fieldValue) {
console.log(i);
所以上面for循环的实际执行过程应该是这样的:
when i=1
first console.log() execute done, it print out 1
fields[i].getText() execute done, it return a Promise,
and push the promise into Protractor control flow,
actually getText() not to read the text from page,
because it's execute async.
when i=2
first console.log() execute done, it print out 2
fields[i].getText() execute done, it return a Promise,
and push the promise into Protractor control flow,
actually getText() not to read the text from page,
because it's execute async.
....
when i=10
the loop end,
you get 1, 2 .. 9, 10 printed out
Protractor control flow get a promise queue
Now Protractor control flow start to execute the promise queue
Protractor push out the fist promise in queue
Important!!! the i=10 now
fields[i].getText() will be fields[10].getText()
so you will get fields[10].getText() for 10 times
选项 1) 正如 Jamines 评论所说,使用 javascript 闭包,对您当前的代码进行一些更改
element(by.repeater(cat in cats).column(cat.name)).then(function(fields) {
for (var i in fields) {
console.log(i);
(function(index){ // change part
fields[index].getText().then(function(fieldValue) {
console.log(index);
if(fieldValue === 'Meow') {
var catAge= element(by.repeater('cat in cats').row(index)).element(by.model('cat.age'));
expect(catAge.getAttribute('value')).toBe('10');
}
})
})(i); // change part
}
});
选项2使用量角器filter()
element(by.repeater(cat in cats).column(cat.name)).then(function(fields) {
for (var i in fields) {
console.log(i);
var matchedIndex = -1;
fields
.filter(function(item, index){
if( matchedIndex > -1) {
// means had found the matched one, directly return false to
// skip read text from page to reduce exection time
return false;
}
else {
return item.getText().then(function(name){
if(name === 'Meow') {
matchedIndex = index;
return true;
}
return false;
})
}
})
.then(function(){
console.log('matchedIndex: ' + matchedIndex);
var catAge= element(by.repeater('cat in cats').row(matchedIndex)).element(by.model('cat.age'));
return expect(catAge.getAttribute('value')).toBe('10');
});
}
});