1 javascript angularjs protractor
我正在尝试编写一个测试,在那里我检查ng-repeat中的项目数量.之后我将1个项目添加到ng-repeat中,我想查看旧值+ 1是否等于新值.
这是我的HTML:
<tr ng-repeat="list in listData.myLists">...</tr>
Run Code Online (Sandbox Code Playgroud)
而我的测试
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);
});
});
Run Code Online (Sandbox Code Playgroud)
但我得到的7不等于NaN.
我还尝试将list.count()+ 1直接添加到toEquals方法中,但后来我得到一个对象而不是一个数字.
我有什么问题吗?在此先感谢您的帮助
Isa*_*man 10
是的!绊倒你的是异步编程.您的测试的问题是在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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
list.count()在尝试使用它返回的值执行某些操作之前,等待承诺返回(异步)非常重要.这就是then()声明的用途; 它迫使测试的其余部分等待count()完成.这样一切都按照你期望的顺序发生.
这是必要的,因为您正在使用amount + 1.量角器的expect()语句理解如何使用promises,但是如果要修改返回值则不然.我们可以secondAmount在expect()没有then()函数的情况下将promise直接放在语句中,但是我们不能把它list.count() + 1放在expect()语句中.
有关详细信息,您可以看到此答案.尝试深入了解Node.JS异步编程和Javascript承诺,它将使您的Protractor生活变得更好!