Two files using supertest with mocha causing EADDRINUSE

血红的双手。 提交于 2019-12-12 08:16:54

问题


I'm using supertest to unit test my server configurations and route handlers. The server configurations tests are in test.server.js and the route handling tests are in test.routes.handlers.js.

When I run all the test files using mocha ., I get EADDRINUSE. When I run each file individually, everything works as expected.

Both files define and require supertest, request = require('supertest'), and the express server file, app = require('../server.js'). In server.js, the server is started like so:

http.createServer(app).listen(app.get('port'), config.hostName, function () {
  console.log('Express server listening on port ' + app.get('port'));
});

Is there something wrong in my implementation? How can I avoid EADDRINUSE error when running my tests?


回答1:


mocha has a 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.

We use that to start an Express server once (and we use an environment variable so that it runs on a different port than our development server):

before(function () {
  process.env.NODE_ENV = 'test';
  require('../../app.js');
});

(We don't need a done() here because require is synchronous.) This was, the server is started exactly once, no matter how many different test files include this root-level before function.

Try requiring supertest from within a root level before function in each of your files.




回答2:


Answering my own question:

My supertest initialization looks like this:

var app = require('../server.js');
var request = require('supertest')(app);

In test.server.js, I had these require statements directly inside a describe. In test.routes.handlers.js, the statements were inside a before inside a describe.

After reading dankohn's answer, I was inspired to simply move the statements to the very top outside any describe or before and the tests all run without problems now.



来源:https://stackoverflow.com/questions/18801551/two-files-using-supertest-with-mocha-causing-eaddrinuse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!