Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/api/vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -1172,14 +1172,14 @@ await vi.runOnlyPendingTimersAsync()
### vi.setSystemTime

```ts
function setSystemTime(date: string | number | Date): Vitest
function setSystemTime(date: string | number | Date | Temporal.Instant | Temporal.ZonedDateTime): Vitest
```

If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers. If fake timers are not enabled, this method will only mock `Date.*` and `Temporal.Now.*` calls.

Useful if you need to test anything that depends on the current date - for example [Luxon](https://github.com/moment/luxon/) calls inside your code.

Accepts the same string and number arguments as the `Date`.
Accepts the same string and number arguments as the `Date`, or a `Temporal.Instant` or `Temporal.ZonedDateTime`. Vitest uses the moment represented by a `ZonedDateTime` as the mocked time and leaves the environment's time zone unchanged.

```ts
const date = new Date(1998, 11, 19)
Expand All @@ -1202,6 +1202,8 @@ To enable mocking timers, you need to call this method. It will wrap all further

Mocking `nextTick` is not supported when running Vitest inside `node:child_process` by using `--pool=forks`. NodeJS uses `process.nextTick` internally in `node:child_process` and hangs when it is mocked. Mocking `nextTick` is supported when running Vitest with `--pool=threads`.

The `now` option accepts a `Date`, number, `Temporal.Instant`, or `Temporal.ZonedDateTime`. Vitest uses the moment represented by a `ZonedDateTime` as the mocked time and leaves the environment's time zone unchanged.

The implementation is based internally on [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).

::: tip
Expand Down
18 changes: 16 additions & 2 deletions packages/vitest/src/integrations/mock/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
FakeMethod,
Config as FakeTimersConfig,
FakeTimers as FakeTimersContext,
TemporalTimelike,
} from '@sinonjs/fake-timers'
import { withGlobal } from '@sinonjs/fake-timers'
import { isChildProcess } from '../../runtime/utils'
Expand Down Expand Up @@ -192,8 +193,12 @@ export class FakeTimers {
}
}

setSystemTime(now?: string | number | Date): void {
const date = typeof now === 'undefined' || now instanceof Date ? now : new Date(now)
setSystemTime(now?: string | number | Date | TemporalTimelike): void {
const normalized = normalizeSystemTime(now)
const date =
typeof normalized === 'undefined' || normalized instanceof Date
? normalized
: new Date(normalized)
if (this._fakingTime) {
this._clock.setSystemTime(date)
} else {
Expand Down Expand Up @@ -261,3 +266,12 @@ export class FakeTimers {
return this._fakingTime
}
}

// Like fake-timers, read epochMilliseconds from Instant or ZonedDateTime without requiring built-in Temporal types.
function normalizeSystemTime(
time?: string | number | Date | TemporalTimelike,
): string | number | Date | undefined {
return time && typeof time === 'object' && 'epochMilliseconds' in time
? time.epochMilliseconds
: time
}
6 changes: 3 additions & 3 deletions packages/vitest/src/integrations/vi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Config as FakeTimersConfig } from '@sinonjs/fake-timers'
import type { Config as FakeTimersConfig, TemporalTimelike } from '@sinonjs/fake-timers'
import type {
MaybeMocked,
MaybeMockedDeep,
Expand Down Expand Up @@ -93,7 +93,7 @@ export interface VitestUtils {
* If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers.
* If fake timers are not enabled, this method will only mock `Date.*` and `new Date()` calls.
*/
setSystemTime: (time: number | string | Date) => VitestUtils
setSystemTime: (time: number | string | Date | TemporalTimelike) => VitestUtils
/**
* Returns mocked current date. If date is not mocked the method will return `null`.
*/
Expand Down Expand Up @@ -577,7 +577,7 @@ function createVitest(): VitestUtils {
return timers().getTimerCount()
},

setSystemTime(time: number | string | Date) {
setSystemTime(time: number | string | Date | TemporalTimelike) {
timers().setSystemTime(time)
return utils
},
Expand Down
24 changes: 24 additions & 0 deletions test/unit/test/timers-temporal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,27 @@ it('Temporal.Now follows setSystemTime without fake timers', () => {
expect(globalThis.Temporal).toBe(real)
expect(globalThis.Temporal.Now.instant().epochMilliseconds).not.toBe(1234)
})

it('setSystemTime accepts Temporal.Instant and Temporal.ZonedDateTime', () => {
vi.setSystemTime(globalThis.Temporal.Instant.fromEpochMilliseconds(1234))
expect(Date.now()).toBe(1234)
expect(globalThis.Temporal.Now.instant().epochMilliseconds).toBe(1234)

vi.useFakeTimers()
vi.setSystemTime(
globalThis.Temporal.ZonedDateTime.from('2022-02-02T17:30:00+05:30[Asia/Kolkata]'),
)
expect(new Date().toISOString()).toBe('2022-02-02T12:00:00.000Z')
})

it('useFakeTimers accepts Temporal as now', () => {
vi.useFakeTimers({ now: globalThis.Temporal.Instant.fromEpochMilliseconds(1234) })
expect(Date.now()).toBe(1234)
expect(globalThis.Temporal.Now.instant().epochMilliseconds).toBe(1234)

vi.useRealTimers()
vi.useFakeTimers({
now: globalThis.Temporal.ZonedDateTime.from('2022-02-02T17:30:00+05:30[Asia/Kolkata]'),
})
expect(new Date().toISOString()).toBe('2022-02-02T12:00:00.000Z')
})
Loading