我正在尝试编写一个测试,其中检查ng-repeat中的项目数量。之后,我将1个项目添加到ng-repeat中,我想查看旧值+ 1是否等于新值。
这是我的HTML:
<tr ng-repeat="list in listData.myLists">...</tr>
我的测试
describe("list test", function(){
it('Description of the test', function(){
browser.get('app/#/list');
var list = element.all(by.repeater('list in listData.myLists'));
var ammount;
list.count().then(function(c) {
ammount = c;
});
... Here I add an item
var secondAmmount = element.all(by.repeater('list in listData.myLists')).count();
expect(secondAmmount).toEqual(ammount + 1);
});
});
但是我得到的7不等于NaN。
我还试过将list.count()+ 1直接添加到toEquals方法中,但后来我得到一个对象而不是一个数字。
我在这里做错了吗? 感谢您提前提供任何帮助
答案 0 :(得分:9)
是的!绊倒你的是异步编程。测试的问题是测试的后半部分(在Here I add an item
之后)之前评估评估ammount = c;
,因为您的第一个then()
语句仍在等待count()
返回。因此,当expect()
语句被点击时,ammount
仍然没有值,并且添加1就不会有效(因为它仍然为空,至少对于几毫秒)。这很有趣,但这就是承诺如何发挥作用。
以下代码可以解决问题:
describe("list test", function(){
it('Description of the test', function(){
browser.get('app/#/list');
var list = element.all(by.repeater('list in listData.myLists'));
list.count().then(function(amount) {
// ... Here I add an item ...
var secondAmount = element.all(by.repeater('list in listData.myLists')).count();
expect(secondAmount).toEqual(amount + 1);
});
});
});
等待list.count()
承诺在尝试对其返回的值执行某些操作之前(异步)回来是非常重要的。这是then()
声明的用途;它会强制测试的其余部分等待count()
完成。这样一切都按照你期望的顺序发生。
这是必要的,因为您使用的是amount + 1
。量角器的expect()
语句了解如何使用promises,但是如果要修改返回值则不然。我们可以将secondAmount
声明直接放在expect()
语句中而不使用then()
函数,但我们不能将list.count() + 1
放在expect()
语句中。
有关详细信息,请参阅this answer。尝试深入了解Node.JS异步编程和Javascript承诺,它将使您的Protractor生活变得更好!
答案 1 :(得分:1)
量角器元素函数异步运行并返回promises。试试这个...
describe("list test", function() {
it('Description of the test', function () {
browser.get('app/#/list');
element.all(by.repeater('list in listData.myLists')).count()
.then(function (amount) {
// ... Here You add an item
element.all(by.repeater('list in listData.myLists')).count()
.then(function (secondAmount) {
expect(secondAmount).toEqual(amount + 1);
})
})
});
});