Jest: Timer mocks

Write synchronous test for code that uses native timer functions (setTimeoutsetIntervalclearTimeoutclearInterval).

// Enable fake timers
jest.useFakeTimers()

test('kill the time', () => {
  const callback = jest.fn()
  
  // Run some code that uses setTimeout or setInterval
  const actual = someFunctionThatUseTimers(callback)
  
  // Fast-forward until all timers have been executed
  jest.runAllTimers()
  
  // Check the results synchronously
  expect(callback).toHaveBeenCalledTimes(1)
})

Or adjust timers by time with advanceTimersByTime():

// Enable fake timers
jest.useFakeTimers()

test('kill the time', () => {
  const callback = jest.fn()
  
  // Run some code that uses setTimeout or setInterval
  const actual = someFunctionThatUseTimers(callback)
  
  // Fast-forward for 250 ms
  jest.advanceTimersByTime(250)
  
  // Check the results synchronously
  expect(callback).toHaveBeenCalledTimes(1)
})

Use jest.runOnlyPendingTimers() for special cases.

Note: you should call jest.useFakeTimers() in your test case to use other fake timer methods.

Leave a Reply

Your email address will not be published. Required fields are marked *