Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 132 ยท Testing and Quality

Storybook and Visual Testing

Learn Storybook with React - writing stories, args, decorators, play-function interaction tests, accessibility checks and visual regression testing - with runnable stand-ins you can edit.

Most of the testing you have seen so far checks behavior: click a button, expect some text. Testing React components and end-to-end testing are great at that. But a large part of what makes a UI correct is how it looks: spacing, colors, a long label that wraps, a disabled state, a dark theme. A unit test with getByText happily passes while the button has become invisible.

Storybook is a tool for building and checking components in isolation. You write small files called stories, each showing a component in one specific state. Storybook displays them in a catalog, and the same stories then become documentation, interaction tests and the input for visual regression testing, which compares screenshots to catch accidental design changes. This lesson explains how all of that fits together.

Storybook and the testing tools are npm packages that our editor cannot load, so the real configuration and test code on this page is read-only (Storybook 9 or later style). Two runnable examples let you experiment with the ideas: a miniature story gallery with a play function, and a tiny pixel-comparison engine. They are teaching stand-ins, not the real tools.

Why develop components in isolation?

Building a component inside the running app means you must click through the app to reach the state you want to see: log in, open a menu, trigger an error. Some states are hard to reach at all (the loading state of a slow request, the empty list, a 500-character username). In isolation you describe the state directly with props, so every state is one click away.

One story file therefore serves several purposes at once:

flowchart LR
    S["Stories<br/>Button.stories.jsx"] --> C["Catalog<br/>browse every state"]
    S --> D["Documentation<br/>props table and examples"]
    S --> I["Interaction tests<br/>play functions"]
    S --> A["Accessibility checks<br/>axe on each story"]
    S --> V["Visual tests<br/>screenshot per story"]

A story is written once and reused: for people to look at, and for machines to test.

Writing stories

A story file lives next to its component. It uses the Component Story Format (CSF): a default export describing the component, and named exports, one per story. Each story is mostly a set of args, which are the props.

JSX
// Button.stories.jsx (needs storybook)
import { fn } from 'storybook/test';
import { Button } from './Button';

const meta = {
  title: 'Example/Button',
  component: Button,
  tags: ['autodocs'],              // generate a documentation page
  args: { onClick: fn() },         // a spy, shown in the Actions panel
  argTypes: {
    variant: { control: 'select', options: ['primary', 'danger', 'ghost'] },
  },
};
export default meta;

export const Primary = { args: { variant: 'primary', children: 'Save' } };
export const Danger = { args: { variant: 'danger', children: 'Delete' } };
export const Disabled = { args: { children: 'Save', disabled: true } };
export const LongLabel = {
  args: { children: 'A very long label that should wrap or truncate nicely' },
};

Things to notice:

  • Args are the inputs. Storybook builds a Controls panel from them (and from argTypes or TypeScript types), so designers and teammates can change props live and see the result.
  • fn() creates a spy function. Click events are listed in the Actions panel, and tests can assert on them.
  • Stories are cheap. Cover the states that matter: default, each variant, disabled, loading, error, empty, long text, right-to-left, small and large screens. The LongLabel story is the kind of case that finds layout bugs.
  • A story can have a custom render function when a component needs more than props, such as a parent wrapper or several components together.

Setup is two commands, npx storybook@latest init to configure the project and npm run storybook to start it. The configuration lives in a .storybook folder:

JSX
// .storybook/preview.jsx
import '../src/index.css';                       // global styles, once
import { ThemeProvider } from '../src/theme';

export const decorators = [
  (Story) => (
    <ThemeProvider>
      <Story />
    </ThemeProvider>
  ),
];

export const parameters = {
  layout: 'centered',
};

A decorator wraps every story, which is how you supply what components expect from the app: context providers, a router (see client-side routing), a data client. Decorators can also be set per component or per story. Components that fetch data should receive their data through props or a mocked provider in stories, so a story never depends on a live server; see fetching data for how to separate the two.

A runnable story gallery

