fix(browser): don't fail when calling vi.useFakeTimers (#4992)

This commit is contained in:
Vladimir 2024-01-17 15:37:04 +01:00 committed by GitHub
parent 8877e22a09
commit 6c5fe49be4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 33 additions and 4 deletions

View File

@ -138,10 +138,20 @@ export class FakeTimers {
if (this._userConfig?.toFake?.includes('nextTick') && isChildProcess())
throw new Error('process.nextTick cannot be mocked inside child_process')
const existingFakedMethods = (this._userConfig?.toFake || toFake).filter((method) => {
switch (method) {
case 'hrtime':
case 'nextTick':
return typeof process !== 'undefined' && method in process && process[method]
default:
return method in globalThis && globalThis[method]
}
})
this._clock = this._fakeTimers.install({
now: Date.now(),
toFake,
...this._userConfig,
toFake: existingFakedMethods,
})
this._fakingTime = true

View File

@ -151,7 +151,7 @@ class AggregateErrorPonyfill extends Error {
export { AggregateErrorPonyfill as AggregateError }
export function isChildProcess(): boolean {
return !!process?.send
return typeof process !== 'undefined' && !!process.send
}
export function setProcessTitle(title: string) {

View File

@ -11,8 +11,8 @@ const {
} = await runVitest()
await test('tests are actually running', async () => {
assert.ok(browserResultJson.testResults.length === 11, 'Not all the tests have been run')
assert.ok(passedTests.length === 9, 'Some tests failed')
assert.ok(browserResultJson.testResults.length === 12, 'Not all the tests have been run')
assert.ok(passedTests.length === 10, 'Some tests failed')
assert.ok(failedTests.length === 2, 'Some tests have passed but should fail')
assert.doesNotMatch(stderr, /Unhandled Error/, 'doesn\'t have any unhandled errors')

View File

@ -0,0 +1,19 @@
import { afterEach, expect, it, vi } from 'vitest'
afterEach(() => {
vi.useRealTimers()
})
it('only runs a setTimeout callback once (ever)', () => {
vi.useFakeTimers()
const fn = vi.fn()
setTimeout(fn, 0)
expect(fn).toHaveBeenCalledTimes(0)
vi.runAllTimers()
expect(fn).toHaveBeenCalledTimes(1)
vi.runAllTimers()
expect(fn).toHaveBeenCalledTimes(1)
})