两个文件使用supertest与mocha导致EADDRINUSE

时间:2013-09-14 12:01:42

标签: javascript node.js unit-testing mocha supertest

我正在使用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错误?

2 个答案:

答案 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之后,我受到了启发,只是将语句移到任何describebefore之外的最顶层,现在测试都没有问题。