From f86e66661492eda45ab2c5d707dd5682e9c40315 Mon Sep 17 00:00:00 2001 From: Guillaume Duboc Date: Tue, 10 Jan 2023 13:54:48 +0100 Subject: [PATCH] docs(api): add advanceTimersByTimeAsync, advanceTimersToNextTimerAsync and runOnlyPendingTimersAsync --- docs/api/index.md | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/docs/api/index.md b/docs/api/index.md index a9bc213d5d4d..e6556247e8d9 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -2533,6 +2533,19 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo vi.advanceTimersByTime(150) ``` +### vi.advanceTimersByTimeAsync + +- **Type:** `async (ms: number) => Promise` + + Works just like `runAllTimersAsync`, but will end after passed milliseconds. This will include asynchronously set timers. For example this will log `1, 2, 3` and will not throw: + + ```ts + let i = 0 + setInterval(() => Promise.resolve().then(() => console.log(++i)), 50) + + await vi.advanceTimersByTimeAsync(150) + ``` + ### vi.advanceTimersToNextTimer - **Type:** `() => Vitest` @@ -2548,6 +2561,21 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo .advanceTimersToNextTimer() // log 3 ``` +### vi.advanceTimersToNextTimerAsync + +- **Type:** `async () => Promise` + + Will call next available timer even if it was set asynchronously. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself. + + ```ts + let i = 0 + setInterval(() => Promise.resolve().then(() => console.log(++i)), 50) + + vi.advanceTimersToNextTimerAsync() // log 1 + .advanceTimersToNextTimerAsync() // log 2 + .advanceTimersToNextTimerAsync() // log 3 + ``` + ### vi.getTimerCount - **Type:** `() => number` @@ -2996,6 +3024,28 @@ IntersectionObserver === undefined vi.runOnlyPendingTimers() ``` +### vi.runOnlyPendingTimersAsync + +- **Type:** `async () => Promise` + + This method will asynchronously call every timer that was initiated after `vi.useFakeTimers()` call, even asynchronous ones. It will not fire any timer that was initiated during its call. For example this will log `1, 2, 3`: + + ```ts + setTimeout(() => { + console.log(1) + }, 100) + setTimeout(() => { + Promise.resolve().then(() => { + console.log(2) + setTimeout(() => { + console.log(3) + }, 50) + }) + }, 10) + + await vi.runOnlyPendingTimersAsync() + ``` + ### vi.setSystemTime - **Type**: `(date: string | number | Date) => void`