预期失败:"Expected [ ] to be empty array."

Failed expectation: "Expected [ ] to be empty array."

这是失败的测试:

describe("Checking errors", function () {
    var scope = {};

    beforeEach(function () {
        browser.get("/#endpoint");
        browser.waitForAngular();

        scope.page = new MyPage();
    });

    it("should not show any errors", function () {
        expect(scope.page.errors).toBeEmptyArray();
    });
});

其中 MyPage 是一个 页面对象:

var MyPage = function () {
    this.errors = element.all(by.css("div.error-block b.error"))
        .filter(function (elm) {
            return elm.isDisplayed().then(function (value) {
                return value;
            });
        })
        .map(function (elm) {
            return elm.getText();
        });
};

module.exports = MyPage;

其中 errors 应该是在页面上找到的可见错误文本数组

这是我们得到的错误:

Failures:

  1) Checking errors should not show any errors
   Message:
     Expected [  ] to be empty array.
   Stacktrace:
     Error: Failed expectation

仅供参考,toBeEmptyArray() 匹配器来自 jasmine-matchers 第三方。


我试过用这种方式打印出 scope.page.errors 的值:

scope.page.errors.then(function (errors) {
    console.log(errors);
});

并打印为[]Array.isArray(errors) returns true.

据我所见,scope.page.errors是一个空数组,但预期失败。我少了什么?

答案在 protractor src 中向下四行。

ElementArrayFinder extends Promise,而 jasmine-matchers 检查 first checks that errors is an actual array exactly how Array.isArray is done ,这将 return false;

这也与 expect(scope.page.errors.length).toBe(0) 未定义一致,因为 promise 没有长度。

只是 运行 errors.then 你的承诺,并测试参数是 [] 您还证明了 运行 scope.page.errors.then

可以做到这一点
Inside test script your code line "scope.page = new MyPage();" is creating new empty MyPage object.Code which you have written in application script is creating page object locally and its not bounded with any angular scope.When there is requirement of testing such objects you need to replicate code for page object creation in beforeEach(); block of test script.And test it.
 describe("Checking errors", function () {
    var scope = {};
     var MyPage ;
    beforeEach(function () {
        browser.get("/#endpoint");
        browser.waitForAngular();

       MyPage = function () {
    this.errors = element.all(by.css("div.error-block b.error"))
        .filter(function (elm) {
            return elm.isDisplayed().then(function (value) {
                return value;
            });
        })
        .map(function (elm) {
            return elm.getText();
        });
};
    });

    it("should not show any errors", function () {
        expect(MyPage.errors).toBeEmptyArray();
    });
});