storybook-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Storybook Testing — Storybook 10

Storybook 测试 — Storybook 10

Overview

概述

Storybook 10 unifies component testing into a single workflow: interaction tests via
play()
functions, visual regression via Chromatic TurboSnap, and accessibility audits via the a11y addon — all running through Vitest. Stories are executable test specifications, not just documentation.
What's new in Storybook 10 (vs 9):
  • ESM-only enforced — the single breaking change; Node 20.16+ / 22.19+ / 24+ required; 29% smaller install
  • Module automocking (
    sb.mock
    )
    — build-time module mocking, scoped per-project in preview.ts
  • CSF factories (React, preview)
    defineMain
    definePreview
    preview.meta()
    meta.story()
    chain
  • Essential addons in core — viewport, controls, interactions, actions no longer separate deps
  • Import path changes
    @storybook/test
    storybook/test
    (old paths still work as aliases)
  • React Server Component story support — test RSC in isolation
  • Vitest 4 support
    experimental-addon-test
    renamed to
    addon-vitest
When to use this skill:
  • Writing component stories in CSF3 format with TypeScript
  • Setting up interaction tests with
    play()
    functions
  • Configuring Chromatic visual regression with TurboSnap
  • Using module automocking at the story level
  • Running accessibility tests in CI via the a11y addon
  • Generating living documentation with autodocs
  • Migrating from Storybook 9 to 10

