Overview
A component test renders a component, reproduces user interaction, and verifies the result that appears on the screen. In the Testing Trophy it belongs to the integration layer, which verifies behavior with the backend boundary mocked, and the tools are Vitest and Testing Library. See Testing Strategy for the layer model as a whole. This page covers the principles that decide what a component test verifies, and the patterns for writing stable tests with Vitest and Testing Library. Verifying visual appearance is the job of Storybook and visual regression testing, and is out of scope here. The shared principles that keep every test trustworthy (verifying resulting state, verifying the whole expected value, and mocking only external boundaries) are covered in Test Code. This page applies those principles to components.Principles
Verify behavior users can observe, not implementation details
The subject of a component test is what users can see and operate. Testing Library states this as a guiding principle, “The more your tests resemble the way your software is used, the more confidence they can give you”, and exposes only APIs that deal with DOM nodes rather than component instances. A component has two kinds of users: the end user who operates the rendered screen, and the developer who passes props. A test touches the component only from these two positions, and does not depend on implementation details such as internal state, the props passed to child components, or CSS class names. A test that depends on implementation details becomes untrustworthy in two directions. It fails after a pure restructuring (a false negative), and it passes while the screen is broken as long as the internal values match (a false positive).Vitest + Testing Library
Tell narrow unit tests from broad unit tests
The term unit test has two meanings. A narrow unit test targets a single function: pure logic such as computing a total or normalizing a date range is verified in the unit layer through input and output, with no rendering. A broad unit test targets one behavior produced by a combination of hooks and components. React hooks often return functions, so verifying each function in isolation does not guarantee that the screen behaves correctly, and the behavior is tested as a whole. The component tests on this page are broad unit tests in this sense. The two need to be told apart because both run on the same test runner (Vitest) and are often written in the same test file. When the viewpoint that checks a function’s input and output and the viewpoint that checks the behavior of the rendered screen mix in one file, one kind of test tends to grow thick while the other stays thin, and nobody notices. When writing a test, be conscious of which viewpoint it verifies and keep the two apart.Narrow unit test (unit layer)
Input and output of a pure function: a total, a normalized date, a sort comparator. No rendering, verified with Vitest alone.
Broad unit test (integration layer)
A behavior produced by components and hooks together. How the screen changes in response to interaction, verified with Testing Library.
Leave what types can guarantee to the static layer
Component tests stand on top of the static layer. When TypeScript types limit the values that props and state can take, values outside that range (an undefined that cannot be passed, a status that does not exist) are rejected by the compiler, so component tests do not need to verify them. This applies the principle from Testing Strategy (“verify everything at the lowest layer that can catch the failure”) to the boundary between the static and integration layers. Types take over verification in many places. If the type guarantees whether a field can be null or undefined, there is no need to test both cases, and only the one the type allows is verified. A status limited to a union of string literals, or props that distinguish required from optional, work the same way. The more values the type rules out of the tests, the more the component tests concentrate on behavior.Vitest + Testing Library
Patterns with Vitest and Testing Library
The patterns below use an order list screen as the example. The screen consists of a form that filters orders by status and a table that shows the fetched orders. The examples assume Vitest’s global APIs (test, expect, vi) and the matchers from @testing-library/jest-dom.
Find elements the way users find them
Testing Library queries have a priority order. The highest priority goes to queries that find elements through cues visible to every user:getByRole by role and name, getByLabelText by label, and getByText by visible text.
getByTestId is the last resort. A test attribute is neither visible nor audible to users, and an element that cannot be found by role or name may point to an accessibility problem in the UI itself. container.querySelector is not used either, because it depends on DOM structure and fails after a pure restructuring.
Vitest + Testing Library
Reproduce interaction with user-event
User interaction is reproduced with@testing-library/user-event. fireEvent dispatches a single DOM event, while user-event reproduces the sequence of events a browser actually fires, such as the focus change on click or the per-key events while typing.
Call userEvent.setup() at the start of the test and interact through the returned instance. Interactions are asynchronous, so they are awaited.
Vitest + Testing Library
Wait for elements to appear, not for time to pass
An element that appears after data is fetched is awaited with afindBy query. findBy retries until the element appears and fails after one second by default. A fixed delay is unstable when too short and slows the whole suite when too long.
Absence, or disappearance, is verified with a queryBy query. getBy throws when nothing matches, so it cannot assert absence. For conditions other than the presence of an element, use waitFor.
Vitest + Testing Library
Verify screen-independent hooks with renderHook
renderHook runs a hook outside a component and exposes its return value through result.current. It is imported from @testing-library/react, and calls that update state are wrapped in act.
It suits hooks that hold logic shared by several screens, or hooks with no UI of their own. A hook that exists for one screen only is verified through interaction in that screen’s component test. Testing it in both places duplicates the same behavior and doubles the places to fix on every change.
Vitest + Testing Library
Mock only the backend boundary
The only thing a component test mocks is the boundary with the backend. Responses are replaced at the network boundary with Mock Service Worker (msw). From the component’s point of view a real HTTP request is made, so the API client and the data-fetching hook run unchanged, and the test catches mistakes down to how the mocked response is interpreted. Child components, hooks, and state stores are not replaced. They are the parts that produce the component’s behavior, and replacing them is the situation that pattern 3 of Test Code describes as mocking the logic under test. A test built that way keeps passing no matter how the implementation changes. For external boundaries other than the network, such as the current time or random values, see the same page. The default responses are registered in the setup file. A test-specific response, such as an error, is overridden for that test alone withserver.use, and resetHandlers after each test removes the override so tests stay independent.
vitest.setup.ts
Vitest + Testing Library
Type mock responses with the API provider’s types
As long as msw replaces the responses, the component tests keep passing even after the real API contract changes. To keep the handlers from drifting away from the real API, obtain type information from the API provider and type the handler responses with it. The types come from an OpenAPI document or a GraphQL schema, or from type definitions shared with the backend. With the types in place, a change in the API contract is caught by the type check in the static layer, not by the component tests. The component tests keep running on mocks that are known to be valid, and guaranteeing the correctness of the mocks through types is what sustains the quality of the tests in this layer. This applies the division of labor with the static layer, described under the principles, to mocks.vitest.setup.ts
Related pages
The following pages cover where component tests sit in the layer model, and the layers below and above them.Testing Strategy
The criteria for choosing a layer, and why component tests form the widest part of the integration layer.
Test Code
The foundation of this page’s principles: resulting state, whole expected values, and boundary mocks.
E2E Testing
Protecting the backend wiring that mocks cannot detect, limited to primary journeys.
Visual Regression Testing
The appearance side of the same layer: what a DOM query cannot see, verified through stories and snapshots.