Skip to content

Commit

Permalink
Decouple fake/real time in waitFor()'s check
Browse files Browse the repository at this point in the history
When running with fake timers, and when polling for promise to complete,
make sure we do the poll in a short *real* time interval, independent of
the fake time interval.

This makes it possible to use long time intervals in fake time without
needing to wait for the corresponding amount of real time passing. A
unit test is added to illustrate this behaviour: with the previous code,
this unit test would have taken over a minute to complete, now it is
near instantaneous.
  • Loading branch information
samavos committed Oct 28, 2024
1 parent 39041ee commit 77428e8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export function waitFor<T>(
}

timeoutId = setTimeout(handleTimeout, timeout)
intervalId = setInterval(checkCallback, interval)
intervalId = setInterval(checkCallback, vi.isFakeTimers() ? 20 : interval)
})
}

Expand Down
14 changes: 14 additions & 0 deletions test/core/test/wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,20 @@ describe('waitFor', () => {
vi.useRealTimers()
})

test('fakeTimer long interval works', async () => {
vi.useFakeTimers()

await vi.waitFor(() => {
return new Promise<void>((resolve) => {
setTimeout(() => {
resolve()
}, 60000)
})
}, { interval: 30000 })

vi.useRealTimers()
})

test('callback stops running after timeout', async () => {
let timedOut = false
let callbackRanAfterTimeout = false
Expand Down

0 comments on commit 77428e8

Please sign in to comment.