Looping elements in WebdriverIO

danielsvane picture danielsvane · Jan 20, 2016 · Viewed 9.6k times · Source

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

garajo picture garajo · Jan 21, 2016
var runner = webdriverjs
.remote(options)
.init()
.url("http://www.google.com")

 // fetch elements
.elements('a', function(err, res){
    // iterate through elements
    res.value.forEach(function(elem) {
        // execute specific action
        runner.elementIdClick(elem.Element, function(err, res) {
             // callback logic here
             // ...
        })
    })
})

from https://github.com/webdriverio/webdriverio/issues/273