Node.js 相当新
制作了一个运行服务器进程并提供文件的应用程序(不使用 express 或任何框架),现在我正在尝试对其进行单元测试。
我正在尝试为此使用 mocha 测试...我打算启动我的服务器进程,然后针对它运行请求以测试预期结果(统计代码、正文内容等)
但是它不能正常工作,所有请求都无法连接到服务器......我很确定问题是因为节点正在运行一个进程循环,当查询运行时服务器没有“在后台”运行或者可能在发出请求时服务器尚未运行(启动 ASYNC)?
无论如何,我想知道测试这个的正确方法是什么,我假设我需要让服务器在后台运行(如分叉进程)和/或我可能需要找到一种方法来等待服务器进程先“起来”,但不确定如何。
或者至少建议测试此类服务器进程(使用 Mocha 或其他)。
谢谢。
这是示例测试代码(自原始问题以来已更新)
var server = new Server302('./fixture/');
var instance;
describe('Tests', function() {
before(function(done) {
instance = http.createServer(function(request, response) {
console.log(request.url);
server.serve(request, response);
}).listen(8000);
instance.on("listening", function() {
console.log("started");
done();
});
});
after(function(done){
instance.close();
console.log("stopped");
done();
});
it("Should fetch test.html", function(done) {
console.log("test1");
http.get("http://localhost:8000/", function(res) {
res.on('data', function(body) {
console.log(body)
expect(body).toEqual("test");
done();
});
})
});
它似乎按顺序执行,但仍然因连接错误而失败,而在使用浏览器手动测试时它可以工作:
started
test1
․․․stopped
✖ 1 of 1 tests failed:
1) Tests Should fetch test.html:
Error: connect ECONNREFUSED
at errnoException (net.js:670:11)
at Object.afterConnect [as oncomplete] (net.js:661:19)