23

I am writing a test case for adding store information in the page for Angular app using Protractor, where initially I am counting the number of stores I already have and after the test block is done I expect the count to increase by one so for that I am doing this by following this link of creating promises How to create and manipulate promises in Protractor?

describe('myApp', function() {
  var items,startCount;

  var testPromise = function(){
    items = element.all(by.repeater('store in storelist'));
    var deferred = protractor.promise.defer();
    items.count().then(function(orgCount){
       startCount = orgCount;
       console.log('Start Count: '+ startCount); //prints correct value e.g, 6
    }, function(error){
       console.log(error);
    });
    return deferred.promise;
  };

it('should accept valid data for adding new store', function() {
   var cNum = null;
   testPromise().then(function(result){
      cNum = result;
      console.log('cNUm value: '+ cNum); //this value doesn't get printed in console
   });
   /* Code for adding test fields in store page */

   expect(items.count()).toBe(cNum+1);
 });
});

I expect the store count to be same at the end of the test. count() is resolving a promise and correct value of store count gets printed in testPromise() but in it block when I call testPromise().then method it never goes in that 'then' block

and the end result says

Message:
 Expected 6 to be 1.
 Stacktrace:
  Error: Failed expectation

I also researched a bit more in webdriver.promise.Promise() from this link http://selenium.googlecode.com/git/docs/api/javascript/class_webdriver_promise_Promise.html and tried using that for creating a promise and resolving its value but not sure what the problem is. Either I get error message saying 'expected 6 to be NaN' or 'expected 6 to be 1' Am I not resolving a promise or writing 'then' block correctly? Would appreciate some insights/help on this issue.

Community
  • 1
  • 1
DesaiM
  • 1,385
  • 2
  • 10
  • 14

3 Answers3

48

Creation

For creating a promise in protractor, you have to write:

var deferred = protractor.promise.defer();
var promise = deferred.promise;

Callbacks

The callbacks are invoked asynchronously. You can register one (or more) "on success" callbacks:

promise.then(function() {
   ...
});

you can also register one (or more) "on error" callback:

promise.then(null, function() {
   ...
});

These registrations could be chained:

promise.then(function() {
   ...
}).then(function() {
   ...
}).then(null, function() {
   ...
}).then(function() {

}, function() {
   ...
}).then(onSuccess, onFailure);

Resolution

Success

The "on success" callbacks are invoked when the promise is resolved successfully:

deferred.fulfill(value);

Failure

The "on failure" callbacks are invoked when the promise is resolved successfully:

deferred.reject(new Error('a problem occurs'));

In your code

you missed the resolution step. You have to fulfill the promise.

A more complete reference is available in the Webdriver.js documentation

gontard
  • 28,720
  • 11
  • 94
  • 117
14

Here's a working example of a user-defined function for use in Protractor which creates and fulfills (or rejects) a promise:

// Get the text of an element and convert to an integer.
// Returns a promise.
function getTextAsInteger(element, radix) {
  // Specify a default radix for the call to parseInt.
  radix = radix || 10;
  // Create a promise to be fulfilled or rejected later.
  var deferred = protractor.promise.defer();
  // Get the text from the element. The call to getText
  // returns a promise.
  element.getText().then(
    function success(text) {
      var num = parseInt(text, radix);
      if (!isNaN(num)) {
        // Successfully converted text to integer.
        deferred.fulfill(num);
      } else {
        // Error converting text to integer.
        deferred.reject('could not parse "$1" into an integer'
          .replace('$1', text));
      }
    },
    function error(reason) {
      // Reject our promise and pass the reason from the getText rejection.
      deferred.reject(reason);
    });

  // Return the promise. This will be resolved or rejected
  // when the above call to getText is resolved.
  return deferred.promise;
}

The function takes element as an argument and calls its getText() method which itself returns a promise. On a successful call to getText(), parse the text as an integer and fulfill the promise. If getText() rejects, we pass the reason to our own reject call.

To use this function, pass in an element promise:

var numField = element(by.id('num-field'));
getTextAsInteger(numField).then(
    function success(num) {
        console.log(num);
    }, 
    function error(reason) {
        console.error(reason);
    });

or:

var numField = element(by.id('num-field'));
expect(getTextAsInteger(numField)).toEqual(jasmine.any(Number));
expect(getTextAsInteger(numField)).toBeGreaterThan(0);
t.888
  • 3,862
  • 3
  • 25
  • 31
-2

I got the same issue and solved it by creating a promise for the expected item count:

it('should accept valid data for adding new store', function() {
    // Given
    let expectedCountAfterNewRow = items.count().then((cnt)=>{return cnt+1}); 
    // Note: items.count() is a promise so the expected count should a promise too

    // When
    /* Code for adding test fields in store page */

    // Then
   expect(items.count()).toEqual(expectedCountAfterNewRow);
});
Julien Kronegg
  • 4,968
  • 1
  • 47
  • 60