> ## Documentation Index
> Fetch the complete documentation index at: https://lib.findy.co.jp/llms.txt
> Use this file to discover all available pages before exploring further.

# What is component testing? Testing behavior, not internals

> Principles and patterns for component tests with Vitest and Testing Library that verify what users observe, not implementation details.

## 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](https://lib.findy.co.jp/frontend/testing-strategy.md) 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](https://lib.findy.co.jp/frontend/visual-regression-testing.md), 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](https://lib.findy.co.jp/development/testing.md). 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).

```tsx Vitest + Testing Library theme={null}
import { render, screen } from "@testing-library/react";
import { OrderList } from "./OrderList";
import { OrderRow } from "./OrderRow";

const orders = [
  { id: "1001", status: "paid", total: 3200 },
  { id: "1002", status: "pending", total: 1800 },
];

// ❌ Replaces the child component and verifies the props it received
// (passes when the child renders wrongly, fails when the child is inlined)
vi.mock("./OrderRow", () => ({ OrderRow: vi.fn(() => null) }));
render(<OrderList orders={orders} />);
expect(OrderRow).toHaveBeenCalledWith(
  expect.objectContaining({ status: "paid" }),
  expect.anything()
);

// ✅ Renders the real component tree and verifies what the user sees
render(<OrderList orders={orders} />);
expect(screen.getByRole("row", { name: /1001/ })).toHaveTextContent("Paid");
expect(screen.getByRole("row", { name: /1002/ })).toHaveTextContent("Pending");
```

### 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.

> [card] 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.

