creating and resolving promises in protractor

后端 未结 3 2001
抹茶落季
抹茶落季 2020-12-05 07:36

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 aft

3条回答
  •  佛祖请我去吃肉
    2020-12-05 08:13

    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);
    

提交回复
热议问题