Skip to content

Commit

Permalink
fix: vi.waitFor/vi.waitUntil interval is now cleared after it times o…
Browse files Browse the repository at this point in the history
…ut (#5875)
  • Loading branch information
pedro00dk authored Jun 12, 2024
1 parent a663c7b commit 041076e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/vitest/src/integrations/wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export function waitFor<T>(callback: WaitForCallback<T>, options: number | WaitF
}

const handleTimeout = () => {
if (intervalId)
clearInterval(intervalId)
let error = lastError
if (!error)
error = copyStackTrace(new Error('Timed out in waitFor!'), STACK_TRACE_ERROR)
Expand Down Expand Up @@ -113,6 +115,8 @@ export function waitUntil<T>(callback: WaitUntilCallback<T>, options: number | W
let intervalId: ReturnType<typeof setInterval>

const onReject = (error?: Error) => {
if (intervalId)
clearInterval(intervalId)
if (!error)
error = copyStackTrace(new Error('Timed out in waitUntil!'), STACK_TRACE_ERROR)
reject(error)
Expand Down
44 changes: 44 additions & 0 deletions test/core/test/wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,28 @@ describe('waitFor', () => {

vi.useRealTimers()
})

test('callback stops running after timeout', async () => {
vi.useFakeTimers()
let timedOut = false
let callbackRanAfterTimeout = false
try {
await vi.waitFor(() => {
callbackRanAfterTimeout = timedOut
throw new Error('waitFor error')
}, {
interval: 100,
timeout: 200,
})
}
catch (error) {
timedOut = true
}
await vi.advanceTimersByTimeAsync(100)
expect(timedOut).toBe(true)
expect(callbackRanAfterTimeout).toBe(false)
vi.useRealTimers()
})
})

describe('waitUntil', () => {
Expand Down Expand Up @@ -180,4 +202,26 @@ describe('waitUntil', () => {

vi.useRealTimers()
})

test('callback stops running after timeout', async () => {
vi.useFakeTimers()
let timedOut = false
let callbackRanAfterTimeout = false
try {
await vi.waitUntil(() => {
callbackRanAfterTimeout = timedOut
return false
}, {
interval: 100,
timeout: 200,
})
}
catch (error) {
timedOut = true
}
await vi.advanceTimersByTimeAsync(100)
expect(timedOut).toBe(true)
expect(callbackRanAfterTimeout).toBe(false)
vi.useRealTimers()
})
})

0 comments on commit 041076e

Please sign in to comment.