4

I am trying to write my first test using Protractor+Jasmine for my non Angular application.

I need call API function of my app global instance, get result and compare it in test. One of passed in parameters for this function is a callback which is called as soon as data are ready. This function is executed some time depend on configuration of app.

I tried to resolve promise object inside this callback function and handle it in test. This is a simplified version of my code and it also doesn't work. Looks like script arguments[0].fulfill("Some data"); is never executed because test was failed by timeout with message:

timed out after 10000msec waiting for spec to complete

describe('Text', function() {
    it('should be displayed on stage with set value', function() {
        var deferred = protractor.promise.defer();
        var promise = deferred.promise;

        promise.then(function (data) {
            console.log(data);
        });

        browser.driver.executeScript('arguments[0].fulfill("Some data");', deferred);
    });
});

Is it at all possible to resolve (fulfill) a promise object inside context of function executeScript()? Are there other ways to handle this issue?

UPD: This code works for me. Thanks!

describe('Text', function() {
    it('should be displayed on stage with set value', function() {
        var deferred = protractor.promise.defer();

        browser.driver.executeAsyncScript(function () {
            var callback = arguments[arguments.length - 1];

            MyApp.apiFunction({
                callback: function (callbackParams) {
                    callback(callbackParams);
                }
            });
        }, function (data) { // Callback
            deferred.fulfill(data);
        }).then(function (result) {
            // Do what you need with data...
            console.log('Result: ', result);
        });
    });
});
Vrednost
  • 43
  • 1
  • 6

2 Answers2

4

executeAsyncScript() is specifically what you need.

Quoting @hankduan from the Understanding execute async script in Selenium topic:

use executeAsyncScript when you care about a return value in a calling script, but that return value won't be available immediately. This is especially necessary if you can't poll for the result, but must get the result using a callback or promise (which you must translate to callback yourself).

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

Jasmine has an async resole called done So if you would pass it as deferred than I think it should work

 it('should be displayed on stage with set value', function(done) {
 browser.driver.executeScript('arguments[0].fulfill("Some data");', function()

    {
 Object.defineProperty(this, "promise", {
          get: function () { done() },
          enumerable: true
      });


done()
});
Dan Kuida
  • 1,017
  • 10
  • 18