量角器 Angular 无法获取元素的个数

Protractor Angular cannot get the count of elements

我正在尝试编写一个测试来检查 ng-repeat 中的项目数量。之后,我向那个 ng-repeat 添加了 1 个项目,我想看看旧值+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 方法中,但我得到的是一个对象而不是数字。

我是不是做错了什么? 提前感谢您的帮助

是的!让您感到困惑的是 异步编程。 您测试的问题是测试的后半部分(Here I add an item 之后)在 之前 [=40] 被评估=] 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() 承诺返回(异步),然后再尝试使用它的值 returns 做某事。这就是 then() 语句的作用;它强制测试的其余部分等待 count() 完成。这样一切都会按照您期望的顺序发生。

这是必需的,因为您正在使用 amount + 1。 Protractor 的 expect() 语句了解如何使用承诺,但如果您正在修改 return 值则不会。我们可以将 secondAmount promise 直接放在 expect() 语句中而无需 then() 函数,但我们不能将 list.count() + 1 放在 expect() 语句中。

更多详情,您可以查看this answer。尝试对 Node.JS 异步编程和 Javascript promises 有深刻的理解,这将使您的 Protractor 生活变得更好!

量角器元素 运行 异步运行,return 承诺。试试这个...

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);
                })
        })
    });
});