'Test Suite Failed to run

Error

thrown: "Exceeded timeout of 5000 ms for a hook. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

  24 |
> 25 | afterAll(async () => {
     | ^
  26 |     jest.setTimeout(20000);
  27 |     await mongo.stop();
  28 |     await mongoose.connection.close();

  at Object.<anonymous> (src/test/setup.ts:25:1)
  at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)

Test Code

setup.test.ts

import { MongoMemoryServer } from 'mongodb-memory-server';
import mongoose from 'mongoose';
import { app } from '../app';

let mongo: any;

beforeAll(async () => {
    jest.setTimeout(10000);
    process.env.JWT_KEY = 'asdfasd';
    mongo = await MongoMemoryServer.create();
    const uri = await mongo.getUri();

    await mongoose.connect(uri);
});

beforeEach(async () => {
    jest.setTimeout(10000);
    const collections = await mongoose.connection.db.collections();

    for(let collection of collections){
        await collection.deleteMany({});
    }
});

afterAll(async () => {
    jest.setTimeout(20000);
    await mongo.stop();
    await mongoose.connection.close();
})

dependencies

"mongodb-memory-server": "^8.0.4", "@types/jest": "^27.0.3", "supertest": "^6.1.6", "ts-jest": "^27.1.2"



Solution 1:[1]

The timeout is referring to the the test taking longer than 5000 ms.

You can set the test timeout programmatically although I don't think this can be done within a test (as you've shown above) it would need to be done in a global setup file like jest.setup.js

Alternateively, I would suggest setting the timeout in your jest.config.js

example:

{
  "name": "my-project",
  "jest": {
    "verbose": true,
    "testTimeout": 5000
  }
}

Solution 2:[2]

I had the same issue and I solved it without editing the config file. What I did is, I added as a second argument a new timeOut as you can see below:

afterAll(async () => {
// your code here 
// your code here 
}, 100000)

Solution 3:[3]

I had the same issue, and as Cody mentioned, by increasing the "testTimeout" in my Jest config file, I managed to overcome this error.

Hope this helps other people encountering this error, thank you very much

My config file:

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  },
  "verbose": true,
  "testTimeout": 1000000
}

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 Cody
Solution 2 Yaakov Abramovich
Solution 3 Yakoub.