Skip to content

Timeout – Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout – How to fix?

Timeout – Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout – This error will be thrown if an async method invocation takes more that 5 seconds.

Advertisements

I have been using Jest.js to test my Node backend and I faced this error when I tried to log result of find() method in a Mongoose model

BookSchema.statics = {

    filter(query){
       console.log(this.find(query)); //This takes more than 5000 milliseconds
       return this.find(query);
    },

    apply(aggregate){
        console.log("AGGR  -- " + JSON.stringify(aggregate));
        return this.aggregate(aggregate);
    },

    insert(book){
        return this.create(book);
    },

    createMany(books) {
        this.insertMany(books);
    }

}

To fix this error, you might not want to log something that takes more time to respond.

Or you can increase the timeout value for your jest test cases.

beforeAll(async () => {
  jest.setTimeout(10000);
await dbHandler.connect();
})

You can also use the package.json to set jest timeout value.

"setupFilesAfterEnv": ["./src/jest/setTimeout.js"],
Advertisements
//setTimeout.js
jest.setTimeout(30000)

Keep in mind that the above solutions set the timeout value globally.

If you want to assign timeout value for a specific test cases that you think might take more time to run, you can do it like the one below.

it('getBooks - Huge data', () => {...}, 30000)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.