Two files using supertest with mocha causing EADDRINUSE

断了今生、忘了曾经 提交于 2019-12-03 21:39:23

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.

M.K. Safi

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.

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