Node.js相当新的
制作了一个运行服务器进程并提供文件的应用程序(不使用express或任何框架),现在我正在尝试对其进行单元测试.
我正在尝试使用mocha测试......我打算启动我的服务器进程,然后针对它运行请求以测试预期结果(统计代码,正文内容等)
但是它无法正常工作,所有请求都无法连接到服务器...我很确定问题是因为节点是juts运行一个进程循环,服务器在运行查询时没有"在后台运行"或者在发出请求时服务器还没有运行(启动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();
});
})
});
Run Code Online (Sandbox Code Playgroud)
它似乎按顺序执行但仍然因连接错误而失败,而在使用浏览器手动测试时它可以正常工作:
started
test1
???stopped
? 1 of 1 tests failed:
1) Tests Should fetch test.html:
Error: connect ECONNREFUSED
at errnoException (net.js:670:11) …Run Code Online (Sandbox Code Playgroud)