I'm currently facing a bug that I can't resolve and I have been struggling for some hours.
I'm using the following versions:
Node: 8.11.3
Express: 4.16.3
Jest: 22.2.2
Mongoose: 5.2.3
I'm trying to do some integration tests with jest and I have 2 files with tests.
In each file I wrote the following:
// Create the server before each test.
beforeEach(() => {
server = require('../../index');
});
// Close the server after each test.
afterEach(async () => {
if (server) {
server.close();
}
});
In index.js
I have the following (This is not all the code, but the relevant code for the bug):
// Listen to the server.
const port = config.PORT || process.env.PORT || 3000;
module.exports = app.listen(port, () => {
winston.info(`Listening to port ${port}...`);
});
When I run npm test
I get this exception all the time:
**listen EADDRINUSE :::3000**
10 | // Listen to the server
11 | const port = config.PORT || process.env.PORT || 3000;
> 12 | module.exports = app.listen(port, () => {
13 | winston.info(`Listening to port ${port}...`);
14 | });
15 |
I tried several ways to solve this by adding async await
to beforeEach
and for afterEach
and tried also to put the sever.close in afterAll
and in beforeAll
but still got the same error.
Then, I tried to solve by doing this:
How Do I Shut Down My Express Server Gracefully When Its Process Is Killed?
But again, with no luck.
Finally, when I wrote all the tests in 1 file, it works without this error
. Does anybody know how to solve this? I don't want to write all my integration tests in 1 file..
Thanks!