Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion docs/api/vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -1159,7 +1159,7 @@ await vi.runOnlyPendingTimersAsync()
function setSystemTime(date: string | number | Date): 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.*` calls.
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.

Expand Down
9 changes: 9 additions & 0 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,15 @@ Temporal.Now.instant().epochMilliseconds // 0 (was the real time in v4)
vi.useFakeTimers({ toNotFake: ['Temporal'] })
```

### `setSystemTime` Now Mocks Temporal

Previously `vi.setSystemTime` mocked only `Date` without fake timers, but now it also mocks methods of `Temporal.Now`.

```ts
vi.setSystemTime(0)
Temporal.Now.instant().epochMilliseconds // 0 (was the real time in v4)
```

### `toThrow("")` Matches Any Error Message

[`toThrow`](/api/expect#tothrow) (and its alias `toThrowError`) treats a string argument as a substring of the error message. In Vitest 4 an empty string was special-cased to the `/^$/` pattern, so it matched only an error whose message was empty. It now behaves like any other substring, and an empty string is contained in every message:
Expand Down
4 changes: 3 additions & 1 deletion docs/guide/mocking.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ Don't forget that this only [mocks _external_ access](/guide/mocking/modules#moc

### Mock the current date

To mock `Date`'s time, you can use `vi.setSystemTime` helper function. This value will **not** automatically reset between different tests.
To mock `Date` and `Temporal`'s time, you can use `vi.setSystemTime` helper function. This value will **not** automatically reset between different tests.

Beware that using `vi.useFakeTimers` also changes the `Date`'s time.

Expand All @@ -180,6 +180,8 @@ const mockDate = new Date(2022, 0, 1)
vi.setSystemTime(mockDate)
const now = new Date()
expect(now.valueOf()).toBe(mockDate.valueOf())
const nowInstant = Temporal.Now.instant()
expect(nowInstant.epochMilliseconds).toBe(mockDate.valueOf())
// reset mocked time
vi.useRealTimers()
```
Expand Down
70 changes: 70 additions & 0 deletions packages/vitest/src/integrations/mock/temporal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
let now: number | undefined

let RealTemporal: typeof Temporal | undefined
let MockedTemporal: typeof Temporal | undefined

function currentZonedDateTime(
RealTemporal: typeof Temporal,
currentTime: number,
timeZoneLike: any,
): Temporal.ZonedDateTime {
const timeZone = timeZoneLike === undefined ? RealTemporal.Now.timeZoneId() : timeZoneLike
return RealTemporal.Instant.fromEpochMilliseconds(currentTime).toZonedDateTimeISO(timeZone)
}

function createMockedTemporal(RealTemporal: typeof Temporal): typeof Temporal {
const propertyDescriptors = Object.getOwnPropertyDescriptors(RealTemporal)
propertyDescriptors.Now.value = {
timeZoneId: RealTemporal.Now.timeZoneId,
instant() {
if (now !== undefined) {
return RealTemporal.Instant.fromEpochMilliseconds(now)
}
return RealTemporal.Now.instant()
},
zonedDateTimeISO(timeZoneLike?: any) {
if (now !== undefined) {
return currentZonedDateTime(RealTemporal, now, timeZoneLike)
}
return RealTemporal.Now.zonedDateTimeISO(timeZoneLike)
},
plainDateTimeISO(timeZoneLike?: any) {
if (now !== undefined) {
return currentZonedDateTime(RealTemporal, now, timeZoneLike).toPlainDateTime()
}
return RealTemporal.Now.plainDateTimeISO(timeZoneLike)
},
plainDateISO(timeZoneLike?: any) {
if (now !== undefined) {
return currentZonedDateTime(RealTemporal, now, timeZoneLike).toPlainDate()
}
return RealTemporal.Now.plainDateISO(timeZoneLike)
},
plainTimeISO(timeZoneLike?: any) {
if (now !== undefined) {
return currentZonedDateTime(RealTemporal, now, timeZoneLike).toPlainTime()
}
return RealTemporal.Now.plainTimeISO(timeZoneLike)
},
[Symbol.toStringTag]: 'Temporal.Now',
}
const MockedTemporal = {} as typeof Temporal
Object.defineProperties(MockedTemporal, propertyDescriptors)
return MockedTemporal
}

export function mockTemporal(date: Date): void {
now = date.valueOf()
RealTemporal = globalThis.Temporal as typeof Temporal | undefined
if (RealTemporal !== undefined) {
MockedTemporal ??= createMockedTemporal(RealTemporal)
globalThis.Temporal = MockedTemporal
}
}

export function resetTemporal(): void {
now = undefined
if (RealTemporal !== undefined) {
globalThis.Temporal = RealTemporal
}
}
4 changes: 4 additions & 0 deletions packages/vitest/src/integrations/mock/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
import { withGlobal } from '@sinonjs/fake-timers'
import { isChildProcess } from '../../runtime/utils'
import { mockDate, RealDate, resetDate } from './date'
import { mockTemporal, resetTemporal } from './temporal'

export class FakeTimers {
private _global: typeof globalThis
Expand Down Expand Up @@ -135,6 +136,7 @@ export class FakeTimers {
useRealTimers(): void {
if (this._fakingDate) {
resetDate()
resetTemporal()
this._fakingDate = null
}

Expand All @@ -148,6 +150,7 @@ export class FakeTimers {
const fakeDate = this._fakingDate || Date.now()
if (this._fakingDate) {
resetDate()
resetTemporal()
this._fakingDate = null
}

Expand Down Expand Up @@ -199,6 +202,7 @@ export class FakeTimers {
else {
this._fakingDate = date ?? new Date(this.getRealSystemTime())
mockDate(this._fakingDate)
mockTemporal(this._fakingDate)
}
}

Expand Down
47 changes: 47 additions & 0 deletions test/unit/test/temporal-mock.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { afterEach, describe, expect, it, vi } from 'vitest'

// use polyfill for node < 26
if (!globalThis.Temporal) {
await import('temporal-polyfill/global')
}

describe('testing Temporal mock functionality', () => {
afterEach(() => {
vi.useRealTimers()
})

it('setting time', () => {
const date = new Date(2000, 0, 1)
vi.setSystemTime(date)

expect(Temporal.Now.instant().epochMilliseconds).toEqual(date.getTime())
expect(Temporal.Now.zonedDateTimeISO().epochMilliseconds).toEqual(date.getTime())
expect(Temporal.Now.plainDateISO()).toEqual(Temporal.PlainDate.from('2000-01-01'))
expect(Temporal.Now.plainDateTimeISO()).toEqual(Temporal.PlainDateTime.from('2000-01-01T00:00:00'))
expect(Temporal.Now.plainTimeISO()).toEqual(Temporal.PlainTime.from('00:00:00'))

vi.useRealTimers()

expect(Temporal.Now.instant().epochMilliseconds).not.toEqual(date.getTime())
expect(Temporal.Now.zonedDateTimeISO().epochMilliseconds).not.toEqual(date.getTime())
expect(Temporal.Now.plainDateISO()).not.toEqual(Temporal.PlainDate.from('2000-01-01'))
expect(Temporal.Now.plainDateTimeISO()).not.toEqual(Temporal.PlainDateTime.from('2000-01-01T00:00:00'))
expect(Temporal.Now.plainTimeISO()).not.toEqual(Temporal.PlainTime.from('00:00:00'))
})

it('getting current date in the specific time zone', () => {
vi.setSystemTime(new Date('2000-01-01T00:00:00Z'))

const timeZone = 'America/Los_Angeles'
const timeZoneLike = new Temporal.ZonedDateTime(0n, timeZone)

for (const tz of [timeZone, timeZoneLike]) {
expect(Temporal.Now.zonedDateTimeISO(tz)).toEqual(
Temporal.ZonedDateTime.from('1999-12-31T16:00:00-08:00[America/Los_Angeles]'),
)
expect(Temporal.Now.plainDateISO(tz)).toEqual(Temporal.PlainDate.from('1999-12-31'))
expect(Temporal.Now.plainDateTimeISO(tz)).toEqual(Temporal.PlainDateTime.from('1999-12-31T16:00:00'))
expect(Temporal.Now.plainTimeISO(tz)).toEqual(Temporal.PlainTime.from('16:00:00'))
}
})
})
Loading