storybook-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseStorybook Testing — Storybook 10
Storybook 测试 — Storybook 10
Overview
概述
Storybook 10 unifies component testing into a single workflow: interaction tests via 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.
play()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 () — build-time module mocking, scoped per-project in preview.ts
sb.mock - CSF factories (React, preview) — →
defineMain→definePreview→preview.meta()chainmeta.story() - Essential addons in core — viewport, controls, interactions, actions no longer separate deps
- Import path changes — →
@storybook/test(old paths still work as aliases)storybook/test - React Server Component story support — test RSC in isolation
- Vitest 4 support — renamed to
experimental-addon-testaddon-vitest
When to use this skill:
- Writing component stories in CSF3 format with TypeScript
- Setting up interaction tests with functions
play() - 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 将组件测试统一为单一工作流:通过函数实现交互测试,通过Chromatic TurboSnap实现视觉回归测试,通过a11y插件实现无障碍审计 —— 所有测试均通过Vitest运行。故事(Stories)是可执行的测试规范,而非单纯的文档。
play()Storybook 10 新增特性(对比9版本):
- 强制仅使用ESM —— 唯一的破坏性变更;要求Node 20.16+ / 22.19+ / 24+;安装包体积缩小29%
- 模块自动模拟() —— 构建时模块模拟,在preview.ts中按项目作用域配置
sb.mock - CSF工厂(React、预览版) —— →
defineMain→definePreview→preview.meta()链式调用meta.story() - 核心内置必备插件 —— viewport、controls、interactions、actions不再是独立依赖
- 导入路径变更 —— →
@storybook/test(旧路径仍可作为别名使用)storybook/test - React Server Component 故事支持 —— 可独立测试RSC
- Vitest 4 支持 —— 更名为
experimental-addon-testaddon-vitest
适用场景:
- 使用TypeScript编写CSF3格式的组件故事
- 利用函数搭建交互测试
play() - 配置带TurboSnap的Chromatic视觉回归测试
- 在故事层面使用模块自动模拟
- 通过a11y插件在CI中运行无障碍测试
- 利用自动文档生成活文档
- 从Storybook 9迁移至10版本
Quick Reference
快速参考
| Rule | Impact | Description |
|---|---|---|
| HIGH | Typesafe CSF3 story factories with |
| CRITICAL | Interaction testing with |
| HIGH | Run stories as Vitest tests via |
| HIGH | TurboSnap reduces snapshot cost 60-90% |
| HIGH | Story-level module mocking with |
| CRITICAL | Automated axe-core accessibility scans in CI |
| MEDIUM | Auto-generated docs from stories |
| 规则 | 影响级别 | 描述 |
|---|---|---|
| 高 | 基于 |
| 关键 | 结合 |
| 高 | 通过 |
| 高 | TurboSnap将快照成本降低60-90% |
| 高 | 通过 |
| 关键 | 在CI中自动运行axe-core无障碍扫描 |
| 中 | 从故事自动生成文档 |
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 function is an executable interaction test that runs in Vitest.
play() - CSF3 + for type safety. Use
satisfiesfor full type inference on args and play functions.satisfies Meta<typeof Component> - Module automocking (SB 10). Register in
sb.mock(import(...)), configure per-story with.storybook/preview.tsinmocked(). Never usebeforeEachin story files. No factory functions —vi.mockis build-time, not runtime.sb.mock - 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.
- 故事即测试。每个带有函数的故事都是可执行的交互测试,在Vitest中运行。
play() - CSF3 + 保障类型安全。使用
satisfies实现对args和play函数的完整类型推断。satisfies Meta<typeof Component> - 模块自动模拟(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-Pattern | Why It Fails | Use Instead |
|---|---|---|
CSF2 | Deprecated, no type inference, will be removed in SB 11 | CSF3 object stories with |
| Deprecated since Storybook 9 | |
| Leaks between stories, breaks isolation | Register |
| Full Chromatic snapshots on every PR | Expensive and slow | TurboSnap with |
| Manual accessibility checking | Misses violations, not repeatable | |
| Separate documentation site | Drifts from actual component behavior | Autodocs with |
| Testing implementation details | Brittle, breaks on refactors | Test user-visible behavior via |
| CJS imports in stories | ESM-only since SB 9/10 | Use ESM imports, set |
| 反模式 | 失败原因 | 替代方案 |
|---|---|---|
CSF2 | 已废弃,无类型推断,将在SB 11中移除 | 使用带 |
| 自Storybook 9起已废弃 | |
故事文件中使用 | 故事间存在泄漏,破坏隔离性 | 在preview.ts中注册 |
| 每个PR都生成完整Chromatic快照 | 成本高且速度慢 | 启用 |
| 手动检查无障碍 | 容易遗漏违规,不可重复 | 在CI流水线中使用 |
| 独立的文档站点 | 与实际组件行为脱节 | 使用带 |
| 测试实现细节 | 脆弱,重构时易失效 | 通过 |
| 故事中使用CJS导入 | SB 9/10起仅支持ESM | 使用ESM导入,在tsconfig中设置 |
References
参考资料
- — Migration path from Storybook 9 to 10
references/storybook-migration-guide.md - — CI pipeline configuration for visual, interaction, and a11y testing
references/storybook-ci-strategy.md - — Essential addons for Storybook 10 in 2026
references/storybook-addon-ecosystem.md
- —— 从Storybook 9迁移至10的指南
references/storybook-migration-guide.md - —— 视觉、交互和无障碍测试的CI流水线配置
references/storybook-ci-strategy.md - —— 2026年Storybook 10必备插件生态
references/storybook-addon-ecosystem.md
Related Skills
相关技能
- — React 19 + Next.js 16 patterns (component architecture)
react-server-components-framework - — Broader accessibility patterns beyond Storybook
accessibility - — CI/CD pipeline patterns for automated testing
devops-deployment
- —— React 19 + Next.js 16 模式(组件架构)
react-server-components-framework - —— 超越Storybook的更广泛无障碍模式
accessibility - —— 自动化测试的CI/CD流水线模式
devops-deployment