mirror of
https://github.com/vitest-dev/vitest.git
synced 2025-12-08 18:26:03 +00:00
fix(browser): don't fail when calling vi.useFakeTimers (#4992)
This commit is contained in:
parent
8877e22a09
commit
6c5fe49be4
@ -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
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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')
|
||||
|
||||
19
test/browser/test/timers.test.ts
Normal file
19
test/browser/test/timers.test.ts
Normal 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)
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user