使用mocha对nodejs(connect)应用程序进行http请求测试?

时间:2012-07-02 10:49:42

标签: http node.js testing connect mocha

我想为我的连接中间件编写一些集成测试,并使用真实的http请求而不是模拟的请求来测试它。

中间件堆栈的行为有所不同,具体取决于传递的配置,这就是为什么我想将中间件服务器作为子进程运行,我可以在每次测试后以不同的配置重新启动。

问题是测试服务器运行没有问题(以太网直接启动或在测试文件中启动)并且可以通过浏览器访问,但是我没有通过http.get(..)获得响应,因为连接是拒绝了。

Error: connect ECONNREFUSED

这是我的设置......

//MOCHA TEST FILE: testServer.test.js

function runTestServer(configEnv) {

    var cmd = "node " + path.resolve(__dirname, "runTestServer.js");

    var testSrv = exec(cmd, { "env" : configEnv },
    function (error, stdout, stderr) {
        if (error !== null) {
            console.log('exec error: ' + error);
        }
    });

    return testSrv;
}


describe("onRequest", function(){
    it("should return a response", function (done) {

        this.timeout(100000);

        var serverInstance = runTestServer({
            "appDir" : path.resolve(__dirname, "../../handleHttp/app")
        });

        http.get({host:'localhost', port:9090, path:'/'}, function (res) {
            //error thrown before this callback gets called
        });

    });
});

这是我作为子进程运行的testServer.js文件的内容。

//Test-Process-File: runTestServer.js
var connect = require("connect"),
handleHttp = require("...")

var server = connect();
handleHttp.init(server); //this methods applies the middleware
console.log("TEST-SERVER listening on 9090");
server.listen(9090);

1 个答案:

答案 0 :(得分:0)

我在发布问题时想出了这个问题,想在这里回答,以防其他人遇到同样的问题。

那么问题是什么?

整个事情都是异步的!

因此,在向服务器发出请求之前,不会初始化服务器。

解决方案

给子进程一些时间来初始化并使testServer-Loader异步!

function runTestServer(configEnv, callback) {

    var cmd = "node " + path.resolve(__dirname, "../runTestServer.js"),
    testSrv;

    testSrv = exec(cmd, { "env" : configEnv },
                 function (error, stdout, stderr) {
                   if (error !== null) {
                     console.log('exec error: ' + error);
                  }
              });

    setTimeout(function() {
        callback(testSrv);
    }, 1000);
}

我的mocha-test-file:

describe("handleHttp", function() {
  describe("#Basic Requesting", function() {

    var serverInstance;

    before(function(done) {
        runTestServer({
            "appDir" : path.resolve(__dirname, "...")
        }, function(srvInstance) {
            serverInstance = srvInstance;
            done();
        });
    });

    //run your tests here 

固定超时不是一个很好的解决方案。也许可以在主进程和子进程之间启用一些通信,以便找出http服务器何时就绪。建议表示赞赏。