Storybook 10 将组件测试统一为单一工作流:通过
play()
函数实现交互测试,通过Chromatic TurboSnap实现视觉回归测试,通过a11y插件实现无障碍审计 —— 所有测试均通过Vitest运行。故事(Stories)是可执行的测试规范,而非单纯的文档。
Storybook 10 新增特性(对比9版本):
  • 强制仅使用ESM —— 唯一的破坏性变更;要求Node 20.16+ / 22.19+ / 24+;安装包体积缩小29%
  • 模块自动模拟(
    sb.mock
    —— 构建时模块模拟,在preview.ts中按项目作用域配置
  • CSF工厂(React、预览版) ——
    defineMain
    definePreview
    preview.meta()
    meta.story()
    链式调用
  • 核心内置必备插件 —— viewport、controls、interactions、actions不再是独立依赖
  • 导入路径变更 ——
    @storybook/test
    storybook/test
    (旧路径仍可作为别名使用)
  • React Server Component 故事支持 —— 可独立测试RSC
  • Vitest 4 支持 ——
    experimental-addon-test
    更名为
    addon-vitest
适用场景:
  • 使用TypeScript编写CSF3格式的组件故事
  • 利用
    play()
    函数搭建交互测试
  • 配置带TurboSnap的Chromatic视觉回归测试
  • 在故事层面使用模块自动模拟
  • 通过a11y插件在CI中运行无障碍测试
  • 利用自动文档生成活文档
  • 从Storybook 9迁移至10版本

Quick Reference

快速参考

RuleImpactDescription
storybook-csf3-factories
HIGHTypesafe CSF3 story factories with
satisfies Meta
storybook-play-functions
CRITICALInteraction testing with
play()
and
@storybook/test
storybook-vitest-integration
HIGHRun stories as Vitest tests via
@storybook/addon-vitest
storybook-chromatic-turbosnap
HIGHTurboSnap reduces snapshot cost 60-90%
storybook-sb-mock
HIGHStory-level module mocking with
sb.mock
storybook-a11y-testing
CRITICALAutomated axe-core accessibility scans in CI
storybook-autodocs
MEDIUMAuto-generated docs from stories

规则影响级别描述
storybook-csf3-factories
基于
satisfies Meta
的类型安全CSF3故事工厂
storybook-play-functions
关键结合
play()
@storybook/test
的交互测试
storybook-vitest-integration
通过
@storybook/addon-vitest
将故事作为Vitest测试运行
storybook-chromatic-turbosnap
TurboSnap将快照成本降低60-90%
storybook-sb-mock
通过
sb.mock
实现故事级别的模块模拟
storybook-a11y-testing
关键在CI中自动运行axe-core无障碍扫描
storybook-autodocs
从故事自动生成文档

Storybook Testing Pyramid

Storybook 测试金字塔

         ┌──────────────┐
         │   Visual     │  Chromatic TurboSnap
         │  Regression  │  (snapshot diffs)
         ├──────────────┤
         │ Accessibility│  @storybook/addon-a11y
         │   (a11y)     │  (axe-core scans)
         ├──────────────┤
         │ Interaction  │  play() functions
         │   Tests      │  (@storybook/test)
         ├──────────────┤
         │  Unit Tests  │  Vitest + storybookTest
         │  (stories)   │  plugin
         └──────────────┘
Each layer catches different defects: unit tests validate logic, interaction tests verify user flows, a11y tests catch accessibility violations, and visual tests catch unintended UI regressions.

         ┌──────────────┐
         │   Visual     │  Chromatic TurboSnap
         │  Regression  │  (快照对比)
         ├──────────────┤
         │ Accessibility│  @storybook/addon-a11y
         │   (a11y)     │  (axe-core扫描)
         ├──────────────┤
         │ Interaction  │  play() functions
         │   Tests      │  (@storybook/test)
         ├──────────────┤
         │  Unit Tests  │  Vitest + storybookTest
         │  (stories)   │  plugin
         └──────────────┘
每一层负责检测不同类型的缺陷:单元测试验证逻辑,交互测试验证用户流程,无障碍测试捕捉无障碍违规问题,视觉测试捕捉意外的UI回归。

Quick Start

快速开始

CSF3 Story with Play Function

带Play函数的CSF3故事

tsx
// Button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react'
import { expect, fn, userEvent, within } from 'storybook/test'
import { Button } from './Button'

const meta = {
  component: Button,
  args: {
    onClick: fn(),
  },
} satisfies Meta<typeof Button>

export default meta
type Story = StoryObj<typeof meta>

export const Primary: Story = {
  args: {
    label: 'Click me',
    variant: 'primary',
  },
  play: async ({ canvasElement, args }) => {
    const canvas = within(canvasElement)
    const button = canvas.getByRole('button', { name: /click me/i })

    await userEvent.click(button)
    await expect(args.onClick).toHaveBeenCalledOnce()
    await expect(button).toHaveStyle({ backgroundColor: 'rgb(37, 99, 235)' })
  },
}
tsx
// Button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react'
import { expect, fn, userEvent, within } from 'storybook/test'
import { Button } from './Button'

const meta = {
  component: Button,
  args: {
    onClick: fn(),
  },
} satisfies Meta<typeof Button>

export default meta
type Story = StoryObj<typeof meta>

export const Primary: Story = {
  args: {
    label: 'Click me',
    variant: 'primary',
  },
  play: async ({ canvasElement, args }) => {
    const canvas = within(canvasElement)
    const button = canvas.getByRole('button', { name: /click me/i })

    await userEvent.click(button)
    await expect(args.onClick).toHaveBeenCalledOnce()
    await expect(button).toHaveStyle({ backgroundColor: 'rgb(37, 99, 235)' })
  },
}

Vitest Configuration

Vitest 配置

ts
// vitest.config.ts
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [storybookTest()],
  test: {
    setupFiles: ['./vitest.setup.ts'],
  },
})

ts
// vitest.config.ts
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [storybookTest()],
  test: {
    setupFiles: ['./vitest.setup.ts'],
  },
})

Key Principles

