Home > Software design >  Jest testing :mockResolveValue with delay
Jest testing :mockResolveValue with delay

Time:12-22

How to mockReturnValue with delay in jest testing?

The intention of this test is to mock method as unsettled on flushpromise. Let's say,

  • If we have promise which is mocked on test class. Once flushpromise , It would resolve the promise and we can able to assert the statement either as resolved or rejected.
  • Requirement for testclass is that the promise shouldn't be resolved or rejected after flushpromise (test Unsettled).

There are two possible way , we can achieve this by

  1. making mockReturnValue return empty promise.
  2. using jeskfaketimer to delay the mockReturnvalue

Both the above option is expected to give unsettled promise on assertion.

Although, The second option doesn't seem working with following code. Any input is appreciated.

Tried the following code.

`

import callout from ".../callout.."

jest.mock(
"../callout..",
()=>{
    return{
         default:jest.fn(),
         };
    },
    {virtual: true}
);

const { setImmediate } = require("timers");

function flushPromises()
{
return new Promise((resolve)=> setImmediate(resolve));
}


`it("test delay", async()=>{
       jest.useFakeTimers();
       callout.mockResolvedValue(()=> Promise(resolve=>setTimeout(()=>resolve(),2000)));
       jest.advanceTimersByTime(20);
       await flushpromises();
       expect(callout).not.toHavebeencalled();
       jest.advanceTimersByTime(2000);
       expect(callout).toHavebeencalled();


});

`

CodePudding user response:

Hope this helps someone, I am able to solve the issue with following change. Basically replaced the setTimeout with wait custom function as shown below. Happy coding!!

```
 import callout from ".../callout.."

 jest.mock(  "../callout..",()=>{
           return{
               default:jest.fn(),
                 };
              },
         {virtual: true}
        );

     const { setImmediate } = require("timers");

     function flushPromises()
      {
        return new Promise((resolve)=> setImmediate(resolve));
      }


  it("test delay", async()=>{
   jest.useFakeTimers();
   let response= {statusCode : 200, 
           JSON.stringify({status:200,data:true})};
   callout.mockReturnValueOnce(wait(2000,respone);
   jest.advanceTimersByTime(20);
   await flushpromises();
   expect(callout).not.toHavebeencalled();
   jest.advanceTimersByTime(2000);
   expect(callout).toHavebeencalled();
  });

 function wait(ms,value)
 {
  return new Promise(resolve => setTimeout(resolve,ms,value));
  • Related