我正在使用supertest对我的服务器配置和路由处理程序进行单元测试。服务器配置测试位于test.server.js
,路由处理测试位于test.routes.handlers.js
。
当我使用mocha .
运行所有测试文件时,我得到EADDRINUSE
。当我单独运行每个文件时,一切都按预期工作。
这两个文件都定义并要求supertest,request = require('supertest')
和快速服务器文件app = require('../server.js')
。在server.js
中,服务器启动如下:
http.createServer(app).listen(app.get('port'), config.hostName, function () {
console.log('Express server listening on port ' + app.get('port'));
});
我的实施中有什么问题吗?运行测试时如何避免EADDRINUSE
错误?
答案 0 :(得分:4)
mocha有root Suite:
You may also pick any file and add "root" level hooks, for example add beforeEach() outside of describe()s then the callback will run before any test-case regardless of the file its in. This is because Mocha has a root Suite with no name.
我们使用它来启动Express服务器一次(我们使用环境变量,使其在与开发服务器不同的端口上运行):
before(function () {
process.env.NODE_ENV = 'test';
require('../../app.js');
});
(我们在这里不需要done()
,因为require是同步的。)就是说,服务器只启动一次,无论有多少个不同的测试文件包含此根级{{1}功能。
尝试在每个文件中的函数之前从根级别中要求超级。
答案 1 :(得分:1)
回答我自己的问题:
我的超级初始化看起来像这样:
var app = require('../server.js');
var request = require('supertest')(app);
在test.server.js
中,我在describe
内直接使用了这些必需语句。在test.routes.handlers.js
中,语句位于before
内的describe
内。
在阅读dankohn's answer之后,我受到了启发,只是将语句移到任何describe
或before
之外的最顶层,现在测试都没有问题。