Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and manipulate promises in Protractor?

I want to use the Node Http module to call my server directly in order to set up my Protractor tests. Http is callback based and I want to turn that into promises.

For example, I want to have this function return promise:

function callMyApi() {
  var promise = // somehow create promise;

  http.request({path: '/yada/yada', method: 'POST'}, function(resp) {
    promise.complete(resp);
  });

  return promise;
}

So, the question is: what do I need to require() and put in place of "somehow create promise" for this to work?

like image 529
Konrad Garus Avatar asked Jan 10 '14 22:01

Konrad Garus


2 Answers

Protractor uses WebDriver's promises and exposes that API globally on 'protractor'. So you should be able to do

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

For the full WebDriverJS Promise API, see the code at https://code.google.com/p/selenium/source/browse/javascript/webdriver/promise.js

like image 176
Jmr Avatar answered Oct 15 '22 05:10

Jmr


This is the wrong way to do this, but knowing about the Protractor Control Flow could help. If you want regular Javascript run in Protractor order add it through the control flow.

In this case you could use your own promise library if you want then just use browser.wait to wait for your promises to complete.

var Promise = require('bluebird');
var promises = [];
browser.controlFlow().execute(function() {
    var p = new Promise...
    promises.push(p);
});
browser.wait( function(){ return Promise.all(promises); }, timeoutMs );

I use this not for regular promises, but for console.log statements or doing timing for a part of a test, or even using fs to print something in a test to a file.

var startTime, duration; 
browser.controlFlow().execute(function() {
    startTime = new Date().getTime();
});
//Protractor code you want timed
browser.controlFlow().execute(function() {
    duration = new Date().getTime() - startTime;
    console.log("Duration:", duration);
});
like image 2
mvndaai Avatar answered Oct 15 '22 06:10

mvndaai