Monday, October 24, 2016

How to use promise method .then() in Protractor

The hardest part of testing Angular apps using Protractor is promise! Protractor returns no other values than only promises So you may not use the returned value from webdriverJS unless you use .then() method to resolve them first. For example:

var rows = element.all(by.repeater('row in tabledata.display.body'));

You can only use the method expect() to check the value:

expect( rows.count()).toEqual(4);

But you cannot use the value '4' for e.g. in a loop! You have to use the so-called .then() method of promise to resolve, like this:
var rows = element.all(by.repeater('row in tabledata.display.body'));

rows.count().then( function(nrRows) { //nrRows=rows.count()

for(var i=0; i<nrRows; i++){
// do somthing with your loop
  }
})
If you need more than one value, then you may nest the .then() method, like this:
var rows = element.all(by.repeater('row in tabledata.display.body'));

var cells = element.all(by.repeater('cel in row'));

row.count().then( function(nrRows) {      //nrRows=rows.count()

  cells.count().then( function(nrCells){  //nrCells=cells.count()

    for (var i=0; i<nrRows; i++){
       // do something with your loop
    }
    // call a function using nrRows and nrCells

    if( nrRows > 0){
      func(nrRows, nrCells);
    }
    else{
      console.log('No rows in the table!');
    }

  })
})
You may use the method .all() to simplify the code, like this:
var rows = element.all(by.repeater('row in tabledata.display.body'));
 
var cells = element.all(by.repeater('cel in row'));
 
q.all([row.count(), cells.count()]).spread(function(nrRows, nrCells){
 
    for (var i=0; i<nrRows; i++){
       // do something with your loop
    }
    // call a function using nrRows and nrCells
 
    if( nrRows > 0){
      func(nrRows, nrCells);
    }
    else{
      console.log('No rows in the table!');
    }
})
Some similar ideas can be found here.
--- End of blog ---

No comments:

Post a Comment