Below is a stand-in that mimics what Storybook does with a story file: it takes the meta object and a table of stories, renders each one in a card with the merged args, and runs the story's play function after it mounts. Two stories simulate a user clicking a like button. The last one makes a wrong assertion on purpose, so you can see what a failing interaction test looks like.

A hand-written mini Storybook

The first four stories only render. ClickToLike shows "play function passed": the code clicked the button, waited, and found the text Liked (1). WrongExpectation shows a red message, expected "Liked (2)" but got "Liked (1)", which is how Storybook's Interactions panel and test runner report a broken assertion. Use the controls at the bottom to change the playground's variant and disabled state, which is what the real Controls panel does with args. Try editing a story's args (for example give Danger a different label) and run again.

Interaction tests with play functions

A play function runs after a story renders and drives it like a user would. It uses Testing Library's queries and userEvent (re-exported from Storybook's test package) and Vitest's expect:

JSX
// LoginForm.stories.jsx
import { expect, fn, userEvent, within } from 'storybook/test';
import { LoginForm } from './LoginForm';

export default { component: LoginForm, args: { onSubmit: fn() } };

export const FilledAndSubmitted = {
  play: async ({ canvasElement, args }) => {
    const canvas = within(canvasElement);
    await userEvent.type(canvas.getByLabelText('Email'), '[email protected]');
    await userEvent.type(canvas.getByLabelText('Password'), 'correct horse');
    await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
    await expect(args.onSubmit).toHaveBeenCalledWith({ email: '[email protected]', password: 'correct horse' });
  },
};

export const ShowsValidationErrors = {
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
    await expect(await canvas.findByText('Email is required')).toBeInTheDocument();
  },
};

Queries are the same ones you use in React tests: by role and label first, never by CSS class. The Interactions panel lets you step through the play function and replay it, which is far easier than debugging a headless test. Because the play function is part of the story, the story is the test, and it also doubles as a demo of the interaction.

To run these checks automatically (for example in CI), Storybook offers a Vitest integration in recent versions and the older @storybook/test-runner based on Playwright. Both open every story in a real browser and fail the run if rendering throws or a play function fails. If you prefer to keep ordinary unit tests, composeStories imports your stories into Vitest or Jest so you can reuse their args and decorators: const { Primary } = composeStories(stories) then render(<Primary />). Stories are also a natural home for per-component accessibility tests; the accessibility add-on runs the axe engine on each story and flags missing labels or low contrast (read more in accessibility testing and accessibility in React). Remember that automated checks find only part of the problems.

Visual regression testing

Interaction tests prove that something works. They cannot tell you that a CSS change moved the button 12 pixels left. Visual regression testing takes a screenshot of each story and compares it with an approved baseline image. If the pictures differ, a person reviews the difference and decides whether it is an intentional design change (accept, the new image becomes the baseline) or a bug (fix the code).

flowchart TD
    A["Code change or pull request"] --> B["Build Storybook"]
    B --> C["Screenshot every story<br/>in a controlled browser"]
    C --> D["Compare with baseline images"]
    D -->|"no differences"| E["Check passes"]
    D -->|"differences"| F["Reviewer inspects the diff"]
    F -->|"intentional"| G["Accept: new baseline"]
    F -->|"bug"| H["Fix the code and run again"]

Visual tests do not decide what looks right. They make every visual change visible so that a human can.

The usual tools are Chromatic (a cloud service from the Storybook team that also gives you review UI), Playwright's own expect(page).toHaveScreenshot(), and services like Percy or open-source options such as Lost Pixel and Argos. They differ in hosting and price, not in principle.

How the comparison works

At its core the comparison is a loop over pixels. The next example uses tiny 20 by 5 "screenshots" made of characters, so you can see the whole process. It computes how many pixels differ, ignores tiny brightness differences (the tolerance that absorbs anti-aliasing noise) and prints a diff map where X marks a changed pixel.

