From 77428e8579085ecc2914a197b7b85e4c08791754 Mon Sep 17 00:00:00 2001 From: Sam Jansen Date: Mon, 28 Oct 2024 13:09:56 +0000 Subject: [PATCH] Decouple fake/real time in waitFor()'s check 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. --- packages/vitest/src/integrations/wait.ts | 2 +- test/core/test/wait.test.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/vitest/src/integrations/wait.ts b/packages/vitest/src/integrations/wait.ts index be027be4cb22..652f52419bc4 100644 --- a/packages/vitest/src/integrations/wait.ts +++ b/packages/vitest/src/integrations/wait.ts @@ -110,7 +110,7 @@ export function waitFor( } timeoutId = setTimeout(handleTimeout, timeout) - intervalId = setInterval(checkCallback, interval) + intervalId = setInterval(checkCallback, vi.isFakeTimers() ? 20 : interval) }) } diff --git a/test/core/test/wait.test.ts b/test/core/test/wait.test.ts index 5061a365d315..75ca4a9ba7f2 100644 --- a/test/core/test/wait.test.ts +++ b/test/core/test/wait.test.ts @@ -102,6 +102,20 @@ describe('waitFor', () => { vi.useRealTimers() }) + test('fakeTimer long interval works', async () => { + vi.useFakeTimers() + + await vi.waitFor(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolve() + }, 60000) + }) + }, { interval: 30000 }) + + vi.useRealTimers() + }) + test('callback stops running after timeout', async () => { let timedOut = false let callbackRanAfterTimeout = false