用 @storybook/testing-library 写一个 play 函数完成“输入+回车”后列表新增一项
解读
面试官想考察三件事:
- 你是否真正理解 play 函数 在 Storybook 交互测试里的定位——它运行在 @storybook/testing-library 提供的真实浏览器环境里,必须 可复现、可断言。
- 你是否熟悉 @storybook/testing-library 的 API(screen、userEvent、within 等),而不是把“play”写成“setTimeout + 肉眼观察”。
- 你是否能把“输入+回车”这种 键盘交互 用 userEvent.type 正确模拟,并 断言 DOM 变化 而非 console.log。
国内面试常见误区:
- 把 play 写成 async () => { input.value = 'xxx'; keyPress(13) },绕过 userEvent,被认为“不还原用户行为”。
- 只打印不断言,缺失 expect,面试官会直接追问“你怎么证明用例通过?”
- 忘记在 meta 级别 引入 @storybook/addon-interactions,导致本地跑得出、CI 挂掉。
知识点
- play 函数签名:( { canvasElement, args } ) => Promise<void>
- @storybook/testing-library 重新导出 screen / within / fireEvent / userEvent,推荐优先用 userEvent,更接近真实。
- userEvent.type(element, '文本{enter}') 一次性完成“输入+回车”,比分开 keyDown 简洁。
- 断言库 使用 @storybook/jest,提供 expect、toBeInTheDocument 等 matcher;toBeInTheDocument 需提前 import '@testing-library/jest-dom'。
- within(canvasElement) 限定查找范围,避免多个 Story 同时挂载造成 查询污染。
- Storybook 7 默认带 interactions addon,但要在 main.ts 里显式声明,否则 CI 不会跑。
答案
以下代码基于 React + TypeScript,组件为 <TodoBox />,已对外暴露 data-testid="new-todo-input" 与 data-testid="todo-list",每项子节点带 data-testid="todo-item"。
// TodoBox.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { within, userEvent, screen } from '@storybook/testing-library';
import { expect } from '@storybook/jest';
import { TodoBox } from './TodoBox';
const meta: Meta<typeof TodoBox> = {
title: 'Example/TodoBox',
component: TodoBox,
parameters: {
// 保证 CI 会跑 interactions
interactions: { disable: false },
},
};
export default meta;
type Story = StoryObj<typeof TodoBox>;
export const AddByEnter: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// 1. 找到输入框
const input = canvas.getByTestId('new-todo-input');
// 2. 模拟用户输入并回车
await userEvent.type(input, '买牛奶{enter}');
// 3. 断言列表新增一项
const list = canvas.getByTestId('todo-list');
expect(list.children).toHaveLength(1);
// 4. 断言文本正确
expect(canvas.getByTestId('todo-item')).toHaveTextContent('买牛奶');
},
};
要点回顾:
- userEvent.type 一次性完成输入+回车,{enter} 是 testing-library 的键盘简写。
- within(canvasElement) 保证只在当前 Story 作用域内查找,避免多个 Story 污染。
- expect 断言 既校验数量又校验文本,让用例真正“挂”得出来。
拓展思考
- 如果产品需求改为 “输入后点按钮新增”,play 函数只需把
userEvent.type(input, '买牛奶')与userEvent.click(button)分开即可;但 按钮的定位 建议用canvas.getByRole('button', { name: /添加/i }),比 testId 更能体现 可访问性优先。 - 当列表项出现 动画延迟(如 200 ms transition),可以在
userEvent.type后加await waitFor(() => expect(...).toBeInTheDocument()),避免动画导致的假失败。 - 国内很多团队把 play 函数直接当自动化用例 跑在 CI,配上 @storybook/test-runner,一条命令
test-storybook就能产出 JUnit 报告;面试时可主动提及,体现工程化闭环。 - 若组件用 Vue 3,写法完全一致,只需把
canvasElement当成挂载点,@storybook/testing-library 的 API 与框架无关,这一点常被候选人忽略,点破可加分。