'How to use Jest global Setup and Teardown in a nodeJS project?

I added tests to my node js project using jest but for each test suite there's a beforeAll method that creates a new test server and connects to a mongo database and an afterAll method that closes both test server and the database. I would like to perform the above tasks globally for all the test suites not one at a time. Below is a sample of my code.

app.js

const express = require("express");
const app = express();
const { connectToDb } = require("./startup/db");
require("./startup/routes")(app);
connectToDb();
...

const port = process.env.PORT || 3000;

if (process.env.NODE_ENV !== "test") {
  app.listen(port, () => winston.info(`Listening on port ${port}...`));
}

module.exports = app;

auth.test.js

const request = require("supertest");
const http = require("http");
const { disconnectDb } = require("../../startup/db");

describe("auth middleware", () => {
  let server;

  beforeAll((done) => {
    const app = require("../../app");
    server = http.createServer(app);
    server.listen(done);
  });

  afterAll((done) => {
    server.close(done);
    disconnectDb();
  });

  it("should return 401 if no token is provided", async () => {
    const res = request(server)
      .post("/api/genres")
      .set("x-auth-token", "")
      .send({ name: "genre1" });
    expect(res.status).toBe(401);
  });

...

jest.config.js

module.exports = {
  testEnvironment: "node",
};


Solution 1:[1]

Try with this jest.config.js:

module.exports = {
  testEnvironment: "node",
  globalSetup: '<rootDir>/src/testSetup.ts'
};

And in testSetup.ts you can do:

// testSetup.ts
module.exports = async () => {
    const app = require("../../app");
    server = http.createServer(app);
    server.listen(done);
};

Solution 2:[2]

use this config: setupFiles: ['./tests/setup.js']

your setup file should look like this:

// setup.js
(async () => {
  const app = require('../app.js')
  global.app = app
})()

then you will be able to use app globally in every test suite

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alecu Marian Alexandru
Solution 2 M. Emre Yalç?n