简体   繁体   中英

Nested promise returns undefined

I'm trying to write tests with cucumber.js using Protractor and chai-as-promised.

In my Page object I have these fragments of code:

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. However, I debugged it and I can see that 'return true;' statement is executed.

Am I missing something about how promises work in this case?

Alternatively, you can also apply reduce() here:

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. Aside from that, reduce() would resolve here in a true or false which defines if a menu is listed or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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