量角器 - 在运行时返回未决承诺

时间:2015-07-01 19:32:54

标签: javascript angularjs selenium-webdriver promise protractor

我正在尝试创建一个函数,它将梳理一个元素数组并返回符合条件的第一个实例。

我在测试中的内容是可行

element.all(by.css('_cssSelector_')).filter(function(elms, index) {
        return elms.getAttribute('height').then(function(height) {
            return parseInt(height) > 0;
        });
    }).then(function(validElms) {
         browser.actions().mouseMove(validElms[0]).perform();
    }

...但如果我将其解决,无法正常工作

getValidElm = function() {
    var validElm = element.all(by.css('_cssSelector_')).filter(function (elms, index) {
        return elms.getAttribute('height').then(function (height) {
            return parseInt(height) > 0;
        });
    }).then(function (validElms) {
        return validElms[0];
        });

    return validElm;
}

如果我再跑:

var validElmFromPage = getValidElm();
console.log(validElmFromPage);

我得到:承诺:: 2046 {[[PromiseStatus]]:"待定"}

这指出函数内部的某些内容在使用函数外部之前未解析的问题。在阅读(广泛)通过这里的帖子,甚至这篇精彩的博客文章(http://spin.atomicobject.com/2014/12/17/asynchronous-testing-protractor-angular/)后,我仍然无法弄清楚这笔交易是什么。我知道它很简单,很可能与controlFlow相关吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

让函数返回一个promise。由于filter()返回ElementArrayFinder,您应该可以使用first()

getValidElm = function() {
    return element.all(by.css('_cssSelector_')).filter(function (elms, index) {
        return elms.getAttribute('height').then(function (height) {
            return parseInt(height) > 0;
        });
    }).first();
}

first()会返回ElementFinder,您可以传递给mouseMove()

var elm = getValidElm();
browser.actions().mouseMove(elm).perform();