如何让Protractor推迟Promise工作?

时间:2015-07-17 09:14:00

标签: javascript promise protractor

场景1)陈旧元素参考错误

it("should have all elements", function (done) {
    var def = protractor.promise.defer();
    var prm = browser.findElements(by.css("jive")).then((elements) => {           
        elements.forEach((ele) => {
            var id = ele.getId();
            var loc = ele.getLocation();
            var inner = ele.getInnerHtml();
            var text = ele.getText();
            var tag = ele.getTagName();
        }); 
        def.then((wtf) => {
            debugger;
        });      
    });      
    done();
});

我认为上面的代码在对所有元素进行迭代后会在队列上有大量的promise。但是当def.then语句运行时,Selenium告诉我我有Stale Elements。迭代正在运行该css的元素。

我希望为迭代请求的所有内容获得一系列已解决的承诺......

场景2)提供过时的元素参考

var promises = Array<webdriver.promise.Promise<any>>();
var allElements: webdriver.IWebElement[] = [];
it("should have all elements", function (done) {
    var alllinks: webdriver.WebElement[];
    browser.controlFlow().execute(() => {
        browser.findElements(by.tagName("a")).then((works) => {
            alllinks = works;
            alllinks.forEach((ele) => {
                promises.push(ele.getAttribute("href"));
                promises.push(ele.getId());
                promises.push(ele.getInnerHtml());
                promises.push(ele.getLocation());
            });
            //getting stale reference here...
            protractor.promise.all(promises).then((wtf) => {
                debugger;
            });

            debugger;
        });
    });

请告知。

2 个答案:

答案 0 :(得分:0)

我认为你需要map()

var links = element.all(by.tagName("a")).map(function (link) {
    return {
        href: link.getAttribute("href"),
        id: link.getId(),
        innerHTML: link.getInnerHtml(),
        location: link.getLocation()
    }
});

现在links将包含一个解析为对象数组的promise。

答案 1 :(得分:-1)

我的小例子可能对你有所帮助:

viewBookingDetailsPage.roomtypeAttributeForParticularDay = function (day, roomTypeNumber, selector) {
    var deferred = protractor.promise.defer();
    element.all(by.repeater(viewBookingDetailsPage.guestroomInfo.allDays)).then(function (days) {
        days[day].all(by.repeater(viewBookingDetailsPage.guestroomInfo.roomTypesInDay)).then(function (roomTypes) {
            deferred.fulfill(roomTypes[roomTypeNumber].$(selector));
        });
    });
    return deferred.promise;
};

在承诺成功解决后,您需要使用fulFill返回结果。