|
| 1 | +--- |
| 2 | +description: Replace wait-for-expect with built-in assertion retries in Vitest or node:test |
| 3 | +--- |
| 4 | + |
| 5 | +# Replacements for `wait-for-expect` |
| 6 | + |
| 7 | +Popular test runners such as Vitest and `node:test` provide built-in assertion retries, so projects using them can remove `wait-for-expect`. |
| 8 | + |
| 9 | +## `vitest` |
| 10 | + |
| 11 | +[`vi.waitFor()`](https://vitest.dev/api/vi.html#vi-waitfor) is available since Vitest 0.34.5 and accepts synchronous or asynchronous assertion callbacks. |
| 12 | + |
| 13 | +It retries callbacks that throw or reject until they succeed or time out. Keep the assertion inside the callback and await the result; returning `false` alone does not trigger a retry. |
| 14 | + |
| 15 | +```ts |
| 16 | +import waitForExpect from 'wait-for-expect' // [!code --] |
| 17 | +import { expect, test } from 'vitest' // [!code --] |
| 18 | +import { expect, test, vi } from 'vitest' // [!code ++] |
| 19 | +
|
| 20 | +test('service becomes ready', async () => { |
| 21 | + const checkReady = async () => { |
| 22 | + expect(await service.isReady()).toBe(true) |
| 23 | + } |
| 24 | + |
| 25 | + await waitForExpect(checkReady, 4500, 50) // [!code --] |
| 26 | + await vi.waitFor(checkReady, { timeout: 4500, interval: 50 }) // [!code ++] |
| 27 | +}) |
| 28 | +``` |
| 29 | + |
| 30 | +If you use `vi.useFakeTimers()`, `vi.waitFor()` automatically advances fake timers by the polling interval on each check. Review tests that previously advanced timers manually. |
| 31 | + |
| 32 | +## `node:test` |
| 33 | + |
| 34 | +[`t.waitFor()`](https://nodejs.org/api/test.html#contextwaitforcondition-options) is available on the test context since Node.js 22.14.0 and 23.7.0 and accepts synchronous or asynchronous assertion callbacks. |
| 35 | + |
| 36 | +It retries callbacks that throw or reject until they succeed or time out. Keep the assertion inside the callback and await the result; returning `false` alone does not trigger a retry. |
| 37 | + |
| 38 | +```ts |
| 39 | +import waitForExpect from 'wait-for-expect' // [!code --] |
| 40 | +import { test } from 'node:test' |
| 41 | +import assert from 'node:assert/strict' |
| 42 | + |
| 43 | +test('service becomes ready', async (t) => { |
| 44 | + const checkReady = async () => { |
| 45 | + assert.equal(await service.isReady(), true) |
| 46 | + } |
| 47 | + |
| 48 | + await waitForExpect(checkReady, 4500, 50) // [!code --] |
| 49 | + await t.waitFor(checkReady, { timeout: 4500, interval: 50 }) // [!code ++] |
| 50 | +}) |
| 51 | +``` |
0 commit comments