Skip to main content
Bun provides fake timers to control time-based operations in your tests. This lets you test timeout, interval, and time-dependent code without waiting for real time to pass.

Basic usage

Use jest.useFakeTimers() to enable fake timers:

Timer APIs

jest.useFakeTimers()

Enables fake timers. All timer APIs will be mocked:
  • setTimeout
  • setInterval
  • setImmediate
  • Date.now()
  • new Date()

jest.useRealTimers()

Restores real timers:

jest.advanceTimersByTime(ms)

Advances all timers by the specified milliseconds:

jest.runAllTimers()

Runs all pending timers until there are no more:
runAllTimers() will cause an infinite loop if you have recurring timers (like setInterval).

jest.runOnlyPendingTimers()

Runs only the timers that are currently pending:

jest.advanceTimersToNextTimer()

Advances timers to the next timer:

jest.clearAllTimers()

Clears all pending timers:

jest.getTimerCount()

Returns the number of pending timers:

Mocking Date

Fake timers also mock Date:

jest.setSystemTime()

Sets the system time:
You can also pass a timestamp:

jest.getRealSystemTime()

Gets the real system time (even with fake timers enabled):

Testing intervals

Testing animations

Test requestAnimationFrame:

Cleanup

Always restore real timers after tests:
Or use beforeEach and afterEach:

Real-world example

Testing a debounce function:

Vitest compatibility

Bun also supports Vitest’s timer APIs:
All jest.* timer methods are available as vi.* as well.