07 / 12
findBy, waitFor and fake timers.
Some changes do not happen immediately. For example:
The product list appears once the API responds.
A notification shows when a product is added to the cart, and closes 3 seconds later.
Your test has to wait for that change. Without waiting, the test checks before the interface updates, and fails.1
findBy* waits until it finds the element. It throws when the time runs out. The default is 1000 ms.3
test("shows a status message while loading, then the products", async () => {
render(
<ProductList
loadProducts={() => Promise.resolve(products)}
onAddToCart={vi.fn()}
/>,
);
expect(screen.getByText("Loading products...")).toBeInTheDocument();
expect(await screen.findAllByRole("article")).toHaveLength(3);
});The first line uses getBy*. The loading message is on screen in the very first render, so no waiting is needed.3
waitFor runs the function you give it again and again until it stops throwing. The default is 1000 ms.1
Use queryBy* when you wait for an element to disappear:3
await waitFor(() =>
expect(screen.queryByText("Loading products...")).not.toBeInTheDocument(),
);waitForElementToBeRemoved(() => screen.queryByText("...")) waits for an element to disappear. The element has to be in the DOM to begin with. If it is already gone, the function throws.1
When you are not sure, use the waitFor and queryBy combination. That works even if the element disappears very quickly.1
A notification appears when a product is added to the cart. The notification closes after 3 seconds. A test that waits 3 seconds is slow. Advance the time yourself.2
import { useEffect, useState } from "react";
export function AddedToast({ productName }: { productName: string }) {
const [visible, setVisible] = useState(true);
useEffect(() => {
const id = setTimeout(() => setVisible(false), 3000);
return () => clearTimeout(id);
}, []);
return visible ? <div role="status">{productName} added to cart.</div> : null;
}import { act, render, screen } from "@testing-library/react";
import { AddedToast } from "./AddedToast";
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
});
afterEach(() => {
vi.useRealTimers();
});
test("the notification disappears after 3 seconds", async () => {
render(<AddedToast productName="Wireless Headphones" />);
expect(await screen.findByRole("status")).toHaveTextContent(
"Wireless Headphones added to cart.",
);
act(() => {
vi.advanceTimersByTime(3000);
});
expect(screen.queryByRole("status")).not.toBeInTheDocument();
});Watch out for three rules:
Call vi.useFakeTimers before render. The component's setTimeout call has to be the fake one.6
Wrap the vi.advanceTimersByTime call in act. The timer updates a React state.7
Call vi.useRealTimers in afterEach.8 afterEach runs even when the test fails.
vi.advanceTimersByTime(ms): advances the time by ms. vi.advanceTimersByTimeAsync(ms): does the same and also runs the timers set up asynchronously.6
vi.runOnlyPendingTimers(): runs the pending timers right away. vi.setSystemTime(date): sets the value of Date.now() and new Date().6
Do not use fake timers for a short wait (300 ms, say). Wait with findBy.
What shows up when the API call fails? Test that:
The loadProducts function returns Promise.reject(new Error("network error")).
Find the Products could not be loaded. message with findByRole("alert").
Confirm with queryBy* that the Loading products... message is gone.
Sources
`findBy`, `waitFor` and `waitForElementToBeRemoved`.
The fake timers guide.
The difference between `getBy`, `queryBy` and `findBy`.
Side effects inside `waitFor`, and using `waitFor` instead of `find*`.
The value given is checked for being an HTMLElement.
The fake timers commands.
Applying the updates before the assertion.
Setting fake timers up and cleaning them up.
`findBy` running into a timeout in Vitest.
The `shouldAdvanceTime` option.
The `advanceTimers` option.
Check the lesson's main ideas with three questions.
Your progress is stored only in this browser.
Last updated: November 3, 2026