Skip to content

React Testing Without Theater

Tests tied to visible user behavior are less coupled to DOM structure, component boundaries and internal state. As a result, they survive certain refactorings without changes.

≈ 11 min readSoftwareTesting

React Testing Without Theater

A green test doesn’t prove that the application works. At first, it only proves that the code still looks the way it did on the day the test was written. React suites like to blur exactly this difference: every component is surrounded by mocks, every assertion knows the hook, the state, the name of the internal function. Such tests turn red in droves at the first refactoring, even though the application still works unchanged from a domain point of view – expensive to maintain and saying nothing about the product. That is the theater in the title: lots of stage, little substance.

The occasion for this post is mundane: a small Vite React app from the introduction-react repo, a single test, one visible line in the UI. What’s interesting is not the line but the boundary it draws – between what a user experiences and how I built it internally. This boundary is the real architectural decision in testing. If you draw it cleanly, you get tests that survive rebuilds. If you miss it, you get a suite that has to be maintained every sprint and still doesn’t catch a regression.

The thesis: behavior beats implementation#

A test has exactly two jobs. It should catch real misbehavior before it reaches the user. And it shouldn’t stop me from restructuring the code. These two goals are in tension, and the resolution is: test what the user observes, not how the component achieves it internally.

The difference becomes visible in two variants of the same test. First, the brittle variant that couples to the internals:

// Brittle: couples the test to internal state and structure
test("increments the count state", () => {
  const { result } = renderHook(() => useCounter());

  act(() => result.current.increment());

  expect(result.current.count).toBe(1);
});

This test knows the hook, its return value and that “increment” is called that. As soon as I replace useCounter with a reducer, a store or a completely different mechanism, it breaks – even though the counter in the browser keeps doing what it should. The test measures my implementation, not the product.

Now the same assertion via observable behavior:

// Robust: asserts what the user actually sees
test("shows the new count after a click", async () => {
  const user = userEvent.setup();
  render(<Counter />);

  await user.click(screen.getByRole("button", { name: /increment/i }));

  expect(screen.getByRole("status")).toHaveTextContent("Count: 1");
});

This test knows nothing about hooks, state or structure. It knows that there is a button you click, and that a number appears afterwards. That is exactly the contract with the user. I can swap out all the internals, and as long as this contract holds, the test stays green. This is the point at which a test turns from a brake on restructuring into a safety net.

Where the boundary physically runs#

This boundary is not an attitude; it is built into the query design of Testing Library. The order of the queries is a statement about trade-offs: getByRole and getByLabelText first, getByText after that, getByTestId as a last resort. That isn’t a matter of style. A role query checks accessibility along the way – if the test finds the element by its role, a screen reader finds it too. A data-testid only checks that I stuck a label on myself.

// Prefer accessible queries – they double as an a11y assertion
screen.getByRole("searchbox");
screen.getByRole("button", { name: /search/i });

// testid is an escape hatch, not the default
screen.getByTestId("product-list");

The practical consequence: I write components so that they can be addressed through roles and labels – semantic elements, aria-label where needed, real <button> instead of clicked <div>. The test forces me into accessible markup, because inaccessible markup is simply hard to test. That’s the kind of coupling I want: testability and product quality pull in the same direction.

So the testid isn’t forbidden; it just needs a justification. It is legitimate when a container has no meaningful role – a layout wrapper, a chart canvas, a list without a semantic counterpart. Then a deliberately set data-testid is more honest than a forced role that doesn’t even exist in the product. The difference is the order: I reach for the testid because the accessible query doesn’t fit, not because it was too cumbersome for me. This order is the entire methodical substance of the query priorities – it makes the exception visible instead of letting it become the rule.

The failure path is half the work#

The happy path looks clean in demo mode. You earn your money with the rest: empty response, timeout, 500 errors, a double click, a slow connection. In React applications, this rest almost always sits at the network boundary, and that’s exactly where I put the mock – not on the hook, not on the fetch call, but at the HTTP layer. With Mock Service Worker, the component runs through its real data logic; only the response is controlled.

// The happy path: results the API returned actually render
test("renders products returned by the API", async () => {
  const user = userEvent.setup();
  render(<ProductSearch />);

  await user.type(screen.getByRole("searchbox"), "react");
  await user.click(screen.getByRole("button", { name: /search/i }));

  expect(await screen.findByRole("listitem"))
    .toHaveTextContent("React Handbook");
});

And the flip side, which makes the difference in production:

// The failure path: does the UI degrade gracefully?
test("shows an error message when the request fails", async () => {
  server.use(
    http.get("/api/products", () => HttpResponse.error()),
  );

  const user = userEvent.setup();
  render(<ProductSearch />);

  await user.click(screen.getByRole("button", { name: /search/i }));

  expect(await screen.findByRole("alert"))
    .toHaveTextContent(/something went wrong/i);
});

The second test is more important than the first. It describes what happens when the backend goes away – whether the app shows an error message or falls into an empty, confusing state. That I set the mock per test via server.use is intentional: the default is the happy path, and the disruption is an explicit, readable deviation. If you don’t test the failure path, you haven’t tested half the product. The user experiences both.

