How to delay variable getting set in Protractor

时间:2015-10-30 21:53:34

标签: selenium protractor

eventArray = element.all(by.css('.icon-event'));
console.log(eventArray.length);
randomNum = Math.floor(Math.random() * eventArray.length);
eventArray.get(randomNum).click();

I'm trying to pick a random element to click, but it seems like protractor is immediately setting the variable to undefined when the test runs. It doesn't wait until eventArray is built before trying to set randomNum.

Does anyone know how to instruct protractor to wait for the eventArray to build before setting randomNum? It seems like the math functions are being called immediately.

1 个答案:

答案 0 :(得分:1)

All locators return a promise, and the then function can reference the element(s) that were found. Your code can be changed to this:

element.all(by.css('.icon-event'))
.then(function(eventArray){
    console.log(eventArray.length);
    randomNum = Math.floor(Math.random() * eventArray.length);
    eventArray.get(randomNum).click();
});