Ad

Wait For Response From Async , Protractor, Nodejs

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"

}
Ad

Answer

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();
},
Ad
source: stackoverflow.com
Ad