Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 14 / Topic 3 of 7

Async utilities: findBy* and waitFor

findBy* queries are sugar for exactly one thing: retry a getBy* query inside waitFor until it stops throwing, or time out. Reach for them whenever the thing you are waiting for is itself a query. examples/03_async_findby_waitfor.jsx's WalletBalance fetches, then shows one of three states:

// examples/03_async_findby_waitfor.test.jsx
render(<WalletBalance userId="u-401" />);
expect(screen.getByText("Loading wallet...")).toBeInTheDocument();
expect(await screen.findByText("Balance: ₹1250")).toBeInTheDocument();

waitFor is the general tool, for anything that is not itself a query - a mock's call count, for instance:

// examples/03_async_findby_waitfor.test.jsx
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));

stage-3-advanced/part-11-fetching-data/examples/04_avoiding_waterfalls.test.jsx already does exactly this (await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))) to prove two requests started without waiting on each other - the same tool, used for the same reason, two parts earlier. waitForElementToBeRemoved covers the third shape, "prove this is actually gone, not just that something else arrived" - and it has one real gotcha worth knowing: pass it a callback that re-queries (() => screen.queryByText("Loading wallet...")), not a captured element reference, or a removal that happens before the observer attaches can time out even though the element is already gone (examples/03_async_findby_waitfor.test.jsx).

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide