Testing Components with Confidence
Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.
What you will be able to do
#- Query the DOM by role and accessible name.
- Handle asynchronous updates with findBy and userEvent.
- Avoid tests that couple to implementation details.
Overview
#Test behavior, not implementation
A good component test renders the component, interacts with it the way a user would, and asserts what the user sees. It does not reach into internal state or call methods directly. This keeps the test valid when the implementation changes.
render(<Counter />);
await userEvent.click(screen.getByRole('button', { name: /increment/i }));
expect(screen.getByText('1')).toBeInTheDocument();
Query by role and name
Prefer queries that reflect accessibility: getByRole with an accessible name, getByLabelText for form fields, getByText for content. These queries also catch accessibility regressions, because a missing label or role makes them fail.
Async updates
State updates from promises or timers are not applied synchronously. Use findBy queries or waitFor to wait for the DOM to update, and userEvent rather than fireEvent so the real event sequence runs.
await userEvent.type(screen.getByLabelText('Email'), 'a@b.com');
expect(await screen.findByText('Saved')).toBeInTheDocument();
Mock at the boundary
Mock the network or the module at the edge, not the component's internals. For a server function or fetch, provide a fake that returns controlled data so the test is deterministic.
What to test
Test the behaviors users depend on: rendering from props, responding to interaction, showing loading and error states, and accessibility. Do not test that a specific hook was called.
Pitfall: asserting on class names or state
Asserting on a class name or a component's internal state couples the test to the implementation. Assert on roles, text and behavior instead.
Testing an error boundary
Render the boundary with a child that throws, suppress the expected console error, and assert the fallback appears and the crashed content does not.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Why does this test fail even though the component works?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.tsxrender(<Async />); expect(screen.getByText('Loaded')).toBeInTheDocument();Exercise 2Implement
Write a test that types into an email field and asserts the submit button becomes enabled.
starter.tsxrender(<EmailForm />);Reveal the reference answer
reference.tsxrender(<EmailForm />); const input = screen.getByLabelText('Email'); const button = screen.getByRole('button', { name: /submit/i }); expect(button).toBeDisabled(); await userEvent.type(input, 'a@b.com'); expect(button).toBeEnabled();Authored expected output: The button is disabled before typing and enabled after a valid value is entered.
The test queries by label and role, asserts the initial disabled state, then types with userEvent and asserts the enabled state. It checks behavior through the accessibility tree.
Exercise 3Debug
This test breaks whenever the class name changes. Explain and fix.
starter.tsxexpect(container.querySelector('.btn-primary')).not.toBeNull();Reveal the reference answer
reference.tsxexpect(screen.getByRole('button', { name: /save/i })).toBeVisible();Authored expected output: The test asserts on the button's role and name instead of a class.
Querying by class couples the test to styling. Querying by role and accessible name asserts the user-facing contract and survives refactors of class names.
Exercise 4Explain
Explain why testing through roles and user events gives more confidence than testing internals.
starter.tsx// role queries and userEvent vs internal stateReveal the reference answer
reference.tsxTesting through roles and user events exercises the same path a user takes: the component renders, the accessibility tree exposes it, the event fires, state updates and the DOM changes. This catches integration bugs between props, handlers and rendering. Testing internals, such as calling a setter or asserting on state, bypasses that path and can pass while the UI is broken. Role queries also double as accessibility checks, because a missing label or role makes the query fail.Authored expected output: A written explanation of user-path coverage and the accessibility side benefit.
The value is that the test mirrors real usage and stays valid as the implementation changes.
Common misconceptions
#- Tests should assert internal state. Assert what the user sees and can do.
- fireEvent is as good as userEvent. userEvent runs the full event sequence and catches more bugs.
- getBy works for async updates. Use findBy or waitFor for updates that happen after a promise.
- Mocking everything makes tests reliable. Mock at the boundary; over-mocking hides integration bugs.
Follow-up practice
#- react-accessibility
- react-component-architecture
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.