> [card] 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](https://lib.findy.co.jp/frontend/testing-strategy.md) ("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.

```tsx Vitest + Testing Library theme={null}
import { render, screen } from "@testing-library/react";
import { OrderRow } from "./OrderRow";

// The order type, with the possible values limited by the type
type Order = {
  id: string;
  status: "pending" | "paid" | "shipped";
  shippedAt: string | null;
  total: number;
};

const order: Order = {
  id: "1001", status: "paid", shippedAt: null, total: 3200,
};

// ❌ Verifies values the type already rules out
// (undefined cannot be passed, and an unknown status is a compile error)
render(<OrderRow order={{ ...order, shippedAt: undefined }} />);
render(<OrderRow order={{ ...order, status: "unknown" }} />);

// ✅ Verifies only the values the type allows (null, and the three statuses)
render(<OrderRow order={{ ...order, shippedAt: null }} />);
expect(screen.getByText("Not shipped")).toBeInTheDocument();
```

This division of labor extends to mocks. When backend responses are replaced with the API provider's types attached, a change in the API contract is caught by the type check in the static layer rather than by the component tests. The concrete method is covered under "Type mock responses with the API provider's types" in the patterns below.

## 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.

```tsx Vitest + Testing Library theme={null}
import { render, screen } from "@testing-library/react";
import { OrderSearch } from "./OrderSearch";

const { container } = render(<OrderSearch />);

// ❌ Depends on test attributes and DOM structure
// (cues users never see; fails when the structure is reorganized)
screen.getByTestId("status-select");
container.querySelector("form > button.primary");

// ✅ Uses the same cues users use to find the element
// (keeps passing through structural changes while label and name hold)
screen.getByLabelText("Status");
screen.getByRole("button", { name: "Search" });
```

### 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.

```tsx Vitest + Testing Library theme={null}
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { OrderSearch } from "./OrderSearch";

render(<OrderSearch />);

// ❌ Fires a single change event, which is not what the user does
// (logic that reacts to focus or key events never runs)
fireEvent.change(screen.getByLabelText("Status"), {
  target: { value: "paid" },
});

// ✅ Reproduces the event sequence a browser fires
const user = userEvent.setup();
await user.selectOptions(screen.getByLabelText("Status"), "paid");
await user.click(screen.getByRole("button", { name: "Search" }));
```

### Wait for elements to appear, not for time to pass

An element that appears after data is fetched is awaited with a `findBy` 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`.

```tsx Vitest + Testing Library theme={null}
import { render, screen, waitFor } from "@testing-library/react";
import { OrderSearch } from "./OrderSearch";

render(<OrderSearch />);

// ❌ Waits a fixed time before querying
// (fails when the response is slow, stays slow when it is fast)
await new Promise((resolve) => setTimeout(resolve, 500));
screen.getByRole("table");

// ✅ Waits for the element, and verifies the loading state is gone
expect(await screen.findByRole("table")).toBeInTheDocument();
expect(screen.queryByText("Loading")).not.toBeInTheDocument();

// ✅ Conditions other than presence are awaited with waitFor
await waitFor(() => {
  expect(screen.getAllByRole("row")).toHaveLength(3);
});
```

### 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.

```tsx Vitest + Testing Library theme={null}
import { act, renderHook } from "@testing-library/react";
import { useOrderFilter } from "./useOrderFilter";

const orders = [
  { id: "1001", status: "paid", total: 3200 },
  { id: "1002", status: "pending", total: 1800 },
];

// ❌ Tests a screen-specific hook on its own, duplicating
// the behavior already covered by the component test
renderHook(() => useOrderSearchForm());

// ✅ Verifies a hook shared by several screens through its return value
const { result } = renderHook(() => useOrderFilter(orders));
expect(result.current.filtered).toHaveLength(2);

act(() => {
  result.current.setStatus("paid");
});
expect(result.current.filtered.map((o) => o.id)).toEqual(["1001"]);
```

### 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](https://lib.findy.co.jp/development/testing.md) 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 with `server.use`, and `resetHandlers` after each test removes the override so tests stay independent.

```typescript vitest.setup.ts theme={null}
import { afterAll, afterEach, beforeAll } from "vitest";
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";

export const server = setupServer(
  // The default response, shared by every test
  http.get("/api/orders", () =>
    HttpResponse.json([
      { id: "1001", status: "paid", total: 3200 },
      { id: "1002", status: "pending", total: 1800 },
    ])
  )
);

beforeAll(() => server.listen());
// Remove per-test overrides so tests stay independent
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
```

```tsx Vitest + Testing Library theme={null}
import { render, screen } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import { server } from "../vitest.setup";
import { OrderSearch } from "./OrderSearch";

// ❌ Replaces the data-fetching hook
// (a change in the API response shape goes undetected)
vi.mock("./useOrders", () => ({
  useOrders: () => ({ data: [], error: new Error("failed") }),
}));

// ✅ Overrides the response for this test only and verifies the screen
test("shows an error when fetching fails", async () => {
  server.use(
    http.get("/api/orders", () =>
      HttpResponse.json({ message: "unavailable" }, { status: 500 })
    )
  );
  render(<OrderSearch />);

  expect(await screen.findByRole("alert")).toHaveTextContent(
    "Orders could not be loaded"
  );
});
```

### 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.

```typescript vitest.setup.ts theme={null}
// Types generated from the API provider (an OpenAPI document or GraphQL schema)
import type { Order } from "./api/types";

// ❌ Writes the response shape by hand
// (the misspelled field state goes unnoticed)
// (when the API contract changes, the mock and the tests keep passing)
http.get("/api/orders", () =>
  HttpResponse.json([{ id: "1001", state: "paid", total: 3200 }])
);

// ✅ Types the response through the handler's third type argument
// (a renamed field or a changed type fails the type check before tests run)
http.get<never, never, Order[]>("/api/orders", () =>
  HttpResponse.json([{ id: "1001", status: "paid", total: 3200 }])
);
```

## Related pages

The following pages cover where component tests sit in the layer model, and the layers below and above them.

> [card] [Testing Strategy](https://lib.findy.co.jp/frontend/testing-strategy.md)
>
> The criteria for choosing a layer, and why component tests form the widest part of the integration layer.

> [card] [Test Code](https://lib.findy.co.jp/development/testing.md)
>
> The foundation of this page's principles: resulting state, whole expected values, and boundary mocks.

> [card] [E2E Testing](https://lib.findy.co.jp/frontend/e2e-testing.md)
>
> Protecting the backend wiring that mocks cannot detect, limited to primary journeys.

> [card] [Visual Regression Testing](https://lib.findy.co.jp/frontend/visual-regression-testing.md)
>
> The appearance side of the same layer: what a DOM query cannot see, verified through stories and snapshots.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.