交互
Storybook 中的 play 函数允许你模拟用户交互,并在故事渲染完成后运行。使用 交互 插件,你可以可视化和调试这些交互。
¥The play function in Storybook allows you to simulate user interactions to run after a story renders. With the Interactions addon, you have a way to visualize and debug these interactions.
交互的播放函数
¥Play function for interactions
故事以结构化的方式隔离和捕获组件状态。在开发组件时,你可以快速浏览故事以验证其外观和功能。每个故事都指定了重现特定状态所需的所有输入。你甚至可以模拟上下文和 API 调用,从而处理组件的大多数使用场景。但是,对于需要用户交互的状态该怎么办?
¥Stories isolate and capture component states in a structured manner. While developing a component, you can quickly cycle through the stories to verify the look and feel. Each story specifies all the inputs required to reproduce a specific state. You can even mock context and API calls, allowing you to handle most use cases of a component. But what about states that require user interaction?
例如,单击按钮打开/关闭对话框、拖动列表项重新排序或填写表单以检查验证错误。要测试这些行为,需要像用户一样与组件交互。交互式故事允许你使用播放函数自动执行这些交互。它们是故事渲染完成后运行的一小段代码,模拟用户与组件交互的具体步骤。
¥For example, clicking a button to open/close a dialog box, dragging a list item to reorder it, or filling out a form to check for validation errors. To test those behaviors, you have to interact with the components as a user would. Interactive stories enable you to automate these interactions using a play function. They are small snippets of code that run once the story finishes rendering, emulating the exact steps a user would take to interact with the component.
由 Testing Library 和 Vitest 提供支持
¥Powered by Testing Library and Vitest
交互功能使用名为 @storybook/test 的软件包编写。它提供了 Storybook 集成的 测试库 和 Vitest 版本。它提供了一种熟悉的、对开发者友好的语法来与 DOM 交互并进行断言,同时还提供额外的遥测数据来辅助调试。
¥The interactions are written using a package called @storybook/test. It provides Storybook-instrumented versions of Testing Library and Vitest. That gives you a familiar developer-friendly syntax to interact with the DOM and make assertions, but with extra telemetry to help with debugging.
设置交互插件
¥Set up the interactions addon
如果你为新项目添加 Storybook,则默认情况下 @storybook/addon-interactions 已安装并配置好。如果你是从旧版本的 Storybook 迁移过来的,则需要手动安装。
¥By default, the @storybook/addon-interactions is already installed and configured if you're adding Storybook for new projects. If you're migrating from a previous version of Storybook, you'll need to install it manually.
运行以下命令安装交互插件及其相关依赖。
¥Run the following command to install the interactions addon and related dependencies.
npm install @storybook/test @storybook/addon-interactions --save-dev接下来,将 .storybook/main.js|ts 更新为以下内容:
¥Next, update .storybook/main.js|ts to the following:
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
framework: '@storybook/your-framework',
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: [
// Other Storybook addons
'@storybook/addon-interactions', // 👈 Register the addon
],
};
export default config;请确保将 @storybook/addon-interactions 列在 @storybook/addon-essentials 插件之后(如果你单独安装了 @storybook/addon-actions,则列在 @storybook/addon-actions 之后)。
¥Make sure to list @storybook/addon-interactions after the @storybook/addon-essentials addon (or the @storybook/addon-actions if you've installed it individually).
现在运行 Storybook 时,交互插件将自动启用。
¥Now when you run Storybook, the Interactions addon will be enabled.

编写组件测试
¥Write a component test
交互作为故事的 play 函数的一部分运行。我们依赖 Testing Library 来完成繁重的测试工作。
¥Interactions run as part of the play function of your stories. We rely on Testing Library to do the heavy lifting.
请确保通过 @storybook/test 导入 Vitest 和 Testing Library 的 Storybook 封装,而不是直接导入原始包。
¥Make sure to import the Storybook wrappers for Vitest and Testing Library via @storybook/test rather than importing the original packages directly.
// Replace your-framework with the name of your framework
import type { Meta, StoryObj } from '@storybook/your-framework';
import { userEvent, waitFor, within, expect, fn } from '@storybook/test';
import { Form } from './Form';
const meta: Meta<typeof Form> = {
component: Form,
args: {
// 👇 Use `fn` to spy on the onSubmit arg
onSubmit: fn(),
},
};
export default meta;
type Story = StoryObj<typeof Form>;
/*
* See https://storybook.js.org/docs/writing-stories/play-function#working-with-the-canvas
* to learn more about using the canvasElement to query the DOM
*/
export const Submitted: Story = {
play: async ({ args, canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Enter credentials', async () => {
await userEvent.type(canvas.getByTestId('email'), 'hi@example.com');
await userEvent.type(canvas.getByTestId('password'), 'supersecret');
});
await step('Submit form', async () => {
await userEvent.click(canvas.getByRole('button'));
});
// 👇 Now we can assert that the onSubmit arg was called
await waitFor(() => expect(args.onSubmit).toHaveBeenCalled());
},
};上述示例使用 canvasElement 将元素查询限定在当前故事中。如果你希望你的 play 函数最终与 Storybook Docs 兼容(Storybook Docs 在同一页面上渲染多个组件),那么它至关重要。此外,step 函数可用于创建带标签的交互组。
¥The above example uses the canvasElement to scope your element queries to the current story. It's essential if you want your play functions to eventually be compatible with Storybook Docs, which renders multiple components on the same page. Additionally, the step function can be used to create labeled groups of interactions.
虽然你可以参考 测试库文档 来了解其使用详情,但在使用 Storybook 封装器时,有一个重要的细节有所不同:方法调用必须使用 await。它允许你使用调试器来回执行交互。
¥While you can refer to the Testing Library documentation for details on how to use it, there's an important detail that's different when using the Storybook wrapper: method invocations must be await-ed. It allows you to step back and forth through your interactions using the debugger.
任何被标记为“操作”(使用 argTypes 注解 或 argTypesRegex)的 args 都会自动转换为 Jest 模拟函数(间谍)。这允许你对这些函数的调用进行断言。
¥Any args that have been marked as an Action, either using the argTypes annotation or the argTypesRegex, will be automatically converted to a Jest mock function (spy). This allows you to make assertions about calls to these functions.
为了在 Storybook 故事中模拟函数以进行可靠且隔离的组件测试,请使用从 @storybook/test 导入的命名 fn。
¥To mock functions in your Storybook stories for reliable and isolated component testing, use the named fn import from @storybook/test.
