enable
Enables timer mocking for the specified timers.
Note: When you enable mocking for a specific timer, its associated clear function will also be implicitly mocked.
Note: Mocking Date
will affect the behavior of the mocked timers as they use the same internal clock.
Example usage without setting initial time:
import { mock } from 'node:test';
mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 });
The above example enables mocking for the Date
constructor, setInterval
timer and implicitly mocks the clearInterval
function. Only the Date
constructor from globalThis
, setInterval
and clearInterval
functions from node:timers
, node:timers/promises
, and globalThis
will be mocked.
Example usage with initial time set
import { mock } from 'node:test';
mock.timers.enable({ apis: ['Date'], now: 1000 });
Example usage with initial Date object as time set
import { mock } from 'node:test';
mock.timers.enable({ apis: ['Date'], now: new Date() });
Alternatively, if you call mock.timers.enable()
without any parameters:
All timers ('setInterval'
, 'clearInterval'
, 'Date'
, 'setImmediate'
, 'clearImmediate'
, 'setTimeout'
, and 'clearTimeout'
) will be mocked.
The setInterval
, clearInterval
, setTimeout
, and clearTimeout
functions from node:timers
, node:timers/promises
, and globalThis
will be mocked. The Date
constructor from globalThis
will be mocked.
If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is January 1st, 1970, 00:00:00 UTC
. You can set an initial date by passing a now property to the .enable()
method. This value will be used as the initial date for the mocked Date object. It can either be a positive integer, or another Date object.
Since
v20.4.0