Skip to content

Commit 6c5fe49

Browse files
authoredJan 17, 2024
fix(browser): don't fail when calling vi.useFakeTimers (#4992)
1 parent 8877e22 commit 6c5fe49

File tree

4 files changed

+33
-4
lines changed

4 files changed

+33
-4
lines changed
 

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

+11-1
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,20 @@ export class FakeTimers {
138138
if (this._userConfig?.toFake?.includes('nextTick') && isChildProcess())
139139
throw new Error('process.nextTick cannot be mocked inside child_process')
140140

141+
const existingFakedMethods = (this._userConfig?.toFake || toFake).filter((method) => {
142+
switch (method) {
143+
case 'hrtime':
144+
case 'nextTick':
145+
return typeof process !== 'undefined' && method in process && process[method]
146+
default:
147+
return method in globalThis && globalThis[method]
148+
}
149+
})
150+
141151
this._clock = this._fakeTimers.install({
142152
now: Date.now(),
143-
toFake,
144153
...this._userConfig,
154+
toFake: existingFakedMethods,
145155
})
146156

147157
this._fakingTime = true

‎packages/vitest/src/utils/base.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ class AggregateErrorPonyfill extends Error {
151151
export { AggregateErrorPonyfill as AggregateError }
152152

153153
export function isChildProcess(): boolean {
154-
return !!process?.send
154+
return typeof process !== 'undefined' && !!process.send
155155
}
156156

157157
export function setProcessTitle(title: string) {

‎test/browser/specs/runner.test.mjs

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ const {
1111
} = await runVitest()
1212

1313
await test('tests are actually running', async () => {
14-
assert.ok(browserResultJson.testResults.length === 11, 'Not all the tests have been run')
15-
assert.ok(passedTests.length === 9, 'Some tests failed')
14+
assert.ok(browserResultJson.testResults.length === 12, 'Not all the tests have been run')
15+
assert.ok(passedTests.length === 10, 'Some tests failed')
1616
assert.ok(failedTests.length === 2, 'Some tests have passed but should fail')
1717

1818
assert.doesNotMatch(stderr, /Unhandled Error/, 'doesn\'t have any unhandled errors')

‎test/browser/test/timers.test.ts

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { afterEach, expect, it, vi } from 'vitest'
2+
3+
afterEach(() => {
4+
vi.useRealTimers()
5+
})
6+
7+
it('only runs a setTimeout callback once (ever)', () => {
8+
vi.useFakeTimers()
9+
10+
const fn = vi.fn()
11+
setTimeout(fn, 0)
12+
expect(fn).toHaveBeenCalledTimes(0)
13+
14+
vi.runAllTimers()
15+
expect(fn).toHaveBeenCalledTimes(1)
16+
17+
vi.runAllTimers()
18+
expect(fn).toHaveBeenCalledTimes(1)
19+
})

0 commit comments

Comments
 (0)
Please sign in to comment.