Skip to content

Commit

Permalink
fix(browser): fix console.time with fake timers (#7207)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Jan 13, 2025
1 parent 9175836 commit 903f3b9
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/browser/src/client/tester/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { format, stringify } from 'vitest/utils'
import { getConfig } from '../utils'
import { rpc } from './rpc'

const { Date, console } = globalThis
const { Date, console, performance } = globalThis

export function setupConsoleLogSpy() {
const {
Expand Down Expand Up @@ -71,7 +71,7 @@ export function setupConsoleLogSpy() {
if (!(label in timeLabels)) {
sendLog('stderr', `Timer "${label}" does not exist`)
}
else if (start) {
else if (typeof start !== 'undefined') {
const duration = end - start
sendLog('stdout', `${label}: ${duration} ms`)
}
Expand Down
2 changes: 2 additions & 0 deletions test/browser/specs/runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ describe('running browser tests', async () => {
expect(stdout).toContain('count: 3')
expect(stdout).toMatch(/default: [\d.]+ ms/)
expect(stdout).toMatch(/time: [\d.]+ ms/)
expect(stdout).toMatch(/\[console-time-fake\]: [\d.]+ ms/)
expect(stdout).not.toContain('[console-time-fake]: 0 ms')
})

test('logs are redirected to stderr', () => {
Expand Down
10 changes: 10 additions & 0 deletions test/browser/test/timers.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { afterEach, expect, it, vi } from 'vitest'

afterEach(() => {
Expand All @@ -17,3 +18,12 @@ it('only runs a setTimeout callback once (ever)', () => {
vi.runAllTimers()
expect(fn).toHaveBeenCalledTimes(1)
})

it('console.time', async () => {
vi.useFakeTimers({
toFake: ['Date', 'performance'],
})
console.time('[console-time-fake]')
await new Promise(r => setTimeout(r, 500))
console.timeEnd('[console-time-fake]')
})

0 comments on commit 903f3b9

Please sign in to comment.