Skip to content

Commit

Permalink
fix(browser): don't fail when calling vi.useFakeTimers (#4992)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Jan 17, 2024
1 parent 8877e22 commit 6c5fe49
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 4 deletions.
12 changes: 11 additions & 1 deletion packages/vitest/src/integrations/mock/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/utils/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions test/browser/specs/runner.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
19 changes: 19 additions & 0 deletions test/browser/test/timers.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})

0 comments on commit 6c5fe49

Please sign in to comment.