等待Async,Protractor,nodejs的响应

时间:2016-01-24 01:11:11

标签: javascript node.js sockets asynchronous protractor

我正在尝试创建一个辅助函数,该函数进行异步调用,这是我的protactor测试数据设置的一部分。有没有办法我可以等待函数的响应然后继续测试,这是我想要做的。

所以基本上测试应该等到异步调用lo loaddata()完成。我已经阅读过有关承诺的使用,但无法成功实施。

"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"

}

1 个答案:

答案 0 :(得分:2)

你需要调整loaddata返回一个承诺,这将是Protractor放在Control Flow上的 - 一系列未决承诺要解决:

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

如果您需要在测试运行之前全局执行此操作,请将其放入onPrepare()并返回。如果loaddata返回一个承诺,Protractor将首先解析它,然后才运行测试:

onPrepare: function () { 
    return loaddata();
},