使用 CSF3 的 play 函数时,如何等待异步接口返回后再继续用户事件

解读

在国内一线/二线前端面试中,Storybook 已从“加分项”变成“组件库基建必考题”。
面试官抛出该问题,核心想验证三点:

  1. 你是否真的用 CSF3(Component Story Format 3) 写过带交互的 stories,而不是停留在“展示型”demo;
  2. 是否理解 play 函数的执行时机(在 story 初次渲染完成后立即运行,且运行在 @storybook/addon-interactions 的沙盒里);
  3. 能否把“异步接口”与 Testing Library 的异步工具(findBy、waitFor)以及 Storybook 的 canvas 作用域 结合起来,写出 可稳定复现、可 CI 重跑 的交互脚本。

如果仅回答“加 async/await”而没有提到 canvasElement、userEvent 的 setup、waitFor 的断言重试机制,会被认为“只看过文档,没踩过真坑”。

知识点

  1. CSF3 默认导出结构:component、args、render、play 等字段;play 是故事级别的副作用钩子,仅在 Storybook 的“交互”面板中执行。
  2. play 函数签名:async ({ canvasElement, args }) => void;canvasElement 是 story 的根 DOM 节点,必须作为 container 传给 Testing Library。
  3. addon-interactions 与 @storybook/testing-library 的关系:Storybook 把 Testing Library 重新导出为 within、userEvent、fireEvent、waitFor 等,但 userEvent 需先调用 userEvent.setup()(Storybook 7 之后强制),否则事件不会按真实时序排队。
  4. 异步接口等待策略:
    • 如果组件内部用 SWR/React-Query,需等待骨架屏消失或数据域渲染完成,推荐 waitFor(() => expect(screen.getByRole('list')).toBeInTheDocument());
    • 如果接口在 play 里手动调用(如点击按钮后触发),需 mock 延迟(msw、storybook-addon-mock)并 await findByText 或 waitFor 断言结果;
    • 禁止直接用 setTimeout 硬编码等待,会被视为“测试不稳定”。
  5. CI 与本地一致性:Storybook 官方在 7.2 之后把 test-runner 做成默认方案,跑 play 函数时会起无头浏览器;若异步断言超时,test-runner 会截图+重跑,因此必须保证 waitFor 的 timeout 与 CI 机器性能匹配(国内阿里云、腾讯云 2C4G 节点建议 5s 以内)。

答案

下面给出一份 可直接在 Vite + React18 + Storybook7 环境跑通 的完整示例,覆盖“点击按钮 → 调接口 → 等数据 → 继续下一步点击”的典型链路:

// ButtonWithApi.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { within, userEvent, waitFor } from '@storybook/testing-library';
import { rest } from 'msw';
import { ButtonWithApi } from './ButtonWithApi';

const meta: Meta<typeof ButtonWithApi> = {
  component: ButtonWithApi,
  parameters: {
    msw: {
      handlers: [
        rest.post('/api/count', async (req, res, ctx) => {
          // 模拟国内 4G 弱网 600ms
          await ctx.delay(600);
          return res(ctx.json({ total: 5 }));
        }),
      ],
    },
  },
};

export default meta;

type Story = StoryObj<typeof ButtonWithApi>;

export const Primary: Story = {
  name: '点击后等接口返回再下一步',
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    // 1. 必须先 setup,否则后续事件不排队
    const user = userEvent.setup();

    // 2. 初始按钮是“查询”
    const queryBtn = canvas.getByRole('button', { name: /查询/i });
    await user.click(queryBtn);

    // 3. 等待 loading 消失,接口数据渲染
    await waitFor(() => {
      expect(canvas.getByText(/总计:5/i)).toBeInTheDocument();
    });

    // 4. 数据返回后再点“重置”
    const resetBtn = canvas.getByRole('button', { name: /重置/i });
    await user.click(resetBtn);

    // 5. 断言 UI 回到初始态
    await waitFor(() => {
      expect(canvas.queryByText(/总计:5/i)).not.toBeInTheDocument();
    });
  },
};

要点回顾:

  • userEvent.setup() 必须在第一行,保证事件顺序与真实浏览器一致;
  • msw 的 delay 模拟国内网络,防止面试 demo 在面试官电脑上过快闪而过;
  • waitFor 包裹断言,而非直接 await findBy,后者只能等一个元素,waitFor 可组合多个断言;
  • 所有查询都基于 canvas 作用域,避免全局污染,符合 Storybook 官方最佳实践。

拓展思考

  1. 如何测试“轮询”场景?
    如果组件用 setInterval 每 3s 刷新一次列表,play 函数里可用 waitFor(() => expect(list.children).toHaveLength(3), { timeout: 10000 }) 并结合 msw 的 ctx.delay 动态返回不同数据,验证 DOM 是否递增。
  2. 如何与后端联调而不写死 mock?
    国内很多团队用 YApi/Apifox 做云端 mock,Storybook 参数里可切换 msw 的 rest 与真实 fetch,通过 env 变量 控制:
    const base = process.env.STORYBOOK_API_ENV === 'real' ? 'https://dev-api.xxx.com' : '';
    rest.get(base + '/api/list', handler)
    
    实现“同一套 play 脚本,本地跑 mock,CI 跑真实服务”的双轨验证。
  3. 如何复用 play 脚本做单元测试?
    Storybook 7 的 @storybook/jest 与 @storybook/testing-react 支持把 story 直接搬进 Jest + RTL 环境,play 函数作为测试用例执行,实现“一份代码,文档+测试+回归”三位一体,显著降低国内中小团队维护多份用例的人力成本。