4

I'm struggling with this:

  • Click a button to get a set of data
  • Check the number of rows returned is what I'm expecting
  • I need to run this 10 times, each time, I'm expecting a different number of rows

The code snippet below doesn't work because 'i' isn't what I'm expecting. How can I make this work?

for (var i = 0; i < subElements.length; ++i) {
    element(by.id('get-data')).click();

    // Check users returned
    element.all(by.id('users')).map(function (elm) {
        return elm;
    }).then(function (users) {
        expect(users.length).toBe(expectedRecords[i]);
        // Some more checks to be added later
    });
}
Jason
  • 1,787
  • 4
  • 29
  • 46
  • possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Benjamin Gruenbaum Jan 06 '15 at 16:55
  • What is `subElements`? Could you show the relevant HTML code? I think this can be solved differently in a protractor-style :) – alecxe Jan 07 '15 at 15:18
  • I solved this by creating a helper function. In the main function, I run thru the for loop, calling the helper function. The helper function does the checks. Don't this is a clean way of doing it so I didn't post, but it's working for now. – Jason Jan 07 '15 at 15:20

2 Answers2

2

What about:

for (var i = 0; i < subElements.length; ++i) {
    element(by.id('get-data')).click();

    var count = element.all(by.id('users')).count();
    expect(count).toBe(expectedRecords[i]);
}

As long as you aren't accessing i in a then, it will be what you want, otherwise i will the the last value in your loop and you'll need closure.

EDIT: see Using protractor with loops

Community
  • 1
  • 1
hankduan
  • 5,994
  • 1
  • 29
  • 43
0

Using bluebird

var Promise = require('bluebird');

it('my test', function(done){
  var promises = subElements.map(function(subElm, i){
    return element(by.id('get-data')).click()
      .then(function(){
        // Check users returned
        return element.all(by.id('users')).map(function (elm) {
          return elm;
        })
      })
      .then(function(users) {
        expect(users.length).toBe(expectedRecords[i]);
      });
  });

  Promise.all(promises).nodeify(done);
})
Bulkan
  • 2,555
  • 1
  • 20
  • 31