嵌套的promise返回undefined

时间:2015-07-14 08:59:45

标签: javascript promise protractor chai cucumberjs

我尝试使用Protractor和chai-as-promise来编写带有cucumber.js的测试。

在我的Page对象中,我有这些代码片段:

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

并在我的步骤定义代码中执行:

$(".selector option").each(function(){
    $(this).attr('data-img-src', function() {
      var file = this.value + '.png';
      var img = file.toLowerCase().replace(/ /g, '-');
      var path = 'path to folder';
      return path+img
    });
});

当我运行此测试时,我得到了

  

预期未定义为真

这意味着isMenuListed方法返回undefined而不是true。但是,我调试了它,我可以看到'返回true;'声明已经执行。

在这种情况下,我是否遗漏了承诺如何运作?

1 个答案:

答案 0 :(得分:1)

或者,您也可以在此处申请reduce()

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

这里的缺点是我们遍历menusOnListElements中的每个元素,如果找到匹配的菜单,则不会停止。除此之外,reduce()将通过truefalse来解决,其中定义了是否列出了菜单。

相关问题