> ## 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 visual regression testing? Detecting visual changes

> Writing Storybook stories as the UI specification, choosing between the play function and component tests, and reviewing visual changes in the pull request.

## Overview

Visual regression testing (VRT) renders every Storybook story, captures a screenshot, and compares it with the last approved screenshot to detect unintended changes in appearance. In the Testing Trophy it belongs to the integration layer next to component tests: component tests verify behavior, and VRT verifies appearance. See [Testing Strategy](https://lib.findy.co.jp/frontend/testing-strategy.md) for the layer model as a whole.

Appearance here means what a component test cannot see. A component test queries the DOM, so when a button has lost its padding or a table overflows the viewport, the test still passes. Layout, spacing, color, typography, and how they hold up across screen widths are verified by comparing pixels.

This page covers how to write stories so that they serve as the UI specification, when to use Storybook's play function instead of a component test, and how to run VRT as part of the pull request. Behavior tests with Vitest and Testing Library are covered in [Component Testing](https://lib.findy.co.jp/frontend/component-testing.md).

## Stories are the UI specification

A **story** is a rendered instance of a component in one specific state: a fixed set of props and a fixed backend response. Collected together, the stories of a component enumerate every state it can show, and that is what makes them a specification rather than a demo.

Stories play three roles at once, and every role depends on the same set of stories being complete.

> [card] UI catalog
>
> Shows how each part and screen renders in the browser the product runs in, without starting the application or preparing data.

> [card] UI variation per state
>
> Identifies the display states one UI can take, such as loading, data patterns, and permissions, and lets you vary args in the Controls panel to see how the UI changes.

> [card] Specification and tests
>
> Verifies that the UI behaves and looks as intended, through VRT, interaction tests run by the Vitest addon, and accessibility checks by the a11y addon, all on the same stories.

A story that is missing a state is missing from all three roles: nobody sees the state in the catalog, nobody can tell it apart from the others, and no test covers it.

### Write one story per visible state

Each state a component can display gets its own named story. For a list that fetches data, that is at least the default state with data, the loading state, the empty state, and the error state. A single story whose state is changed through the Controls panel is not a test case, because nothing renders it in those states.

Define `args` as a typed variable rather than inline in the meta, and take the mock data from the same fixtures as the component tests. When both use the same data, the state the test verifies and the state the story shows are the same state, and a renamed prop fails the type check in the story file as well.

```tsx OrderList.stories.tsx theme={null}
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { ComponentProps } from "react";
import { OrderList } from "./OrderList";
// Fixtures shared with the component tests
import { orders } from "./testing/orders";

type Component = typeof OrderList;
type Story = StoryObj<Component>;

// args as a typed variable, so a renamed prop fails the type check here
const args = {
  orders,
  isLoading: false,
  error: null,
} satisfies ComponentProps<Component>;

const meta = { component: OrderList, args } satisfies Meta<Component>;
export default meta;

// ❌ One story that covers "everything" through the Controls panel
// (nothing ever renders the loading, empty, or error state)
export const Playground: Story = {};

// ✅ One story per visible state; each is a review item and a test case
export const Default: Story = {};
export const Loading: Story = { args: { isLoading: true } };
export const Empty: Story = { args: { orders: [] } };
export const LoadFailed: Story = {
  args: { error: new Error("Orders could not be loaded") },
};
```

### Render in the context the component lives in

A component rendered alone on a blank canvas does not show how it looks in the product. A card that stretches to its parent's width fills the whole viewport, and a component that reads the router, the locale, or the theme from context does not render at all.

Decorators wrap every story in the surroundings it needs. Project-wide providers (router, internationalization, theme, the mocked API client) go in the preview file so that every story gets them, and width or layout constraints go on the component's meta. The story then renders under the same conditions as the screen it belongs to, and the snapshot shows what users see.

```tsx .storybook/preview.tsx theme={null}
import type { Preview } from "@storybook/react-vite";
import { AppProviders } from "../src/AppProviders";

const preview: Preview = {
  decorators: [
    // Every story renders inside the same providers as the application
    (Story) => (
      <AppProviders>
        <Story />
      </AppProviders>
    ),
  ],
};

export default preview;
```

```tsx OrderCard.stories.tsx theme={null}
import type { Meta } from "@storybook/react-vite";
import { OrderCard } from "./OrderCard";

// ❌ Rendered alone, the card stretches to the full width of the canvas
const metaWithoutLayout = {
  component: OrderCard,
} satisfies Meta<typeof OrderCard>;

// ✅ A decorator gives the card the width it has inside the order list
const meta = {
  component: OrderCard,
  decorators: [
    (Story) => (
      <div style={{ width: 360 }}>
        <Story />
      </div>
    ),
  ],
} satisfies Meta<typeof OrderCard>;
export default meta;
```

### Put stories at the top of the component tree

Stories go on the component that assembles a screen or a section, and on reusable parts that appear in several places. A child that only ever appears inside one parent is already covered by the parent's stories, and gets its own only when the parent's stories cannot show all of its states, for example a row with many status variants.

Rendering at the top shows the component in its real composition, which is where layout regressions appear. It also keeps the number of stories, and with it the cost of review and snapshots, proportional to the number of screens rather than the number of files. A story on a child shows the child's own states (boundary values, error text) and does not reproduce the parent's responsibilities.

### Mock the backend boundary the same way as in component tests

Stories mock the same boundary as component tests: the network. With the Mock Service Worker addon, the default handlers are registered in the preview file and a story overrides them in `beforeEach`, so a story can show an error response without changing the component. The test provider of a GraphQL client works the same way.

The loading state is produced by a response that never resolves. This keeps the story deterministic, because a response that resolves after a delay produces a different screenshot depending on when the capture happens.

```tsx .storybook/preview.tsx theme={null}
import type { Preview } from "@storybook/react-vite";
import { http, HttpResponse } from "msw";
import { mswLoader } from "msw-storybook-addon/csf3";
import { orders } from "../src/orders/testing/orders";

// The decorators from the previous example are omitted here
const preview: Preview = {
  loaders: [mswLoader()],
  // The default response, shared by every story
  beforeEach({ msw }) {
    msw.use(http.get("/api/orders", () => HttpResponse.json(orders)));
  },
};

export default preview;
```

```tsx OrderSearch.stories.tsx theme={null}
import type { Meta, StoryObj } from "@storybook/react-vite";
import { delay, http, HttpResponse } from "msw";
import { OrderSearch } from "./OrderSearch";

const meta = { component: OrderSearch } satisfies Meta<typeof OrderSearch>;
export default meta;
type Story = StoryObj<typeof meta>;

// Uses the default handlers registered in .storybook/preview.tsx
export const Default: Story = {};

// ✅ Overrides the response for this story only
export const LoadFailed: Story = {
  beforeEach({ msw }) {
    msw.use(
      http.get("/api/orders", () =>
        HttpResponse.json({ message: "unavailable" }, { status: 500 })
      )
    );
  },
};

// ✅ A response that never resolves keeps the loading state on screen
export const Loading: Story = {
  beforeEach({ msw }) {
    msw.use(
      http.get("/api/orders", async () => {
        await delay("infinite");
      })
    );
  },
};
```

## Interaction tests with the play function

A story shows a state that can be reached through props and backend responses. Some states can only be reached through interaction: a menu that is open, a form after a failed submit, a list after a filter has been applied. The **play function** fills this gap.

### Reach a state through interaction, then capture it

`play` runs after the story renders, in a real browser, and receives the rendered canvas and a `userEvent` instance in its context. Queries on `canvas` are the same Testing Library queries as in component tests, `expect` and `fn` come from `storybook/test`, and `step` groups interactions under a label in the Interactions panel. Interactions are asynchronous and are awaited.

An interaction test has two outputs: the assertions inside `play`, and the screen after `play` has finished. The second one is what VRT captures, so a state reached through interaction becomes a snapshot like any other story.

```tsx OrderSearch.stories.tsx theme={null}
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, fn } from "storybook/test";
import { OrderSearch } from "./OrderSearch";

const meta = {
  component: OrderSearch,
  // A spy as the callback, so play can assert that it was called
  args: { onSearch: fn() },
} satisfies Meta<typeof OrderSearch>;
export default meta;
type Story = StoryObj<typeof meta>;

// ✅ Reaches the filtered state through interaction; the snapshot
// captures the screen in that state
export const FilteredByPaid: Story = {
  play: async ({ canvas, userEvent, args, step }) => {
    await step("Filter by status", async () => {
      await userEvent.selectOptions(canvas.getByLabelText("Status"), "paid");
      await userEvent.click(canvas.getByRole("button", { name: "Search" }));
    });
    await expect(args.onSearch).toHaveBeenCalledWith({ status: "paid" });
    await expect(
      await canvas.findByRole("row", { name: /1001/ })
    ).toBeVisible();
  },
};
```

### Use play for states and component tests for behavior

Storybook's documentation notes that interaction tests can be expensive to maintain when applied to every component. On this site an interaction test exists to put the screen into a state worth looking at, and a component test exists to verify behavior branches. Writing the same assertions in both places doubles the maintenance cost without adding confidence.

> [card] Interaction test (play function)
>
> Runs in a real browser, reaches a state through interaction, and leaves the screen there for the snapshot. One per state worth seeing: an open dialog, a filled form, a filtered list.

> [card] Component test (Vitest + Testing Library)
>
> Verifies behavior branches through the DOM, fast and without a browser. One per branch: each validation rule, each status, each error.

The Vitest addon for Storybook runs every story, including its play function, as a Vitest test in a real browser, so interaction tests run in the pull request pipeline on the same runner as the component tests.

> [!NOTE]
>
> Storybook's documentation describes its testing experience as built around component tests, and the Storybook UI labels the run of play functions as "Run component tests". On this site, component test refers to the Vitest and Testing Library tests described in [Component Testing](https://lib.findy.co.jp/frontend/component-testing.md), and a test written in a story's play function is called an interaction test.

## How VRT works and runs

### How a story becomes a snapshot test

A VRT service builds Storybook, renders every story in a cloud browser, and captures a screenshot. The screenshot is compared pixel by pixel with the **baseline**, the last screenshot of that story that a reviewer accepted, and a story whose pixels differ beyond a threshold is reported as changed.

Comparing pixels rather than the rendered HTML is what makes this a test of appearance. A snapshot of the DOM changes whenever the markup changes, even when nothing visible moved, and stays the same when a stylesheet breaks the layout. The pixel comparison catches the second case and ignores the first.

The examples below use Chromatic. Other tools, such as a self-hosted pipeline that captures stories and compares the images, or the screenshot assertions of a browser automation tool, follow the same model of snapshot, baseline, and review.

### Chromatic

Chromatic is a visual testing service built by the Storybook maintainers. Each time it runs in CI, it builds the Storybook, publishes it at a shareable URL, renders every story in cloud browsers, and compares the snapshots with their baselines. It also works with Playwright and Cypress tests, but the Storybook integration is its primary use.

> [card] Storybook publishing
>
> Every build publishes the Storybook at a shareable URL, so designers and product managers review components without a local environment.

> [card] UI Tests
>
> Compares each story's snapshot with its baseline and reports the changed stories as a status check on the pull request.

> [card] UI Review
>
> Shows the visual changes between the pull request branch and its base branch, independent of baselines, so designers and reviewers can sign off on them.

> [card] TurboSnap
>
> Uses the git history and the bundler's dependency graph to snapshot only the stories affected by the change.

The Visual Tests addon runs the same tests from the Storybook UI, so a developer can review and accept changes locally before pushing, and the accepted baselines carry over to the build in CI.

### Review visual changes in the pull request

The result of a VRT run is not pass or fail but a list of changed stories, and a person decides what each change is. The service reports the changes as a status check on the pull request, and the check does not pass until every change has been reviewed.

Accepting a change makes the new screenshot the baseline for that story. Denying it marks a regression and fails the check, so the author fixes the component and pushes again. Accepted baselines follow the branch: after the pull request merges, the default branch inherits them, so a change is reviewed once rather than on every branch.

Who reviews depends on the change. The author accepts changes they intended and can explain. A change the author did not expect is a regression or a side effect of a shared component, and goes back to the code. A change to the design itself is reviewed by the designer in the published Storybook, which is the same artifact the snapshots came from.

The service finds the baseline by walking the git history to the nearest ancestor commit that has a build, so the pipeline runs on every push, including pushes to the default branch, and checks out the full history. Snapshotting only the stories whose dependency graph changed keeps the cost of each build proportional to the change.

```yaml .github/workflows/visual-regression.yml theme={null}
on:
  # Every push, including the default branch, so that baselines exist
  # for the branch a pull request is compared against
  push:

jobs:
  visual-regression:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          # Full history, so the service can find the baseline build
          fetch-depth: 0
      - run: npm ci
      - run: npm run build-storybook
      - uses: chromaui/action@latest
        with:
          projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
          storybookBuildDir: storybook-static
          # Snapshot only the stories affected by the changed files
          onlyChanged: true
```

### Keep snapshots deterministic

A snapshot that differs between two runs of the same code is a false positive, and false positives are what make a team stop reading the list of changes. Every source of variation is removed on the story side.

* **Dates and times.** Pin the current date the component depends on, through a prop or a mocked clock, so that "today" is the same date on every run.
* **Random data.** Fixtures are fixed values, never generated at render time.
* **Animations.** Chromatic pauses CSS animations at their last frame by default. Animations driven by JavaScript are disabled when the story runs under the service.
* **Asynchronous content.** Wait for it in `play` with `findBy` or `waitFor` instead of a fixed delay, so the capture happens when the content is there.
* **Fonts.** Serve web fonts from the project so that the browser does not fall back to a different typeface on one run.

Stories that exist only to run an interaction, or that show content that cannot be made stable, are excluded from snapshots. Sub-pixel rendering noise is absorbed by raising the diff threshold slightly, not by excluding the story.

```tsx OrderCalendar.stories.tsx theme={null}
import type { Meta, StoryObj } from "@storybook/react-vite";
import { OrderCalendar } from "./OrderCalendar";

const meta = {
  component: OrderCalendar,
  parameters: {
    // The default threshold is .063; raise it only to absorb
    // sub-pixel rendering noise, never to hide a layout change
    chromatic: { diffThreshold: 0.1 },
  },
} satisfies Meta<typeof OrderCalendar>;
export default meta;
type Story = StoryObj<typeof meta>;

// ❌ "Today" moves every day, so the snapshot changes every day
export const Unpinned: Story = {};

// ✅ Pins the date the component depends on
export const Today: Story = {
  args: { today: new Date("2026-04-01") },
};

// ✅ Excludes a story that exists only to run an interaction
export const KeyboardNavigation: Story = {
  parameters: { chromatic: { disableSnapshot: true } },
  play: async ({ canvas, userEvent }) => {
    await userEvent.click(canvas.getByRole("gridcell", { name: "15" }));
    await userEvent.keyboard("{ArrowRight}");
  },
};
```

### What VRT is for

> [card] Suited
>
> Layout, spacing, color, and typography. Breakpoints and themes rendered as viewport and theme variants. Shared components whose change ripples into many screens. Design review by people without a local environment.

> [card] Not suited
>
> Behavior branches and data correctness, which component tests verify through the DOM. Wiring to the real backend, which E2E tests verify. Content that cannot be made deterministic. Screens with so many states that the snapshot count outgrows what reviewers read.

The cost of VRT scales with the number of stories times the number of variants, and is paid on every build in snapshots and in review time. The story conventions above keep the count proportional to the number of screens, and change-based snapshot selection keeps the cost of each build proportional to the change.

> [!NOTE]
>
> The capture tool behind VRT has to keep up with Storybook's releases, and when its maintenance stops, Storybook itself can no longer be upgraded. Prefer a tool maintained alongside Storybook, or one built on the same browser automation as the rest of the test suite.

## Related pages

The following pages cover where VRT sits in the layer model, the behavior tests it pairs with, and the review it becomes part of.

> [card] [Testing Strategy](https://lib.findy.co.jp/frontend/testing-strategy.md)
>
> The criteria for choosing a layer, and why appearance and behavior share the integration layer.

> [card] [Component Testing](https://lib.findy.co.jp/frontend/component-testing.md)
>
> The behavior side of the integration layer: verifying what users can do, with Vitest and Testing Library.

> [card] [Code Review](https://lib.findy.co.jp/development/code-review.md)
>
> How a pull request is reviewed, and where the review of visual changes fits in.


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