Skip to content

Commit

Permalink
fix: prevent running test cases timers after environment teardown (#2971
Browse files Browse the repository at this point in the history
)
  • Loading branch information
AriPerkkio authored Mar 7, 2023
1 parent a1954cc commit bde75a3
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 4 deletions.
4 changes: 0 additions & 4 deletions packages/vitest/src/runtime/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,6 @@ function withSafeTimers(fn: () => void) {
const promises = new Set<Promise<unknown>>()

export const rpcDone = async () => {
// Run possible setTimeouts, e.g. the onces used by ConsoleLogSpy
const { setTimeout } = getSafeTimers()
await new Promise(resolve => setTimeout(resolve))

if (!promises.size)
return
const awaitable = Array.from(promises)
Expand Down
4 changes: 4 additions & 0 deletions packages/vitest/src/runtime/setup.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ export async function withEnv(
await fn()
}
finally {
// Run possible setTimeouts, e.g. the onces used by ConsoleLogSpy
const { setTimeout } = getSafeTimers()
await new Promise(resolve => setTimeout(resolve))

await env.teardown(globalThis)
}
}
16 changes: 16 additions & 0 deletions test/core/test/dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,19 @@ it('doesn\'t throw, if listening for error', () => {
dispatchEvent(new Event('custom'))
expect(spy).toHaveBeenCalled()
})

it('timers are not run after environment teardown', async () => {
setInterval(() => {
try {
window.document.createElement('div')
}
catch (err) {
if (/window is not defined/.test((err as any).message))
throw new Error('setInterval was called after environment teardown')

throw err
}
}, 1)

expect(window.document).toBeDefined()
})
32 changes: 32 additions & 0 deletions test/watch/test/stdout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { readFileSync, writeFileSync } from 'fs'
import { afterEach, expect, test } from 'vitest'

import { startWatchMode, waitFor } from './utils'

const testFile = 'fixtures/math.test.ts'
const testFileContent = readFileSync(testFile, 'utf-8')

afterEach(() => {
writeFileSync(testFile, testFileContent, 'utf8')
})

test('console.log is visible on test re-run', async () => {
const vitest = await startWatchMode()
const testCase = `
test('test with logging', () => {
console.log('First')
console.log('Second')
console.log('Third')
expect(true).toBe(true)
})
`

writeFileSync(testFile, `${testFileContent}${testCase}`, 'utf8')

await waitFor(() => {
expect(vitest.getOutput()).toMatch('stdout | math.test.ts > test with logging')
expect(vitest.getOutput()).toMatch('First')
expect(vitest.getOutput()).toMatch('Second')
expect(vitest.getOutput()).toMatch('Third')
})
})

0 comments on commit bde75a3

Please sign in to comment.