diff --git a/doc/api/test.md b/doc/api/test.md index 573f2da98f9d..25f354dae45e 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -1365,6 +1365,63 @@ test('runs timers as setTime passes ticks', (context) => { }); ``` +### Temporal + +The mock timers API also allows mocking the [`Temporal.Now`][] methods that +read the current time. This is useful for testing code that reads the current +time through the Temporal API instead of the legacy `Date` object. + +Enabling the `'Temporal.Now'` api mocks the following methods: + +* `Temporal.Now.instant()` +* `Temporal.Now.zonedDateTimeISO()` +* `Temporal.Now.plainDateTimeISO()` +* `Temporal.Now.plainDateISO()` +* `Temporal.Now.plainTimeISO()` + +`Temporal.Now.timeZoneId()` is not mocked and keeps returning the actual +system time zone. Only the clock is virtualized, not the time zone. + +**Note:** `Date` and `Temporal.Now` share the same internal mock clock. When +both are mocked, `Date.now()` and `Temporal.Now.instant().epochMilliseconds` +always agree, and advancing the clock with `.tick()` or `.setTime()` advances +both. + +**Note:** The mock clock has millisecond precision, while `Temporal.Instant` +has nanosecond precision. Mocked values are derived from the clock's +millisecond value, so the sub-millisecond digits of +`Temporal.Now.instant().epochNanoseconds` are always zero. + +```mjs +import assert from 'node:assert'; +import { test } from 'node:test'; + +test('mocks Temporal.Now', (context) => { + // Optionally choose what to mock + context.mock.timers.enable({ apis: ['Temporal.Now'], now: 9999 }); + assert.strictEqual(Temporal.Now.instant().epochMilliseconds, 9999); + + // Advance in time will also advance Temporal.Now + context.mock.timers.tick(1); + assert.strictEqual(Temporal.Now.instant().epochMilliseconds, 10000); +}); +``` + +```cjs +const assert = require('node:assert'); +const { test } = require('node:test'); + +test('mocks Temporal.Now', (context) => { + // Optionally choose what to mock + context.mock.timers.enable({ apis: ['Temporal.Now'], now: 9999 }); + assert.strictEqual(Temporal.Now.instant().epochMilliseconds, 9999); + + // Advance in time will also advance Temporal.Now + context.mock.timers.tick(1); + assert.strictEqual(Temporal.Now.instant().epochMilliseconds, 10000); +}); +``` + ## Snapshot testing