用 @storybook/testing-react 把 story 渲染到 Jest 并断言样式类

解读

这道题在国内 React 组件库面试中非常常见,考察的是“把 Storybook 资产复用到单测”的能力。
很多团队已经用 Storybook 写好了交互、视觉、文档,但测试用例却重复写了一遍“渲染+传参”的样板代码,维护成本高。
面试官想知道:

  1. 你是否了解 @storybook/testing-react 的定位——把 CSF story 直接变成测试“场景”;
  2. 能否在 Jest(通常配合 react-testing-library)里拿到真实 DOM,并断言样式类存在与否;
  3. 是否清楚该方案在 Vite / Webpack / esbuild 等国内主流脚手架里的配置差异;
  4. 对 样式隔离、CSS-Module、CSS-in-JS 的类名生成规则有没有实战经验。

一句话:让 story 成为“唯一数据源”,测试、文档、视觉回归共用同一套代码。

知识点

  1. @storybook/testing-react 原理

    • 把 CSF 2/3 的 story 对象转成纯 React 元素,不依赖 Storybook 运行时;
    • 内部调用 Storybook 的 decorators + args + play 函数,保证渲染层与浏览器端一致。
  2. 与 react-testing-library 结合

    • render(<composeStory(Primary, Meta)>) 即可拿到 container;
    • 用 screen.getByRole / getByTestId 定位节点,再 expect(el).toHaveClass('ant-btn-primary')。
  3. 样式类断言的坑

    • CSS-Module 默认哈希:需要把 styles.primary 当作期望值,而非硬编码 'primary';
    • Scoped CSS(Vue 系)在 Jest 里需开 vitest-environment-jsdom 并引入对应 postcss 插件;
    • 动态类(例如 clsx({ [styles.active]: isActive }))要先 fireEvent.click 触发状态再断言。
  4. 国内工程化配套

    • 若用 umi/max 或 ice.js,需在 jest.config.js 里加 moduleNameMapper 把 @/styles.module.less 映射到 identity-obj-proxy;
    • Vite 项目推荐改走 vitest,@storybook/testing-react 同样适用,只需把 render 换成 @testing-library/react 的导出即可。
  5. 性能与稳定性

    • 每个 story 在 Jest 里都是独立测试作用域,不会污染全局 document;
    • 若 story 带 play 函数(交互脚本),建议用 await waitFor(() => …) 等待副作用结束再断言。

答案

以下示例基于 React 18 + TypeScript + Jest + react-testing-library,组件库采用 CSS-Module,目录结构为 src/Button/index.tsx 与 src/Button/Button.stories.tsx。

  1. 安装依赖
npm i -D @storybook/testing-react @testing-library/react @testing-library/jest-dom jest-environment-jsdom identity-obj-proxy
  1. 配置 Jest(jest.config.js)
module.exports = {
  testEnvironment: 'jsdom',
  moduleNameMapper: {
    '\\.module\\.(css|less|sass)$': 'identity-obj-proxy',
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};
  1. 全局增强(jest.setup.js)
import '@testing-library/jest-dom';
  1. Story 文件(Button.stories.tsx)
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './index';
import styles from './index.module.less';

const meta: Meta<typeof Button> = {
  title: 'Example/Button',
  component: Button,
};
export default meta;

type Story = StoryObj<typeof meta>;

export const Primary: Story = {
  args: { type: 'primary', children: '提交' },
};
  1. 测试文件(Button.test.tsx)
import { composeStory } from '@storybook/testing-react';
import { render, screen } from '@testing-library/react';
import { expect, test } from '@jest/globals';
import Meta, { Primary } from './Button.stories';

// 把 story 转成普通 React 组件
const PrimaryButton = composeStory(Primary, Meta);

test('**主按钮应包含 ant-btn-primary 样式类**', () => {
  render(<PrimaryButton />);
  const button = screen.getByRole('button', { name: /提交/ });
  // 若用 CSS-Module,断言的是映射后的哈希类
  expect(button).toHaveClass(styles.primary);
});
  1. 运行
npm test -- Button.test

若看到绿色 ✅,说明 story 成功被 Jest 消费,且样式类断言通过。

拓展思考

  1. 多主题/多品牌
    在测试里切换 globals.theme='dark' 参数,可一次性验证同一 story 在不同主题下的类名差异,无需重写渲染逻辑。

  2. 视觉回归
    把 @storybook/testing-react 与 jest-image-snapshot 结合,可在同一套 story 上跑“类名断言 + 像素diff”双重校验,国内大厂常用该方案替代人工 UI 走查。

  3. play 函数复用
    若 story 里已用 userEvent.click 写好了交互脚本,测试可直接 await PrimaryButton.play({ canvasElement: container }),零成本把交互用例搬进单测。

  4. 跨项目复用
    把组件库所有 stories 打成 npm 包,业务方直接 import { PrimaryButton } from 'ui-lib/stories' 做快照测试,实现“测试用例随包发布”,显著降低跨项目回归成本。