Testing React Through User Behavior
A React test is strongest when it protects what a user can perceive and do, not private implementation details.
This keeps tests aligned with roles, names, labels, text, focus, pending states, validation, and visible outcomes.
Test behavior, not React internalsβ
Weak goals include asserting a private state variable changed, a Hook ran exactly once, or a child was shallow-rendered with a specific internal prop.
Strong goals include:
- a dialog appears after activating its trigger;
- the submit button becomes disabled while work is pending;
- validation feedback is associated with the field;
- focus returns after closing a modal;
- a successful mutation changes the visible list.
Testing Library's philosophyβ
import { render, screen } from '@testing-library/react';
it('renders the account name', () => {
render(<AccountCard name="Aisha" />);
expect(screen.getByRole('heading', { name: 'Aisha' })).toBeInTheDocument();
});
The important part is the semantic query, not the library syntax.
Query priorityβ
Prefer:
screen.getByRole('button', { name: 'Save profile' });
over:
screen.getByTestId('save-button');
getBy, queryBy, and findByβ
screen.getByRole('button', { name: 'Submit' });
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
const alert = await screen.findByRole('alert');
Accessible names are part of behaviorβ
<button aria-label="Delete invoice">
<TrashIcon />
</button>
screen.getByRole('button', { name: 'Delete invoice' });
If the name disappears, the test fails in the same area where assistive-technology users would lose the control's meaning.
Prefer visible labels for formsβ
<label>
Email
<input type="email" />
</label>
screen.getByRole('textbox', { name: 'Email' });
// or
screen.getByLabelText('Email');
Interact the way users doβ
const user = userEvent.setup();
render(<LoginForm />);
await user.type(screen.getByLabelText('Email'), 'aisha@example.com');
await user.type(screen.getByLabelText('Password'), 'correct horse battery staple');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
Use fireEvent when you specifically need lower-level event dispatch that user-event does not model.
Assert observable stateβ
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();
expect(screen.getByRole('dialog')).toBeVisible();
expect(screen.getByLabelText('Email')).toHaveValue('aisha@example.com');
expect(screen.getByRole('alert')).toHaveTextContent('Email is required');
expect(screen.getByRole('tab', { name: 'Billing' })).toHaveAttribute('aria-selected', 'true');
Controlled components: test through the parent contractβ
function ControlledHarness() {
const [value, setValue] = useState('');
return <SearchBox value={value} onValueChange={setValue} />;
}
Type into the field and assert the visible value. Do not mutate props or private state directly.
Custom Hooks: test at the most meaningful boundaryβ
If a Hook exists only to support a component, prefer testing through that component. For reusable Hook libraries, a harness is appropriate.
function DisclosureHarness() {
const disclosure = useDisclosure();
return (
<>
<button onClick={disclosure.show}>Open</button>
{disclosure.open && <div role="dialog">Settings</div>}
</>
);
}
Providers belong in test infrastructureβ
function renderApp(ui: React.ReactElement) {
return render(
<ThemeProvider>
<RouterProvider router={router}>{ui}</RouterProvider>
</ThemeProvider>,
);
}
Keep helpers honest about which providers a feature actually needs.
Pure reducers can have direct unit testsβ
expect(reducer({ count: 0 }, { type: 'increment' })).toEqual({ count: 1 });
Mock boundaries, not the applicationβ
Good test-double boundaries include network transport, clocks, randomness, unsupported browser APIs, and expensive third-party integrations.
Avoid mocking React itself, every child, every custom Hook, or every module in a feature. Excessive mocking creates confidence in a fake architecture.
Network behavior should include failure statesβ
A network-backed component should exercise loading, success, error, retry, cancellation where relevant, and optimistic behavior.
Snapshot tests are specializedβ
Large snapshots are easy to approve without understanding the change. Prefer targeted semantic assertions unless the serialized output itself is the behavior you intend to protect.
Test IDs can be legitimateβ
Use a data-testid when no meaningful semantic selector existsβfor example a canvas marker or purely structural rendering hook. Do not add one automatically to every element.
Strict Modeβ
Strict Mode can expose purity, Effect, ref, and cleanup assumptions.
Weak when call count is not the product contract:
expect(connect).toHaveBeenCalledTimes(1);
Stronger:
expect(screen.getByText('Connected')).toBeVisible();
When protocol call counts genuinely matter, assert them deliberately and account for the test environment.
Accessibility assertions are behavior assertionsβ
expect(screen.getByRole('button', { name: 'Close dialog' })).toBeVisible();
expect(screen.getByLabelText('Password')).toHaveAttribute(
'aria-describedby',
expect.stringContaining('password-hint'),
);
Semantic tests improve accessibility confidence, but automated tests do not replace keyboard, screen-reader, contrast, and real-browser review for complex widgets.
Test names should describe contractsβ
Good:
shows validation feedback when email is empty;returns focus to the trigger after closing the dialog;keeps previous results visible while new search is pending;announces a failed save through an alert.
Avoid names such as sets isOpen to true or calls useEffect when those are only implementation details.
Review checklistβ
- Can the test locate important UI by role/name or label?
- Does interaction happen through rendered behavior?
- Are assertions user-observable?
- Are mocks placed at real boundaries?
- Are failure/pending states covered where relevant?
- Does focus/accessibility behavior have protection?
- Would an internal refactor leave the test valid if behavior did not change?
Interview questionsβ
- What does it mean to test React through user behavior?
- Why is
getByRoleoften stronger thangetByTestId? - When should you use
getBy,queryBy, andfindBy? - Why is
user-eventusually preferable to manually invoking handlers? - Which boundaries are reasonable to mock?
- Why can a reducer unit test and component test both be valuable?