Sub topic 3
Testing Async UI with `findBy` and `waitFor`
Assume you know React components, hooks, promises, and basic Jest or Vitest syntax. This chapter focuses on behavior users can observe.
Waiting for asynchronous UI
Use findBy when an element should appear after asynchronous work. It combines a query with a wait and returns a promise. Use getBy for content that should already exist. Use queryBy when checking that content is absent.
test('shows the loaded user', async () => {
const loadUser = jest.fn().mockResolvedValue({ name: 'Ada' });
render(<UserGreeting loadUser={loadUser} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByRole('heading', { name: 'Hello, Ada' }))
.toBeInTheDocument();
});Use waitFor when the condition is not a single element query, such as checking a callback or several state changes.
await waitFor(() => {
expect(saveUser).toHaveBeenCalledWith({ name: 'Ada' });
});Mocking dependencies
Inject callbacks as props and use jest.fn() or vi.fn() to observe calls. For modules, replace the imported function with a test mock. For network requests, prefer a request-level tool such as Mock Service Worker so the component still uses its normal request code.
test('submits the form value', async () => {
const user = userEvent.setup();
const onSubmit = jest.fn();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
expect(onSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});Providers and custom hooks
A custom render helper applies shared providers consistently:
export function renderWithTheme(ui, options) {
return render(ui, { wrapper: ThemeProvider, ...options });
}Test a custom hook with renderHook. Wrap updates in act so React finishes the state change before asserting.
const { result } = renderHook(() => useToggle());
expect(result.current[0]).toBe(false);
act(() => result.current[1]());
expect(result.current[0]).toBe(true);Common pitfalls
- Do not use
waitForfor every assertion. Use the most specific query. - Do not query React state, component instances, or internal class names.
- Prefer roles and labels over test IDs.
- Await every
userEventinteraction. - Mock external boundaries, but keep the component’s user-visible behavior real.
Exercise
Which query should you use when a heading appears after a promise resolves?
Show answer
Use findByRole, and await its returned promise.