Async discipline is part of the failure path too. findBy* waits for an element to appear, waitFor for a condition to hold – but only for observable states, not for guessed setTimeout values. If you build in fixed wait times instead, you trade flakiness for slowness and end up keeping both.

Specification by Example: tests that speak the domain language#

The most stable test names a domain intent, not a technical sequence. A test name like “calls dispatch with INCREMENT” describes mechanics and ages with every rename. “shows the new count after a click” describes a promise to the user and only ages when the promise changes. That is the core of Specification by Example: the example is domain documentation, expectation and automatable check at the same time – three things that otherwise drift apart.

In practice, this means I write the describe and test blocks so that a product owner could read and confirm them without knowing the code:

describe("Product search", () => {
  test("shows results matching the query", async () => { /* ... */ });
  test("shows an empty state when nothing matches", async () => { /* ... */ });
  test("shows an error when the service is unavailable", async () => { /* ... */ });
});

This suite is a specification. It says what the feature can do and what it does when something goes wrong. A reviewer sees immediately whether a case is missing – the empty state, the error case – and can object on domain grounds without reading the implementation. This is exactly where the methodical lever lies: misunderstandings become visible in the test, not only in production. That moves the expensive clarification from the end of the chain to the beginning.

The architecture of the suite: layers instead of mass#

Not every test costs the same or delivers the same. A sustainable React suite is layered. Pure logic – formatting, validation, reducers – I check with fast unit tests without a DOM. The behavior of the components I check with component tests with a mocked network boundary; that’s the layer in which I invest the most trust and the most time. And I keep a small number of real integration runs that play through the actual interplay of the parts once instead of simulating it.

flowchart TD
  A[User intent<br/>Specification by Example] --> B[Component tests<br/>role and label queries]
  B --> C[Network boundary<br/>mocked with MSW]
  C --> D[Few integration runs<br/>real wiring]
  D --> E[Refactor<br/>tests stay green]
  E --> A

The distribution is a deliberate investment decision, not dogma. Many slow end-to-end tests give you a warm feeling and a cold pipeline: they are slow, flaky and expensive to maintain, and when they turn red, nobody knows right away why. A few targeted integration runs plus a dense, fast component layer catch more real bugs per minute invested. The test run belongs in the developer’s fast feedback loop, not only in the nightly CI – hence Vitest and jsdom instead of a real browser, wherever the statement allows it.

Why it pays off#

Testing is not an end in itself and not a way to soothe your conscience; it is an investment with a measurable return. The yield is speed of change. A suite that couples to behavior allows refactoring without fear: I turn useCounter into a store, the tests stay green, and I know the contract holds. A suite that couples to implementation turns every refactoring into a second project – first restructure the code, then update dozens of tests. The second kind leads teams to postpone restructuring. That’s how technical debt arises not despite the tests but because of them.

The concrete advantage lies in lower coupling. If a test accesses the UI through role, label and visible result, I can split components, move internal state or rearrange the markup as long as the observable behavior stays the same. Whether reviews get shorter or the regression rate drops, on the other hand, depends on the suite, the run time and the failure paths actually checked.

Typical mistakes#

The first mistake is confusing the tool with the solution. Testing Library doesn’t produce good tests; it only makes bad ones harder. You can still stick to testids with it, inspect state through detours and cut the network boundary at the wrong point. The tool expresses a boundary; it doesn’t draw it.

The second mistake is confusing coverage with safety. Ninety percent line coverage says nothing about whether the failure path is checked. A suite that covers every happy path and no failure case has high numbers and low value. I’d rather count failure cases than lines.

The third mistake is mocking everything. If you mock the hook, mock the store and mock the child component, in the end you are only testing the mocks. The deeper the mock sits, the less real behavior runs through the test. The network boundary is almost always the right cut – behind it begins someone else’s code, in front of it lies my product.

How I check a test#

Before a test is allowed into the suite, I ask it three questions. Would it turn red if the feature broke from a domain point of view? If not, it checks nothing. Does it stay green if I restructure the implementation without changing the behavior? If not, it’s a brake on restructuring. And does its name describe a user intent that a domain expert could confirm? If not, it ages with the next rename.

A test that passes all three questions is cheap to maintain and expensive only once – when it’s written. A test that fails one of them gets paid for again every sprint. Over the lifetime of a project, this difference decides whether the suite creates trust or a maintenance burden.

Further reading#

The repo shows the small Vite React app and the test examples in the context of a complete learning curve from building block to architecture. The docs of Testing Library and Vitest help you cross-check query priorities and async behavior – but the real point remains the decision of where, in the concrete example, the boundary between behavior and implementation runs.

Conclusion#

React testing becomes valuable when tests answer a question the user cares about: does the application do what it should, even when something goes wrong? A test that simulates a click and checks a visible result stays stable through internal restructuring as long as the domain case stays the same. That is the solid advantage; speed or error rate have to prove themselves in the project.

Revised and translated from German with the help of AI.