Multiple server instance attempts while running jest

夙愿已清 提交于 2021-01-29 06:33:15

问题


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.


回答1:


the problem is here

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

Everytime you try to require the index.js you technically copy paste all the code from inside index.js to your test script.

Since you run multiple test files at the same time, each test attempts to run the same code inside index.js

You can read more on this http://fredkschott.com/post/2014/06/require-and-the-module-system/




回答2:


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!



来源:https://stackoverflow.com/questions/55440614/multiple-server-instance-attempts-while-running-jest

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