Skip to content

Commit

Permalink
fix: prevent running test cases timers after environment teardown
Browse files Browse the repository at this point in the history
  • Loading branch information
AriPerkkio committed Mar 7, 2023
1 parent 3331365 commit f2e345b
Show file tree
Hide file tree
Showing 3 changed files with 20 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()
})

0 comments on commit f2e345b

Please sign in to comment.