简体   繁体   English

嵌套的承诺返回未定义

[英]Nested promise returns undefined

I'm trying to write tests with cucumber.js using Protractor and chai-as-promised. 我正在尝试使用Protractor和chai-as-promised用Cucumber.js编写测试。

In my Page object I have these fragments of code: 在我的Page对象中,有以下代码片段:

var menusOnListElements = element.all(by.repeater('menu in menus').column('menu.name'))

this.isMenuListed = function(menu) {
    return menusOnListElements.each(function(element) {
        return element.getText().then(function (name) {
            if (menu.name === name) {
                return true; //this is executed
            }
        });
    });
};

and in my step definition code I do: 在步骤定义代码中,我执行了以下操作:

var menu = {};
menu.name = 'Abc';
expect(new MenusPage().isMenuListed(menu)).to.eventually.be.true.notify(done);

When I run this test I get 当我运行此测试时,我得到

expected undefined to be true 预期未定义为真

which means that the isMenuListed method returned undefined instead of true. 这意味着isMenuListed方法返回的是undefined而不是true。 However, I debugged it and I can see that 'return true;' 但是,我调试了它,可以看到“返回true”; statement is executed. 语句被执行。

Am I missing something about how promises work in this case? 我在这种情况下是否遗漏了诺言的工作方式?

Alternatively, you can also apply reduce() here: 另外,您也可以在此处应用reduce()

this.isMenuListed = function(menu) {
    return menusOnListElements.reduce(function(acc, element) {
        return element.getText().then(function (name) {
            return acc || menu.name === name;
        }, false);
    });
};

The drawback here is that we go through every single element in the menusOnListElements and don't stop if we find the matching menu. 此处的缺点是我们会遍历menusOnListElements中的每个元素,并且如果找到匹配的菜单就不会停止。 Aside from that, reduce() would resolve here in a true or false which defines if a menu is listed or not. 除此之外, reduce()将在此处以truefalse解析,这定义了是否列出菜单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM