17

I got an array of promises from this code: element.all(by.repeater('unit in units')), and I am finding it really difficult to get the data into another array:

element.all(by.repeater('unit in units')).then(function (arr) {
    var items = [];

    for (var i = 0; i < arr.length; i++) {
      arr[i].getText().then(function(text) {
        items.push(text);
      });
    }

   //PROBLEM ITEMS is Empty
   console.log(items);
});
e-shfiyut
  • 3,538
  • 2
  • 30
  • 31
Acosta
  • 1,057
  • 1
  • 10
  • 22

3 Answers3

33

Managed to get the same result on a simpler way avoiding using Q and the repeater. Using the inbuilt map does the trick.

var tabs = element.all(by.css('.unitTabs li a')).map(function (elm) {
    return elm.getText();
});

tabs.then(function (result) {
    var sorted = _.sortBy(result, function (name) { return name; });
    for (var i = 0; i < result.length; i++) {
        expect(result[i]).toBe(sorted[i]);
    }
});
Andy
  • 17,423
  • 9
  • 52
  • 69
Acosta
  • 1,057
  • 1
  • 10
  • 22
  • 3
    I'm glad that someone is using my map implementation! – Andres D Feb 13 '14 at 15:07
  • 1
    Thanks Andres, quite handy util, do you have any kind of blog/wiki were we can see some more detail about that pleas? the reason I asked if because I found it hanging in and test somewhere on the web rather than a proper documentation – Acosta Feb 14 '14 at 10:16
  • 1
    You could also use ```protractor.promise.all```, see http://spin.atomicobject.com/2014/12/17/asynchronous-testing-protractor-angular/ – user1613512 Feb 11 '15 at 07:43
  • What one should expect in `tabs` map, what is the key what is the value? Could you please add it to answer? – Yoda Aug 07 '17 at 13:32
8

Fixed using Q

var Q = require('q');

element.all(by.repeater('unit in units')).then(function (arr) {
    var promises = [];
    for (var i = 0; i < arr.length; i++) {
        promises.push(arr[i].getText());
    }

    Q.all(promises).done(function (result) {
        // print the results when the lookups and processing are done                
        console.log(result.length);
        console.log(result);                
    });
});
Andy
  • 17,423
  • 9
  • 52
  • 69
Acosta
  • 1,057
  • 1
  • 10
  • 22
2

npm Q is the first thing to do then use requirejs on top of your script like that

      var Q = require('q');

      element.all(by.repeater('object in objects')).then(function (arr) {
          var promises = [];
          for (var i = 0; i < arr.length; i++) {
              promises.push(arr[i].getText());
          }

          Q.all(promises).done(function (result) {
              // print the results when the lookups and processing are done
              console.log(result.length);
              console.log(result);
          });
      });

BTW I think my second option it is cleaner.

Acosta
  • 1,057
  • 1
  • 10
  • 22