Fake timers
The fake timers may be useful when a piece of code sets a long timeout that we don't want to wait for in a test.
Rstest provides some utility functions to help you fake timers powered by @sinonjs/fake-timers.
rstest.useFakeTimers
- Alias:
rs.useFakeTimers - Type:
(config?: FakeTimerInstallOpts) => Rstest
To enable mocking timers, you need to call this method. It uses @sinonjs/fake-timers under the hood.
You can also pass a configuration object to customize the behavior of the fake timers.
rstest.useRealTimers
- Alias:
rs.useRealTimers - Type:
() => Rstest
Restores the original timer functions (such as setTimeout, setInterval, etc.), disabling the fake timers.
rstest.isFakeTimers
- Alias:
rs.isFakeTimers - Type:
() => boolean
Returns true if fake timers are currently enabled, otherwise false.
rstest.setSystemTime
- Alias:
rs.setSystemTime - Type:
(now?: number | Date) => Rstest
Sets the current system time used by fake timers. Useful for testing code that depends on the current date or time.
rstest.getRealSystemTime
- Alias:
rs.getRealSystemTime - Type:
() => number
Returns the real system time (as a timestamp), even when fake timers are enabled.
rstest.runAllTicks
- Alias:
rs.runAllTicks - Type:
() => Rstest
Runs all queued microtasks (e.g., process.nextTick).
rstest.runAllTimers
- Alias:
rs.runAllTimers - Type:
() => Rstest
Executes all pending timers (both timeouts and intervals).
rstest.runAllTimersAsync
- Alias:
rs.runAllTimersAsync - Type:
() => Promise<Rstest>
Asynchronously executes all pending timers.
rstest.runOnlyPendingTimers
- Alias:
rs.runOnlyPendingTimers - Type:
() => Rstest
Runs only the currently pending timers (does not schedule new ones).
rstest.runOnlyPendingTimersAsync
- Alias:
rs.runOnlyPendingTimersAsync - Type:
() => Promise<Rstest>
Asynchronously runs only the currently pending timers.
rstest.advanceTimersByTime
- Alias:
rs.advanceTimersByTime - Type:
(ms: number) => Rstest
Advances the fake timers by the specified milliseconds, executing any timers scheduled within that time.
rstest.advanceTimersByTimeAsync
- Alias:
rs.advanceTimersByTimeAsync - Type:
(ms: number) => Promise<Rstest>
Asynchronously advances the fake timers by the specified milliseconds.
rstest.advanceTimersToNextTimer
- Alias:
rs.advanceTimersToNextTimer - Type:
(steps?: number) => Rstest
Advances the timers to the next scheduled timer, optionally for a given number of steps.
rstest.advanceTimersToNextTimerAsync
- Alias:
rs.advanceTimersToNextTimerAsync - Type:
(steps?: number) => Promise<Rstest>
Asynchronously advances the timers to the next scheduled timer.
rstest.advanceTimersToNextFrame
- Alias:
rs.advanceTimersToNextFrame - Type:
() => Rstest
Advances the timers to the next animation frame.
rstest.getTimerCount
- Alias:
rs.getTimerCount - Type:
() => number
Returns the number of fake timers still left to run.
rstest.clearAllTimers
- Alias:
rs.clearAllTimers - Type:
() => Rstest
Removes all timers that are scheduled to run.