How to write a test case for this function in jest

238 views Asked by At

// Code for Timer Function//

 Function startTimer (event)
    {
       var session Timeout= 
       setTimeout (function ()
   {
    Self.postMessage (
   {
        Message:'show dialog'
   };
   );
   },  event.duration);
    }

How to write test case for this ?

1

There are 1 answers

1
Anto P V On

Refer Timer mocks available in Jest

https://jestjs.io/docs/timer-mocks

jest.useFakeTimers();
jest.spyOn(global, 'setTimeout');

test('Timer Function', () => {
  const startTimer  = require('../startTimer ');
  startTimer ();

  expect(setTimeout).toHaveBeenCalledTimes(1);
  expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), event.duration);
});