Search code examples
node.jsmongodbjestjssupertest

Multiple server instance attempts while running jest


Okay, So I've been writing tests for my node.js app using jest and supertest, for every test suite after the first, I'm getting an error Error: listen EADDRINUSE: address already in use :::3000, I believe this is because it attempts to start the server on every test file (I have multiple test files *.test.js in /tests)

The top part before tests are described in each test file looks something like this

const request = require("supertest");
const app = require("../index.js"); // the express server

jest.setTimeout(30000);

let token;

beforeAll(done => {
  request(app)
    .post("/api/users/login")
    .send({
      email: "email here",
      password: "password here"
    })
    .end((err, response) => {
      token = response.body.data; // save the token!
      done();
    });
});

afterAll(done => {
  //logout() //Not implemented yet
  done();
});

/* Test starts here */

So, I need to know how to prevent jest from attempting to initialize multiple instances of my server? is it possible to say have all this code run in a pre-test file or so? is there something I can add to my afterAll to cause it to stop the server so when another test starts it i'm good? Many thanks.


Solution

  • Alrighty, so while removing the connection at each start and using concurrently per @Omar Sherif's answer was a valid workaround I found it unnecessarily complicated, setting up a globalSetup per jest's documentation was also a rather unnecessary hassle.

    A simple solution I found was the following; since running jest sets the NODE_ENV to test, in my index.js folder, instead of just having my server listen to a network port which was unnecessary, I added a very simple if condition.

    if (process.env.NODE_ENV !== "test") {
      app.listen(port, () => console.log(`Server Running on ${port}`));
    }
    

    This seemed to do the trick. Thanks!