1

I am trying to create a helper function that makes an async call which is a part of my data setup for the protactor test. is there a way i can wait for the response of the function and then proceed with the tests, here is what I am trying to do.

so basically the test should wait until the async call lo loaddata() is finished. I have read about use of promises but couldn't get to implement it sucessfully.

"use strict";

describe('sample passing test spec', function() {
describe('sample passing test suite', function() {
  loaddata();
    it('sample passing test', function () {
    datall();
        expect("1").toEqual("2");
    });
    });
});



loaddata() is basically making a socket connection 

function loaddata(){
var net = require('net');

var client = new net.Socket();
client.connect(20000, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client\n');
});


client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});

client.on('close', function() {
console.log('Connection closed');
});

return "function execution over"

}
vin7787
  • 13
  • 2
  • In Javascript, you cannot "wait" for an async operation to be done. You can either schedule a callback to be called or return a Promise that will trigger it's `.then()` handler when the event is done. Other code will continue to run while the async operation is doing its thing. You can't wait in Javascript. Probably worth reading this [How do I return a response from an asynchronous operation?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – jfriend00 Jan 24 '16 at 02:01

1 Answers1

2

You would need to tweak loaddata to return a promise which would Protractor put on the Control Flow - a queue of pending promises to resolve:

function loaddata() {
    var deferred = protractor.promise.defer();
    var net = require('net');

    var client = new net.Socket();
    client.connect(20000, '127.0.0.1', function() {
        console.log('Connected');
        client.write('Hello, server! Love, Client\n');
    });


    client.on('data', function(data) {
        console.log('Received: ' + data);
        client.destroy(); // kill client after server's response
        deferred.fulfill(true);
    });

    client.on('close', function() {
    console.log('Connection closed');
    });

    return deferred.promise;
}

If this is something you need to do globally before your test run, put it into onPrepare() and return. If loaddata returns a promise, Protractor would first resolve it and only then run tests:

onPrepare: function () { 
    return loaddata();
},
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195