Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor click through elements and count children

I am experiencing problem with counting child elements while looping through collection of elements and clicking on every element using protractor. I am pretty new to that, and spent much time trying to figure out solution.

My current code looks like this:

function clickThroughElements(elements) {
        var amountOfChildElements = 0;
        for(var i in elements) {
          var element = elements[i];
          element.click();
          element.all(by.css('div')).then(function(elements) {
            amountOfChildElements += elements.length;
          });
        }
        return amountOfChildElements;
      }

Obviously I am getting 0 on return, because increment of amountOfChildElements is happening asynchronously. Can anybody recommend, how to properly return amountOfChildElements?

like image 981
artumi Avatar asked Mar 06 '26 10:03

artumi


1 Answers

You should avoid loops when promises are involved.

One way to get the count would be to first get all the counts as an array of promise with map. Then resolve them with promise.all and aggregate the values with reduce:

function clickThroughElements(elements) {
  var counts = elements.map(e => {
    e.click();
    return e.all(by.css('div')).count();
  });

  return protractor.promise.all(counts).then(values => {
    return values.reduce((acc, value) => acc + value, 0);
  });
}

Usage :

clickThroughElements(elements).then(count => {
    console.log(count);
});
like image 115
Florent B. Avatar answered Mar 07 '26 23:03

Florent B.



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!