Search code examples
node.jsunit-testingjestjsintegration-testing

Alternative to using jest.setTimeout


Currently I've some tests (Jest + Supertest) configured in my NodeJS/Express/MongoDB app. From my experience is can greatly differ when the server actually connects successfully with MongoDB (could take a couple of seconds).

My test where failing because it timed out after 5000ms (I believe this is Jests default timeout).

I was able to bypass this by defining a jest.setTimeout(15000) in the first part of the test which all together looks like this:

test('POST' + endpointUrl, async () => {
    jest.setTimeout(15000);

    const response = await request(app)
        .post(endpointUrl)
        .send(newTodo);

    ASSERTIONS
});

I'm wondering if this was the right way to solve my issue.


Solution

  • If you have an async function and must wait for the response, just use the done keyword as the test callback parameter.

    test('POST' + endpointUrl, async (done) => {
        const response = await request(app)
            .post(endpointUrl)
            .send(newTodo);
    
        ASSERTIONS
        
        done();
    });
    

    Or:

    test('POST' + endpointUrl, done => {
        request(app)
            .post(endpointUrl)
            .send(newTodo)
            .then(res => {
                ASSERTIONS
                done();
            })
            .catch(error => {
                fail(`It must be done, but catched because of: ${error}`);
            })
    });
    

    For more information, just check this topic: Testing Asynchronous Code