Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 709
danielsvane Avatar asked May 30 '26 20:05

danielsvane


2 Answers

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

like image 73
garajo Avatar answered Jun 01 '26 10:06

garajo


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);
    });
like image 26
danielsvane Avatar answered Jun 01 '26 09:06

danielsvane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!