核心原则

  • Stories are tests. Every story with a
    play()
    function is an executable interaction test that runs in Vitest.
  • CSF3 +
    satisfies
    for type safety.
    Use
    satisfies Meta<typeof Component>
    for full type inference on args and play functions.
  • Module automocking (SB 10). Register
    sb.mock(import(...))
    in
    .storybook/preview.ts
    , configure per-story with
    mocked()
    in
    beforeEach
    . Never use
    vi.mock
    in story files. No factory functions —
    sb.mock
    is build-time, not runtime.
  • TurboSnap for CI speed. Only snapshot stories affected by code changes — reduces Chromatic usage by 60-90%.
  • Accessibility is not optional. The a11y addon runs axe-core scans on every story and gates CI on violations.
  • Living documentation. Autodocs generates prop tables and usage examples directly from stories — no separate docs site needed.

  • 故事即测试。每个带有
    play()
    函数的故事都是可执行的交互测试,在Vitest中运行。
  • CSF3 +
    satisfies
    保障类型安全
    。使用
    satisfies Meta<typeof Component>
    实现对args和play函数的完整类型推断。
  • 模块自动模拟(SB 10)。在
    .storybook/preview.ts
    中注册
    sb.mock(import(...))
    ,在
    beforeEach
    中通过
    mocked()
    按故事配置。切勿在故事文件中使用
    vi.mock
    。无需工厂函数 ——
    sb.mock
    是构建时模拟,而非运行时。
  • TurboSnap 提升CI速度。仅对受代码变更影响的故事生成快照 —— 可将Chromatic使用成本降低60-90%。
  • 无障碍测试不可或缺。a11y插件会对每个故事运行axe-core扫描,并在CI中阻止违规情况。
  • 活文档。Autodocs直接从故事生成属性表和使用示例 —— 无需单独的文档站点。

Anti-Patterns (FORBIDDEN)

反模式(禁止使用)

Anti-PatternWhy It FailsUse Instead
CSF2
Template.bind({})
Deprecated, no type inference, will be removed in SB 11CSF3 object stories with
satisfies
@storybook/test-runner
package
Deprecated since Storybook 9
@storybook/addon-vitest
vi.mock()
in story files
Leaks between stories, breaks isolationRegister
sb.mock(import(...))
in preview.ts, configure with
mocked()
in beforeEach
Full Chromatic snapshots on every PRExpensive and slowTurboSnap with
onlyChanged: true
Manual accessibility checkingMisses violations, not repeatable
@storybook/addon-a11y
in CI pipeline
Separate documentation siteDrifts from actual component behaviorAutodocs with
tags: ['autodocs']
Testing implementation detailsBrittle, breaks on refactorsTest user-visible behavior via
play()
CJS imports in storiesESM-only since SB 9/10Use ESM imports, set
"module": "ESNext"
in tsconfig

反模式失败原因替代方案
CSF2
Template.bind({})
已废弃,无类型推断,将在SB 11中移除使用带
satisfies
的CSF3对象故事
@storybook/test-runner
自Storybook 9起已废弃
@storybook/addon-vitest
故事文件中使用
vi.mock()
故事间存在泄漏,破坏隔离性在preview.ts中注册
sb.mock(import(...))
,在beforeEach中用
mocked()
配置
每个PR都生成完整Chromatic快照成本高且速度慢启用
onlyChanged: true
的TurboSnap
手动检查无障碍容易遗漏违规,不可重复在CI流水线中使用
@storybook/addon-a11y
独立的文档站点与实际组件行为脱节使用带
tags: ['autodocs']
的Autodocs
测试实现细节脆弱,重构时易失效通过
play()
测试用户可见行为
故事中使用CJS导入SB 9/10起仅支持ESM使用ESM导入,在tsconfig中设置
"module": "ESNext"

References

参考资料

  • references/storybook-migration-guide.md
    — Migration path from Storybook 9 to 10
  • references/storybook-ci-strategy.md
    — CI pipeline configuration for visual, interaction, and a11y testing
  • references/storybook-addon-ecosystem.md
    — Essential addons for Storybook 10 in 2026
  • references/storybook-migration-guide.md
    —— 从Storybook 9迁移至10的指南
  • references/storybook-ci-strategy.md
    —— 视觉、交互和无障碍测试的CI流水线配置
  • references/storybook-addon-ecosystem.md
    —— 2026年Storybook 10必备插件生态

Related Skills

相关技能

  • react-server-components-framework
    — React 19 + Next.js 16 patterns (component architecture)
  • accessibility
    — Broader accessibility patterns beyond Storybook
  • devops-deployment
    — CI/CD pipeline patterns for automated testing
  • react-server-components-framework
    —— React 19 + Next.js 16 模式(组件架构)
  • accessibility
    —— 超越Storybook的更广泛无障碍模式
  • devops-deployment
    —— 自动化测试的CI/CD流水线模式