'Import a file after the Jest environment has been torn down

I'm making a simple API with Express and I'm trying to add tests with Jest but when I try to run the tests it displays the next error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at BufferList.Readable (node_modules/readable-stream/lib/_stream_readable.js:179:22)
      at BufferList.Duplex (node_modules/readable-stream/lib/_stream_duplex.js:67:12)
      at new BufferList (node_modules/bl/bl.js:33:16)
      at new MessageStream (node_modules/mongodb/lib/cmap/message_stream.js:35:21)
      at new Connection (node_modules/mongodb/lib/cmap/connection.js:52:28)
/home/jonathangomz/Documents/Node/Express/Devotionals/node_modules/readable-stream/lib/_stream_readable.js:111
  var isDuplex = stream instanceof Duplex;
                        ^

TypeError: Right-hand side of 'instanceof' is not callable

I'm not sure to trust the result if right after jest break (or something like that): enter image description here

My test is:

const app = require("../app");
const request = require("supertest");

describe("Testing root router", () => {
  test("Should test that true === true", async () => {
    jest.useFakeTimers();
    const response = await request(app).get("/");
    expect(response.status).toBe(200);
  });
});

My jest configuration on package.json:

"jest": {
    "testEnvironment": "node",
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ]
  }

Notes:

I read about jest.useFakeTimers() but It's not working and I'm not sure if I'm using in the wrong way. I also tried adding it to the beforeEach method but nothing.



Solution 1:[1]

Try adding --testTimeout=10000 flag when calling jest, it works for me.

Information based on Testing NodeJs/Express API with Jest and Supertest

--testTimeout flag - This increases the default timeout of Jest which is 5000ms. This is important since the test runner needs to refresh the database before running the test

Solution 2:[2]

By adding jest.useFakeTimers() just after all your import.

What about making your test async ?

const app = require("../app");
const request = require("supertest");

describe("Testing root router",async () => {
  test("Should test that true === true", async () => {
    jest.useFakeTimers();
    const response = await request(app).get("/");
    expect(response.status).toBe(200);
  });
});

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 SikoraWojciech
Solution 2 Alexis G