两个文件使用超级摩擦引起EADDRINUSE摩卡
我使用supertest来unit testing我的服务器configuration和路由处理程序。 服务器configurationtesting在test.server.js
,路由处理testing在test.routes.handlers.js
。
当我使用mocha .
运行所有的testing文件mocha .
,我得到EADDRINUSE
。 当我单独运行每个文件时,一切都按预期工作。
这两个文件定义并要求supertest, request = require('supertest')
和express服务器文件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')); });
我的实现有什么问题吗? 运行testing时如何避免EADDRINUSE
错误?
摩卡有一个套件 :
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服务器一次(并且我们使用一个环境variables,以便它运行在与我们的开发服务器不同的端口上):
before(function () { process.env.NODE_ENV = 'test'; require('../../app.js'); });
(因为require是同步的,所以在这里我们不需要done()
。)这就是服务器启动一次,不pipe有多less个不同的testing文件包含这个根级别before
函数。
尝试在每个文件的函数之前从根级别请求supertest。
回答我自己的问题:
我最超级初始化看起来像这样:
var app = require('../server.js'); var request = require('supertest')(app);
在test.server.js
,我直接在describe
有这些require语句。 在test.routes.handlers.js
,这些语句是在一个describe
before
的。
在阅读了Dankohn的回答之后 ,我的灵感就是将陈述简单地移动到任何describe
或before
的最高层,现在testing都毫无问题地运行。