JS A tiny pixel-comparison engine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first picture is the baseline. Unchanged code produces 0 different pixels. A fill that is slightly lighter (brightness 60 instead of 40) stays within the tolerance of 25 and still passes. The wider button fails: 11 pixels differ, three new columns on the right edge plus the label that moved, and the map shows exactly where. Real tools do the same on millions of pixels, and many compare perceptually rather than channel by channel. Setting the tolerance is a trade-off: too strict and every font-rendering hiccup is a failure, too loose and real regressions slip through.

Keeping visual tests stable

Flaky visual tests teach teams to ignore them, so the main work is removing sources of noise:

  • Same environment every time. Fonts, anti-aliasing and scrollbars differ by operating system. Run screenshots in the same container or in the vendor's cloud, not on each developer's laptop.
  • Freeze time and randomness. A story that shows "3 minutes ago", today's date or a random avatar changes on every run. Pass fixed data through args.
  • Stop animations. Disable CSS transitions and animations in screenshot mode (see animation) or wait for them to finish; also respect prefers-reduced-motion.
  • Wait for fonts and images. Screenshot only after web fonts and images have loaded, and use local assets in stories.
  • No network. Stories should render from props or mocked data, never from a live API.
  • Keep stories focused. One state per story gives clear diffs. A giant story of a whole page makes every diff a puzzle.

Where Storybook and visual tests fit

You do not need to put everything in Storybook. A reasonable split:

  • Design-system and shared components (buttons, inputs, modals, tables): stories for every state, interaction tests for complex ones, visual tests on all of them. This is where the investment pays off most; see component design and UI libraries.
  • Feature components with tricky states (empty, loading, error): a few stories each.
  • Whole pages and flows: end-to-end tests with Playwright, optionally with screenshot assertions.
  • Pure logic and hooks: plain unit tests (testing hooks and logic). No story needed.

Costs to keep in mind: stories are code that needs maintenance, visual tests need review time for every accepted change, and a catalog nobody opens stops being documentation. Start with the components that many people use and that break easily, and grow from there.

Common mistakes

  • Stories that depend on the real app: a live API, a logged-in user, today's date. They break for reasons unrelated to the component.
  • Using visual tests instead of behavior tests, or the reverse. They catch different things.
  • Accepting diffs without looking. Approving a batch of changes in one click defeats the purpose.
  • Missing decorators: a component that needs a theme or router works in the app and crashes in Storybook until you add the same providers.
  • Giant play functions that test a whole feature. Keep each one short and about one behavior.
  • Querying by CSS class or test id first instead of role and label, which also miss accessibility problems.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a story in Storybook?

    A story shows one state of a component, mostly defined by args (props). The same story is used for the catalog, docs, interaction tests and visual tests.
  2. 2. What is a play function for?

    Play functions run after render and use userEvent, queries and expect to drive the story like a user, turning the story into an interaction test.
  3. 3. What problem does visual regression testing catch that a getByText test does not?

    Behavior tests do not know how the component looks. Screenshot comparison shows layout and style changes that no assertion covered.
  4. 4. Why do visual tests usually run in a fixed environment such as a container or cloud service?

    Rendering differences between operating systems produce noisy diffs. A controlled environment makes screenshots reproducible.
  5. 5. Your visual test reports a diff and the new look is exactly what the designer asked for. What do you do?

    A diff is a prompt for review. If the change is intentional, you approve it and the new image replaces the baseline.

Summary

  • Storybook lets you build and review components in isolation. A story is a component in one state, defined mostly by args; one story file feeds the catalog, docs, interaction tests, accessibility checks and visual tests.
  • Decorators supply providers and global styles, and fn() spies record callbacks. Keep stories independent of real data and the network.
  • A play function drives the rendered story with Testing Library queries and userEvent, then asserts. It can run in the browser panel and in CI.
  • Visual regression testing compares screenshots with approved baselines. A person reviews every difference and either fixes the bug or accepts the new baseline.
  • Keep screenshots stable: fixed environment, frozen time and data, no animation, loaded fonts and images, and focused stories.
  • Use these tools where they pay off most (shared components) and combine them with unit tests and end-to-end tests.

Next: TypeScript and React