Skip to content

Commit bbf2f0d

Browse files
BPScotthi-ogawacodex
authored
fix(deps): update fake-timers to 15.3.2. support toNotFake (#10043)
Co-authored-by: Hiroshi Ogawa <hi.ogawa.zz@gmail.com> Co-authored-by: Codex <noreply@openai.com>
1 parent c36cc5b commit bbf2f0d

12 files changed

Lines changed: 160 additions & 64 deletions

File tree

‎docs/api/vi.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1051,7 +1051,7 @@ vi.useRealTimers()
10511051
### vi.useFakeTimers
10521052

10531053
```ts
1054-
function useFakeTimers(config?: FakeTimerInstallOpts): Vitest
1054+
function useFakeTimers(config?: FakeTimersConfig): Vitest
10551055
```
10561056

10571057
To enable mocking timers, you need to call this method. It will wrap all further calls to timers (such as `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `setImmediate`, `clearImmediate`, and `Date`) until [`vi.useRealTimers()`](#vi-userealtimers) is called.
@@ -1065,6 +1065,16 @@ The implementation is based internally on [`@sinonjs/fake-timers`](https://githu
10651065
But you can enable it by specifying the option in `toFake` argument: `vi.useFakeTimers({ toFake: ['nextTick', 'queueMicrotask'] })`.
10661066
:::
10671067

1068+
You can use `toFake` to specify which timers to mock, or `toNotFake` to specify which timers to keep native. Note that `toFake` and `toNotFake` cannot be specified together.
1069+
1070+
```ts
1071+
// only mock setTimeout and clearTimeout
1072+
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
1073+
1074+
// mock all timers except setInterval
1075+
vi.useFakeTimers({ toNotFake: ['setInterval'] })
1076+
```
1077+
10681078
### vi.setTimerTickMode <Version>4.1.0</Version> {#vi-settimertickmode}
10691079

10701080
- **Type:** `(mode: 'manual' | 'nextTimerAsync') => Vitest | (mode: 'interval', interval?: number) => Vitest`

‎docs/config/faketimers.md‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ outline: deep
55

66
# fakeTimers
77

8-
- **Type:** `FakeTimerInstallOpts`
8+
- **Type:** `FakeTimerConfig`
99

1010
Options that Vitest will pass down to [`@sinon/fake-timers`](https://npmx.dev/package/@sinonjs/fake-timers) when using [`vi.useFakeTimers()`](/api/vi#vi-usefaketimers).
1111

@@ -21,12 +21,23 @@ Installs fake timers with the specified Unix epoch.
2121
- **Type:** `('setTimeout' | 'clearTimeout' | 'setImmediate' | 'clearImmediate' | 'setInterval' | 'clearInterval' | 'Date' | 'nextTick' | 'hrtime' | 'requestAnimationFrame' | 'cancelAnimationFrame' | 'requestIdleCallback' | 'cancelIdleCallback' | 'performance' | 'queueMicrotask')[]`
2222
- **Default:** everything available globally except `nextTick` and `queueMicrotask`
2323

24-
An array with names of global methods and APIs to fake.
25-
26-
To only mock `setTimeout()` and `nextTick()`, specify this property as `['setTimeout', 'nextTick']`.
24+
An array with names of global methods and APIs to fake. For example, to only mock `setTimeout()` and `nextTick()`, specify this property as `['setTimeout', 'nextTick']`.
2725

2826
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`.
2927

28+
## fakeTimers.toNotFake
29+
30+
- **Type:** `('setTimeout' | 'clearTimeout' | 'setImmediate' | 'clearImmediate' | 'setInterval' | 'clearInterval' | 'Date' | 'nextTick' | 'hrtime' | 'requestAnimationFrame' | 'cancelAnimationFrame' | 'requestIdleCallback' | 'cancelIdleCallback' | 'performance' | 'queueMicrotask')[]`
31+
- **Default:** `[]`
32+
33+
An array with names of global methods and APIs to keep native. All other available timers will be mocked. For example, to keep `setInterval()` native and mock all other timers, specify this property as `['setInterval']`.
34+
35+
Mocking `nextTick` is not supported when running Vitest inside `node:child_process` by using `--pool=forks`. When running with `--pool=forks`, Vitest automatically adds `nextTick` to the `toNotFake` array.
36+
37+
::: warning
38+
Using both `toFake` and `toNotFake` together is not supported.
39+
:::
40+
3041
## fakeTimers.loopLimit
3142

3243
- **Type:** `number`

‎packages/vitest/package.json‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,15 +192,14 @@
192192
"@edge-runtime/vm": "^5.0.0",
193193
"@jridgewell/trace-mapping": "catalog:",
194194
"@opentelemetry/api": "^1.9.0",
195-
"@sinonjs/fake-timers": "15.0.0",
195+
"@sinonjs/fake-timers": "15.3.2",
196196
"@types/estree": "catalog:",
197197
"@types/istanbul-lib-coverage": "catalog:",
198198
"@types/istanbul-reports": "catalog:",
199199
"@types/jsdom": "^27.0.0",
200200
"@types/node": "^24.12.0",
201201
"@types/picomatch": "^4.0.2",
202202
"@types/prompts": "^2.4.9",
203-
"@types/sinonjs__fake-timers": "^15.0.1",
204203
"@vitest/expect": "workspace:*",
205204
"@vitest/snapshot": "workspace:*",
206205
"acorn": "8.11.3",

‎packages/vitest/src/defaults.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ export const configDefaults: Readonly<{
8888
include: never[]
8989
}
9090
coverage: CoverageOptions
91-
fakeTimers: import('@sinonjs/fake-timers').FakeTimerInstallOpts
91+
fakeTimers: import('@sinonjs/fake-timers').Config
9292
maxConcurrency: number
9393
dangerouslyIgnoreUnhandledErrors: boolean
9494
typecheck: {

‎packages/vitest/src/integrations/mock/timers.ts‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,18 @@
66
*/
77

88
import type {
9-
FakeTimerInstallOpts,
10-
FakeTimerWithContext,
11-
InstalledClock,
9+
Clock,
10+
FakeMethod,
11+
Config as FakeTimersConfig,
12+
FakeTimers as FakeTimersContext,
1213
} from '@sinonjs/fake-timers'
1314
import { withGlobal } from '@sinonjs/fake-timers'
1415
import { isChildProcess } from '../../runtime/utils'
1516
import { mockDate, RealDate, resetDate } from './date'
1617

1718
export class FakeTimers {
1819
private _global: typeof globalThis
19-
private _clock!: InstalledClock
20+
private _clock!: Clock
2021
// | _fakingTime | _fakingDate |
2122
// +-------------+-------------+
2223
// | false | falsy | initial
@@ -25,16 +26,16 @@ export class FakeTimers {
2526
// | true | truthy | unreachable
2627
private _fakingTime: boolean
2728
private _fakingDate: Date | null
28-
private _fakeTimers: FakeTimerWithContext
29-
private _userConfig?: FakeTimerInstallOpts
29+
private _fakeTimers: FakeTimersContext
30+
private _userConfig?: FakeTimersConfig
3031
private _now = RealDate.now
3132

3233
constructor({
3334
global,
3435
config,
3536
}: {
3637
global: typeof globalThis
37-
config: FakeTimerInstallOpts
38+
config: FakeTimersConfig
3839
}) {
3940
this._userConfig = config
4041

@@ -154,22 +155,28 @@ export class FakeTimers {
154155
this._clock.uninstall()
155156
}
156157

157-
const toFake = Object.keys(this._fakeTimers.timers)
158-
// Do not mock timers internally used by node by default. It can still be mocked through userConfig.
159-
.filter(
160-
timer => timer !== 'nextTick' && timer !== 'queueMicrotask',
161-
) as (keyof FakeTimerWithContext['timers'])[]
162-
163-
if (this._userConfig?.toFake?.includes('nextTick') && isChildProcess()) {
158+
let toFake = this._userConfig?.toFake
159+
if (isChildProcess() && toFake?.includes('nextTick')) {
164160
throw new Error(
165161
'process.nextTick cannot be mocked inside child_process',
166162
)
167163
}
168164

165+
let toNotFake = this._userConfig?.toNotFake
166+
if (toFake === undefined && toNotFake === undefined) {
167+
// Do not mock timers internally used by node by default. It can still be mocked through userConfig.
168+
toFake = (Object.keys(this._fakeTimers.timers) as FakeMethod[])
169+
.filter(timer => timer !== 'nextTick' && timer !== 'queueMicrotask')
170+
}
171+
if (isChildProcess() && toNotFake && !toNotFake.includes('nextTick')) {
172+
toNotFake = [...toNotFake, 'nextTick']
173+
}
174+
169175
this._clock = this._fakeTimers.install({
170176
now: fakeDate,
171177
...this._userConfig,
172-
toFake: this._userConfig?.toFake || toFake,
178+
...(toFake && { toFake }),
179+
...(toNotFake && { toNotFake }),
173180
ignoreMissingTimers: true,
174181
})
175182

@@ -228,7 +235,7 @@ export class FakeTimers {
228235
}
229236
}
230237

231-
configure(config: FakeTimerInstallOpts): void {
238+
configure(config: FakeTimersConfig): void {
232239
this._userConfig = config
233240
}
234241

‎packages/vitest/src/integrations/vi.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { FakeTimerInstallOpts } from '@sinonjs/fake-timers'
1+
import type { Config as FakeTimersConfig } from '@sinonjs/fake-timers'
22
import type {
33
MaybeMocked,
44
MaybeMockedDeep,
@@ -27,7 +27,7 @@ export interface VitestUtils {
2727
/**
2828
* This method wraps all further calls to timers until [`vi.useRealTimers()`](https://vitest.dev/api/vi#vi-userealtimers) is called.
2929
*/
30-
useFakeTimers: (config?: FakeTimerInstallOpts) => VitestUtils
30+
useFakeTimers: (config?: FakeTimersConfig) => VitestUtils
3131
/**
3232
* Restores mocked timers to their original implementations. All timers that were scheduled before will be discarded.
3333
*/
@@ -496,7 +496,7 @@ function createVitest(): VitestUtils {
496496
const _envBooleans = ['PROD', 'DEV', 'SSR']
497497

498498
const utils: VitestUtils = {
499-
useFakeTimers(config?: FakeTimerInstallOpts) {
499+
useFakeTimers(config?: FakeTimersConfig) {
500500
if (isChildProcess()) {
501501
if (
502502
config?.toFake?.includes('nextTick')

‎packages/vitest/src/node/types/config.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { FakeTimerInstallOpts } from '@sinonjs/fake-timers'
1+
import type { Config as FakeTimersConfig } from '@sinonjs/fake-timers'
22
import type { PrettyFormatOptions } from '@vitest/pretty-format'
33
import type { SequenceHooks, SequenceSetupFiles, SerializableRetry, TestTagDefinition } from '@vitest/runner'
44
import type { SnapshotStateOptions } from '@vitest/snapshot'
@@ -617,7 +617,7 @@ export interface InlineConfig {
617617
/**
618618
* Options for @sinon/fake-timers
619619
*/
620-
fakeTimers?: FakeTimerInstallOpts
620+
fakeTimers?: FakeTimersConfig
621621

622622
/**
623623
* Custom handler for console.log in tests.

‎packages/vitest/src/runtime/config.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { FakeTimerInstallOpts } from '@sinonjs/fake-timers'
1+
import type { Config as FakeTimersConfig } from '@sinonjs/fake-timers'
22
import type { PrettyFormatOptions } from '@vitest/pretty-format'
33
import type { SequenceHooks, SequenceSetupFiles, SerializableRetry, TestTagDefinition } from '@vitest/runner'
44
import type { SnapshotEnvironment, SnapshotUpdateState } from '@vitest/snapshot'
@@ -34,7 +34,7 @@ export interface SerializedConfig {
3434
unstubGlobals: boolean
3535
unstubEnvs: boolean
3636
// TODO: make optional
37-
fakeTimers: FakeTimerInstallOpts
37+
fakeTimers: FakeTimersConfig
3838
maxConcurrency: number
3939
defines: Record<string, any>
4040
expect: {

patches/@sinonjs__fake-timers@15.0.0.patch renamed to patches/@sinonjs__fake-timers@15.3.2.patch

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
diff --git a/src/fake-timers-src.js b/src/fake-timers-src.js
2-
index a9bcfd1ca..942539085 100644
2+
index 7d4cfa1b6b8aebc8575e08bd432f8f8ca43d3c4f..09d12bec356aa1048f09771e915075fdecb065b9 100644
33
--- a/src/fake-timers-src.js
44
+++ b/src/fake-timers-src.js
55
@@ -2,14 +2,14 @@
@@ -11,16 +11,16 @@ index a9bcfd1ca..942539085 100644
1111
try {
1212
- timersModule = require("timers");
1313
+ timersModule = __vitest_required__.timers;
14-
} catch (e) {
14+
} catch {
1515
// ignored
1616
}
1717
try {
1818
- timersPromisesModule = require("timers/promises");
1919
+ timersPromisesModule = __vitest_required__.timersPromises;
20-
} catch (e) {
20+
} catch {
2121
// ignored
2222
}
23-
@@ -197,7 +197,7 @@ function withGlobal(_global) {
23+
@@ -510,7 +510,7 @@ function withGlobal(_global) {
2424
isPresent.hrtime && typeof _global.process.hrtime.bigint === "function";
2525
isPresent.nextTick =
2626
_global.process && typeof _global.process.nextTick === "function";

‎pnpm-lock.yaml‎

Lines changed: 9 additions & 24 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)