danielsvane danielsvane - 3 months ago 41
Node.js Question

Looping elements in WebdriverIO

I'm trying to loop through a list of links, and perform some actions with each one. I can iterate the elements using elements, but using click inside the forEach doesn't block the next step in forEach, and Selenium goes nuts, as it tries to continue doing actions on elements not in the DOM anymore.

var q = require("q");
var webdriverio = require('webdriverio');
var options = {
desiredCapabilities: {
browserName: 'chrome'
}
};

var clicks = [];

var runner = webdriverio.remote(options);

runner
.init()
.url('https://www.google.dk/search?q=burrito')
.elements(".r").then(function(res){
res.value.forEach(function(elem){
console.log(elem);
clicks.push(
runner
.elementIdClick(elem.ELEMENT)
.pause(5000)
.back()
.pause(2000)
);
});

return q.all(clicks);
});


How do I make sure the next iteration in the forEach doesn't run before all the code is executed inside the forEach?

Edit: I should have mentioned that I already tried https://github.com/webdriverio/webdriverio/issues/941 and https://github.com/webdriverio/webdriverio/issues/273. I updated my code sample with something more specific.

Answer

As per this response from the creator of WebdriverIO, the correct way to loop through some links and click them:

runner
    .init()
    .url('https://www.google.dk/search?q=burrito')
    .getText(".r").then(function(res){
        console.log(res);
        res.forEach(function(elem){
            console.log(elem);
            clicks.push(
                runner
                    .click('=' + elem)
                    .back()
            );
        });

        return q.all(clicks);
    });
Comments