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"
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
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With