DEV Community

sagarMehta1907
sagarMehta1907

Posted on

How to resolve async timeout in jest test case for async callback?

How to resolve async timeout in jest test case for function?

I worked with node js and jest test. I am facing issue while execute test case for one function "getValidData()" that function sometimes getting late to provide response. So jest test case was failed and provide error related to below async timeout.

Error : Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

Please refer below for "getValidData()" function and test case for the same.

Actual Function: In data.js file

exports.getValidData = function(){
return new Promise(function(resolve, reject){
    const payloadData = {
        'user_id': userid,
    };

    const res = await fetch('https://<token-url>',{
        method: 'POST',
        headers: {
            'Accept': 'application/json'
        },
        body: new URLSearchParams(payloadData )
    });

    if(res.status != 200){
        reject(res.message);
    }
    let responseData = await res.json();
    resolve(responseData);

});
}
Enter fullscreen mode Exit fullscreen mode

Test Case for Above function:In data.test.js file

const dataTest = require("../data");
it("Test case for function getValidData", async()=>{
   await dataTest.getValidData().then(res => {
       expect(res).not.tobeNull();
   }).catch(err => {

   });
}, 30000);
Enter fullscreen mode Exit fullscreen mode

How can i resolve this issue related to timeout with test case for above "getValidData()" function? Please let me know your thoughts and guidance on how to pass and execute without failed the above test case for "getValidData()" function.

Top comments (2)

Collapse
 
rishabhraghwendra profile image
Rishabhraghwendra18

Did you got the solution ?

Collapse
 
paularah profile image
Paul Arah

Please share if you d have a solution