Take elements while a condition evaluates to true (extending ElementArrayFinder)

后端 未结 2 1506
孤城傲影
孤城傲影 2020-11-29 10:57

We have a menu represented as a ul->li list (simplified):

2条回答
  •  囚心锁ツ
    2020-11-29 11:33

    takewhile() actually worked for me once I removed the protractor.promise = require("q"); from onPrepare() - this was there to replace protractor.promise with q on the fly to be able to use the syntactic sugar like spread() function. Apparently, it is not safe to use q in place of protractor.promise.

    All I have to do now is to add this to onPrepare():

    protractor.ElementArrayFinder.prototype.takewhile = function(whileFn) {
        var self = this;
        var getWebElements = function() {
            return self.getWebElements().then(function(parentWebElements) {
                var list = [];
                parentWebElements.forEach(function(parentWebElement, index) {
                    var elementFinder =
                        protractor.ElementFinder.fromWebElement_(self.ptor_, parentWebElement, self.locator_);
    
                    list.push(whileFn(elementFinder, index));
                });
                return protractor.promise.all(list).then(function(resolvedList) {
                    var filteredElementList = [];
                    for (var index = 0; index < resolvedList.length; index++) {
                        if (!resolvedList[index]) {
                            break;
                        }
                        filteredElementList.push(parentWebElements[index])
                    }
                    return filteredElementList;
                });
            });
        };
        return new protractor.ElementArrayFinder(this.ptor_, getWebElements, this.locator_);
    };
    

    The usage is very similar to filter():

    element.all(by.css("ul li a")).takewhile(function (elm) {
        return elm.getText().then(function (text) {
            return text;
        });
    });
    

    FYI, proposed to make takewhile() built-in.

提交回复
热议问题