Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test millisecods argument on setTimeout with jest

I have a method to trigger a pause using a promise with a setTimeout:

pause = ({ time } = {}) => {
  const pauseTime = time || 500;

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, pauseTime)
  })
}

I want to test it with jest, expecting the timeout function gets the time argument that pause method receives.

jest.useFakeTimers();

const setTimeoutSpy = spyOn(window, 'setTimeout')
const pausePromise = pause({ time: 2500 })


await jest.runAllTimers();

pausePromise.then(() => {
  expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
  expect(setTimeoutSpy).toHaveBeenCalledWith(2500);
})

jest.useRealTimers();
return pausePromise

I tried with mocks and spies. Also tried without timers and awaiting the promise. But I always get the same result: Expected spy to have been called one time, but it was called zero times.

Any idea?

Thanks!

like image 885
Rodrigo Avatar asked Sep 20 '25 09:09

Rodrigo


1 Answers

Finally I found the issue. It was a problem with the spy implementation:

  1. I was doing spyOn(... instead of jest.spyOn(...
  2. I changed the object I was spying on from window to global

Thanks all for your comments!

like image 187
Rodrigo Avatar answered Sep 23 '25 00:09

Rodrigo