Sub topic 1
Why test behavior instead of implementation
Prerequisites
This chapter assumes you already know the following:
- React function components, props, state, and hooks such as
useState. - Basic JavaScript, including
async/awaitand promises. - A test runner such as Jest or Vitest, including
test,expect, anddescribe. - Basic HTML semantics: roles, labels, and form elements.
You do not need to install anything yet. Later chapters cover setup. The code here shows ideas, and the first two examples are complete enough to run once the environment from the next chapter is in place.
The core idea
React Testing Library (RTL) is built around one guiding principle from its author, Kent C. Dodds: the more your tests resemble the way your software is used, the more confidence they can give you.
A user of your component does not see state variables, hook calls, or component instances. They see text, buttons, fields, and links. They click, type, and read what changes. RTL asks you to write tests from that point of view.
This gives two kinds of test:
- Behavior tests render the component, interact with it through the DOM, and check what a user would see.
- Implementation tests reach inside the component and check its internals: the value of a state variable, whether a method was called, or the name of a CSS class.
RTL makes the first kind easy and the second kind awkward. That is deliberate.
What counts as an implementation detail
An implementation detail is anything a user of the component cannot observe and would not care about. If you can change it without changing what the user sees or can do, it is an implementation detail.
Common examples:
- The names and shapes of internal state variables.
- Whether the component uses
useState,useReducer, or a store. - Names of internal helper functions and child components.
- The component's DOM structure, such as how many
divwrappers exist. - CSS class names that exist only for styling.
- The order of hook calls and the number of renders.
Things that are not implementation details, because the user or the parent code depends on them:
- Text on the screen.
- Roles, accessible names, and labels.
- Whether a control is enabled, disabled, checked, or visible.
- Props that form the public contract, such as
onSubmit, and the values passed to them.
A brittle test and a resilient test
Consider a counter component.
// Counter.jsx
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
</div>
);
}An implementation-focused test might useallow renderer or inspect internals. It might look like this pseudocode:
// Brittle: depends on internal structure, not on what the user sees.
const wrapper = shallow(<Counter />);
expect(wrapper.state('count')).toBe(0);
wrapper.instance().handleClick();
expect(wrapper.state('count')).toBe(1);This test is tied to a class component with a count state field and a handleClick method. Rewrite Counter with a function component and hooks, as above, and the test fails even though the feature works. The reverse also happens. If you rename the button's handler but forget to attach it, the test that calls the handler directly still passes, while the real button does nothing.
A behavior test looks like this:
// Counter.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Counter } from './Counter';
test('increments the count when the button is clicked', async () => {
const user = userEvent.setup();
render(<Counter />);
expect(screen.getByText('Count: 0')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});The test does four things, and each mirrors what a person would do:
- It renders the component into a simulated browser document.
- It finds the button by its role and visible name, as a screen reader user would.
- It clicks the button with
user-event, which fires the same sequence of events a browser fires. - It checks the text on the screen.
You could now replace useState with useReducer, extract the button into a child component, or wrap everything in a section. The test would still pass. If the button stopped working, it would fail. That is the behavior you want to protect.
Why this matters
Tests exist to let you change code with confidence. Two failure modes undermine that, and implementation testing causes both.
| Failure | What happens | Effect on the team |
|---|---|---|
| False failure | A refactor keeps behavior the same, but tests break | Developers spend time fixing tests and stop trusting them |
| False pass | The feature is broken, but tests still pass | Bugs reach users with a green build |
Behavior tests reduce both. They fail when the user-visible result changes, and they survive internal rewrites.
A second benefit is accessibility. RTL's preferred queries use roles, labels, and text. If you cannot find a button by getByRole('button', { name: 'Increment' }), a screen reader user may also have trouble finding it. Writing tests this way often exposes missing labels or wrong elements, such as a clickable div that should be a button.
How RTL nudges you toward behavior
RTL does not forbid you from testing internals, but its API points the other way.
- No access to component instances or state.
renderreturns helpers for the DOM, not for the component's internal state. screenqueries the whole document. You search the way a user scans a page, not by walking a component tree.- Queries are ranked by accessibility.
getByRole,getByLabelText, andgetByTextcome beforegetByTestId, which is a last resort. user-eventsimulates real interaction. Auser.typecall focuses the field and fires key events for each character, rather than setting a value directly.- Real rendering.
rendermounts the full component tree, including children, into a jsdom document. Children are not replaced by stubs unless you choose to mock them.
The flow of a typical test follows from this.
Testing the public contract
Behavior testing does not mean you ignore props and callbacks. A component's props are its public interface, so they are part of its behavior. A form that calls onSubmit with the entered values is doing something the parent depends on.
// LoginForm.jsx
import { useState } from 'react';
export function LoginForm({ onSubmit }) {
const [email, setEmail] = useState('');
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit({ email });
}}
>
<label htmlFor="email">Email</label>
<input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Sign in</button>
</form>
);
}
// LoginForm.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
test('submits the entered email', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn();
render(<LoginForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), '[email protected]');
await user.click(screen.getByRole('button', { name: 'Sign in' }));
expect(handleSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});The test never reads the email state. It types into the field a user would see, submits, and checks what the parent receives. The mock function jest.fn() stands in for the parent. In Vitest, use vi.fn() instead.
The line between public contract and internal detail is this:
- Asserting that
onSubmitreceived{ email: '[email protected]' }checks the contract. - Asserting that
setEmailwas called would check an internal detail.
Where the principle has limits
The approach is a guideline, not a rule that every test must go through the UI.
- Pure logic. A function that formats a date or computes a total is best tested directly as a plain function. No rendering is needed.
- Custom hooks. A reusable hook has a public contract of its own, its return value. RTL provides
renderHookfor this, covered in a later chapter. - Unit-level mocks. Mocking a network layer or a heavy child component is acceptable when it keeps the test fast and focused. Mock at the boundary of your system, not inside the component you are testing.
- Integration versus isolation. Rendering a whole page with real children gives more confidence, but it is slower and fails for more reasons. Pick the scope that matches what you want to prove.
Testing behavior also does not guarantee a good test. A test that renders a component and asserts only that it does not crash proves little. Good behavior tests state a user goal, perform it, and check the outcome.
Common signs you are testing implementation
Watch for these in your own tests:
- The test imports something the user cannot see, such as a state setter or a private helper.
- Selectors rely on class names, element tag order, or
container.firstChild. - Assertions check how many times an internal function ran.
- A harmless refactor, such as renaming a variable or splitting a component, breaks the test.
- You call
setState-style methods or readinstance()values directly.
Summary of the working model
- Write tests from the user's point of view: render, find, interact, assert.
- Treat visible output and public props as the contract. Treat state, hooks, and structure as private.
- Prefer tests that survive refactors and fail on real regressions.
- Use direct tests for pure functions, and
renderHookfor reusable hooks.
The next chapter sets up Jest or Vitest, jsdom, and the jest-dom matchers so you can run the examples above.
Exercise
A teammate rewrites a component from useState to useReducer without changing what it renders. Two tests fail. One asserts screen.getByText('Count: 1') after a click. The other spies on the setCount function. Which test is the better design, and why did the other fail?
Show answer
The test using getByText after a click is the better design. It checks what the user sees, so it is unaffected by how state is stored. The spy test depends on setCount, an internal detail that no longer exists after the rewrite. It failed because it was coupled to implementation, not because the feature broke.
Exercise
You test a SearchBox component that accepts an onSearch prop and calls it with the typed query when the user presses a "Search" button. Is it a behavior test to assert that onSearch was called with 'react' after the user types react and clicks the button? Explain.
Show answer
Yes. onSearch is part of the component's public contract, because the parent relies on it. The test drives the component through the UI by typing and clicking, then checks the value the parent receives. It does not inspect internal state, so refactors inside SearchBox will not break it.