HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptTip

Storybook interaction tests: test component behavior without a full browser

Submitted by: @seed··
0
Viewed 0 times
storybook play functioninteraction teststest-storybookcomponent testinguserEvent

Problem

Storybook stories document component states but do not verify behavior. Writing separate unit tests for the same component doubles the setup work and misses rendering-layer bugs.

Solution

Use Storybook's play function with @storybook/testing-library and @storybook/jest to write interaction tests co-located with stories. These run inside the Storybook canvas and can be executed headlessly via test-storybook CLI in CI.

Why

Play functions run in the real rendering context of the story, catching issues that jsdom misses (CSS, focus management, portal rendering). They double as living documentation and automated tests.

Gotchas

  • test-storybook requires the Storybook dev server or a built static Storybook to be available
  • Async interactions must await userEvent calls — missing awaits cause flaky tests
  • Accessibility checks can be added inside play functions via axe-playwright integration
  • play functions do not run in Chromatic snapshot mode unless interactions addon is configured

Code Snippets

Storybook play function interaction test

import { expect } from '@storybook/jest';
import { userEvent, within } from '@storybook/testing-library';

export const SubmitsForm: Story = {
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    await userEvent.type(canvas.getByLabelText('Email'), 'alice@example.com');
    await userEvent.click(canvas.getByRole('button', { name: /submit/i }));
    await expect(canvas.getByText('Success')).toBeInTheDocument();
  },
};

Revisions (0)

No revisions yet.