我正在尝试为我的 express 服务器设置 jasmine 测试。我正在根据每个规范启动一个新服务器,并尝试在每个规范完成后将其关闭。不幸的是,服务器似乎并没有关闭……因此无法运行多个规范。
服务器.js:
var app = require('express')();
exports.start = function(config){
if(!this.server){
app.get('/', function(req, res){
res.status(200);
res.end();
})
this.server = app.listen(config.port, function(){
console.log('Server running on port %d', config.port);
});
}
};
exports.close = function(){
this.server.close();
}
路由规范.js:
var server = require('./path/to/server.js');
var http = require('http');
describe('express server', function () {
beforeEach(function () {
server.start({port: 8000});
});
afterEach(function () {
server.close();
});
describe('/', function () {
it('should return 200', function (done) {
http.get('http://localhost:8000', function (res) {
expect(res.statusCode).toBe(200);
done();
});
});
});
});
第一个规范按预期通过,但终端从未完成测试(即:服务器仍在运行)并且添加的任何后续测试都会导致抛出“ECONNREFUSED”。
最佳答案
您可以使用 npm 模块 server-destroy . server-destroy 跟踪所有连接,然后在调用 destroy 时关闭它们。此外,destroy 方法需要一个回调,所以你应该将你的“完成”函数传递给你的 destroy 方法......下面是从 npm 模块描述中复制的,并在 destroy 调用中添加了一个回调。
var enableDestroy = require('server-destroy');
var server = http.createServer(function(req, res) {
// do stuff, blah blah blah
});
server.listen(PORT);
// enhance with a 'destroy' function
enableDestroy(server);
// some time later...
server.destroy(done);
如果打开的连接不是问题,您可以简单地将 done 函数传递给关闭函数 server.close(done),如本文 How to correctly unit test Express server 中所述
关于node.js - 运行 jasmine 规范后关闭快速服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23230217/