Quick answer
A useful component test performs a user action and checks the resulting interface or callback contract. Select a control by its role and accessible name, interact with it through user-event, then assert the state the user can observe. Avoid tests that duplicate a component’s private state variables or freeze a large rendered snapshot.
Practical implementation steps
Write the behaviour as a short scenario: the user opens details, sees additional content, then closes it. Render the smallest component boundary that owns that interaction. Use a DOM environment such as jsdom for Vitest and install React Testing Library, user-event, and their compatible dependencies in the application being tested.
Choose getBy queries for elements that must exist now, queryBy for absence, and findBy for content that appears asynchronously. Await user interactions. If the component depends on a router, theme, or query client, provide the minimal real provider setup; replace external network responses at a boundary rather than mocking every hook inside the component.
Implementation example
This complete interaction example uses Vitest assertions and explicit cleanup, so it does not require jest-dom matchers or global test hooks. The disclosure is deliberately small; replace it with the production component when applying the test to your app.
// @vitest-environment jsdom
import { useState } from "react";
import { afterEach, expect, test } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
afterEach(cleanup);
function Details() {
const [open, setOpen] = useState(false);
return <>
<button type="button" aria-expanded={open}
onClick={() => setOpen(value => !value)}>Details</button>
{open && <p>Consultation details</p>}
</>;
}
test("opens and closes details", async () => {
const user = userEvent.setup();
render(<Details />);
const trigger = screen.getByRole("button", { name: "Details" });
expect(screen.queryByText("Consultation details")).toBeNull();
await user.click(trigger);
expect(trigger.getAttribute("aria-expanded")).toBe("true");
expect(screen.getByText("Consultation details")).toBeTruthy();
await user.click(trigger);
expect(screen.queryByText("Consultation details")).toBeNull();
});
A DOM simulation does not demonstrate real layout, browser navigation, or screen-reader output. Add a browser test for the workflow that depends on those behaviours. For asynchronous data, assert the pending state and final result separately, and exercise a rejected response without converting the test into a copy of the implementation.
Tradeoffs and alternatives
Role queries exercise the component’s semantic interface and survive many styling changes. Text queries remain appropriate for non-interactive content. Test IDs can identify a region without a meaningful accessible role, but using them for every button hides naming and semantics problems. Visual regression tests complement behavioural tests when spacing or typography is the actual contract.
Common mistakes
Unawaited events, broad sleeps, assertions on internal hooks, and identical mocks for success and failure make tests pass without establishing the user result. A wrapper around state setters is not evidence that an actual form can submit. Keep the failure message and recovery action within the tested scenario.
Production checklist
- Queries identify controls by role and name.
- Every asynchronous event is awaited.
- Tests isolate external services without replacing the behaviour being tested.
- Failure, absence, and recovery states have useful assertions.
- Browser coverage handles layout and navigation assumptions.
FAQ
Should I wrap each test in act?
Testing Library helpers already coordinate common React updates. Await the documented interactions first; investigate remaining act warnings rather than hiding them or adding arbitrary timeouts.
Are passing role queries an accessibility audit?
They establish a useful part of the semantic contract. Keyboard order, contrast, zoom, focus visibility, and assistive-technology behaviour still need their appropriate checks.
Next step
Choose one interactive region from a real project screen and test its successful action and recoverable failure. Keep the assertions centred on what changes for the user.
Primary sources
- Testing Library: About queries
- Testing Library: user-event introduction
- Vitest: Test environments
- React: act
Related guides and examples
Need this implemented in a real product?
React and Next.js applications with deliberate rendering, reliable data flows, and a clear path to production.