Vitest 插件
Storybook 的 Vitest 插件允许你直接在 Storybook 中测试组件。它会将你的 stories 转换为组件测试,在真实的浏览器环境中测试组件的渲染和行为。它还可以计算故事提供的项目 coverage。
¥Storybook's Vitest addon allows you to test your components directly inside Storybook. On its own, it transforms your stories into component tests, which test the rendering and behavior of your components in a real browser environment. It can also calculate project coverage provided by your stories.
如果你的项目使用其他测试插件,例如 可视化测试插件 或 可访问性插件,你可以将这些测试与组件测试一起运行。
¥If your project is using other testing addons, such as the Visual tests addon or the Accessibility addon, you can run those tests alongside your component tests.
为故事运行组件测试时,状态显示在侧边栏中。侧边栏可以筛选,仅显示失败的故事,你可以点击失败故事上的菜单按钮查看调试选项。
¥When component tests are run for a story, the status is shown in the sidebar. The sidebar can be filtered to only show failing stories, and you can press the menu button on a failing story to see debugging options.
你还可以在监视模式下运行测试,当你更改组件或故事时,它将自动重新运行测试。要激活,请点击测试小部件中的观看模式切换按钮(眼睛图标)。
¥You can also run tests in watch mode, which will automatically re-run tests when you make changes to your components or stories. To activate, press the watch mode toggle (the eye icon) in the testing widget.
安装和设置
¥Install and set up
安装前,请确保你的项目满足以下要求:
¥Before installing, make sure your project meets the following requirements:
-
使用 Vite 的 Storybook 框架(例如
vue3-vite、react-vite、preact-vite、nextjs-vite、sveltekit等)¥A Storybook framework that uses Vite (e.g.
vue3-vite,react-vite,preact-vite,nextjs-vite,sveltekit, etc.) -
Vitest ≥ 3.0
-
如果你尚未安装 Vitest,它将自动为你安装和配置。
¥If you're not yet using Vitest, it will be installed and configured for you automatically
-
-
(可选)MSW ≥ 2.0
¥(optional) MSW ≥ 2.0
-
如果安装了 MSW,则必须是 v2.0.0 或更高版本,以免与 Vitest 的依赖冲突。
¥If MSW is installed, it must be v2.0.0 or later to not conflict with Vitest's dependency
-
与 Next.js 一起使用 — Vitest 插件在 Next.js ≥ 14.1 的项目中受支持,但你必须使用 @storybook/nextjs-vite 框架。运行下面的安装命令时,如果你尚未安装并使用该框架,系统将提示你安装。
¥Using with Next.js — The Vitest addon is supported in Next.js ≥ 14.1 projects, but you must be using the @storybook/nextjs-vite framework. When you run the setup command below, you will be prompted to install and use the framework if you haven't already.
自动设置
¥Automatic setup
运行以下命令自动安装和配置插件:
¥Run the following command to install and configure the addon automatically:
npx storybook add @storybook/addon-vitestadd 命令 将:
¥The add command will:
-
安装并注册 Vitest 插件
¥Install and register the Vitest addon
-
检查项目的 Vite 和 Vitest 设置
¥Inspect your project's Vite and Vitest setup
-
如有必要,请使用合理的默认值安装和配置 Vitest
¥Install and configure Vitest with sensible defaults if necessary
-
使用 Playwright 的 Chromium 浏览器设置浏览器模式
¥Set up browser mode using Playwright's Chromium browser
-
如果需要,系统会提示你安装 Playwright 浏览器二进制文件。
¥Prompt you to install Playwright browser binaries if needed
设置完全自动化,所有配置都由系统自动处理。完整的配置选项可以在下面的 API 部分 中找到。
¥The setup is fully automated and handles all configuration for you. The full configuration options can be found in the API section, below.
如果在安装过程中提示你安装 Playwright 浏览器二进制文件,请选择 "是" 进行安装。这些是在浏览器模式下运行测试所必需的,浏览器模式是组件测试的推荐设置。
¥If you're prompted to install Playwright browser binaries during setup, select "Yes" to install them. These are required for running tests in browser mode, which is the recommended setup for component testing.
你可以随时运行 playwright install 来安装 Playwright 浏览器二进制文件。
¥You can install the Playwright browser binaries at any time by running playwright install.
手动设置(高级)
¥Manual setup (advanced)
Manual setup instructions (only needed if automatic setup fails)
对于某些项目设置,add 命令可能无法自动执行插件和插件的设置,并会要求你完成额外的设置步骤。操作方法如下:
¥For some project setups, the add command may be unable to automate the addon and plugin setup and ask you to complete additional setup steps. Here's what to do:
-
确保 Vite 和 Vitest 已在你的项目中配置。
¥Make sure Vite and Vitest are configured in your project.
-
配置 Vitest 以使用 浏览器模式。
¥Configure Vitest to use browser mode.
-
在你的项目和 在你的 Storybook 配置中注册它 中安装插件
@storybook/addon-vitest。¥Install the addon,
@storybook/addon-vitest, in your project and register it in your Storybook configuration. -
创建测试设置文件
.storybook/vitest.setup.ts。你可以使用 示例设置文件 作为指南。¥Create a test setup file,
.storybook/vitest.setup.ts. You can use the example setup file as a guide. -
调整你的 Vitest 配置,添加该插件并引用设置文件。你可以使用 示例配置文件 作为指南。
¥Adjust your Vitest configuration to include the plugin and reference the setup file. You can use the example configuration files as a guide.
-
对于已有 Vitest 测试的项目,我们建议,如果你使用的是 Vitest 4.0 或更高版本,则使用单独的 测试项目;如果你使用的是 Vitest 3.x,则使用单独的 工作区文件,以便为 Storybook 测试和其他测试定义不同的配置。你可以根据需要单独运行它们,也可以同时运行。
¥For projects with existing Vitest tests, we recommend using a separate test project if you're using Vitest ≥ 4.0 and a workspace file if you're using Vitest 3.x to define separate configurations for your Storybook tests and other tests. You can run them in isolation or together, depending on your needs.
-
示例配置文件
¥Example configuration files
当插件自动设置时,它将为你创建或调整 Vitest 配置文件。如果你手动设置,则在配置项目时可以使用以下示例作为参考。
¥When the addon is set up automatically, it will create or adjust your Vitest configuration files for you. If you're setting up manually, you can use the following examples as a reference when configuring your project.
Example Vitest setup file
Storybook 故事包含在 .storybook/preview.js|ts 中定义的配置。要确保配置可用于你的测试,你可以在 Vitest 设置文件中应用它。以下是如何执行此操作的示例:
¥Storybook stories contain configuration defined in .storybook/preview.js|ts. To ensure that configuration is available to your tests, you can apply it in a Vitest setup file. Here's an example of how to do that:
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import { setProjectAnnotations } from '@storybook/your-framework';
import * as previewAnnotations from './preview';
const annotations = setProjectAnnotations([previewAnnotations]);setProjectAnnotations 函数是 可移植故事 API 的一部分,Vitest 插件内部使用它将你的故事转换为测试。
¥The setProjectAnnotations function is part of the portable stories API, which is used internally by the Vitest plugin to transform your stories into tests.
Example Vitest config file
插件最简单的应用是将其包含在你的 Vitest 配置文件中:
¥The most simple application of the plugin is to include it in your Vitest configuration file:
import { defineConfig, mergeConfig } from 'vitest/config';
import { playwright } from '@vitest/browser-playwright';
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const dirname = path.dirname(fileURLToPath(import.meta.url));
import viteConfig from './vite.config';
export default mergeConfig(
viteConfig,
defineConfig({
test: {
// Use `workspace` field in Vitest < 3.2
projects: [
{
extends: true,
plugins: [
storybookTest({
// The location of your Storybook config, main.js|ts
configDir: path.join(dirname, '.storybook'),
// This should match your package.json script to run Storybook
// The --no-open flag will skip the automatic opening of a browser
storybookScript: 'yarn storybook --no-open',
}),
],
test: {
name: 'storybook',
// Enable browser mode
browser: {
enabled: true,
// Make sure to install Playwright
provider: playwright({}),
headless: true,
instances: [{ browser: 'chromium' }],
},
setupFiles: ['./.storybook/vitest.setup.ts'],
},
},
],
},
}),
);Example Vitest workspace file (Vitest < 3.2)
如果你使用的是 Vitest 工作区,则可以定义一个新的工作区项目:
¥If you're using a Vitest workspace, you can define a new workspace project:
import { defineWorkspace } from 'vitest/config';
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineWorkspace([
// This is the path to your existing Vitest config file
'./vitest.config.ts',
{
// This is the path to your existing Vite config file
extends: './vite.config.ts',
plugins: [
storybookTest({
// The location of your Storybook config, main.js|ts
configDir: path.join(dirname, '.storybook'),
// This should match your package.json script to run Storybook
// The --ci flag will skip prompts and not open a browser
storybookScript: 'yarn storybook --ci',
}),
],
test: {
name: 'storybook',
// Enable browser mode
browser: {
enabled: true,
// Make sure to install Playwright
provider: 'playwright',
headless: true,
instances: [{ browser: 'chromium' }],
},
setupFiles: ['./.storybook/vitest.setup.ts'],
},
},
]);用法
¥Usage
有多种使用插件运行测试的方法。
¥There are multiple ways to run tests using the addon.
我们建议(并默认配置)在 浏览器模式 中运行 Vitest,使用 Playwright 的 Chromium 浏览器。浏览器模式可确保你的组件在真实的浏览器环境中进行测试,这比 JSDom 或 HappyDom 等模拟更准确。这对于测试依赖浏览器 API 或功能的组件尤其重要。
¥We recommend (and configure, by default) running Vitest in browser mode, using Playwright's Chromium browser. Browser mode ensures your components are tested in a real browser environment, which is more accurate than simulations like JSDom or HappyDom. This is especially important for testing components that rely on browser APIs or features.
Storybook UI
运行测试最简单的方法是通过 Storybook UI。只需单击一下,你就可以对项目中的所有故事、一组故事或单个故事运行多种类型的测试。
¥The easiest way to run tests is through the Storybook UI. With a click, you can run multiple types of tests for all stories in your project, a group of stories, or a single story.
要为整个项目运行所有测试,请按侧边栏底部测试小部件中的“运行测试”按钮。
¥To run all tests for your whole project, press the Run tests button in the testing widget at the bottom of the sidebar.

或者,你可以扩展测试小部件以单独运行特定类型的测试。组件测试下列出的子类型将一起运行,包括启用监视模式(代码更改后将自动重新运行相关测试)(带有眼睛图标)的情况。
¥Alternatively, you can expand the testing widget to run specific types of tests individually. The sub-types listed under component tests will all run together, including when watch mode (which will automatically re-run relevant tests upon code changes) is enabled (with the eye icon).

如果你安装了 可视化测试插件,你将看到一个选项,可以同时运行可视化测试和组件测试。
¥If you have the Visual tests addon installed, you'll see an option to run Visual tests alongside Component tests.

其他插件(例如 a11y)也可能提供可从测试小部件运行的测试类型,这些测试类型会影响故事和组件的状态指示器。
¥Other addons, such as a11y, may also provide test types that can be run from the testing widget and affect the status indicators on stories and components.
要针对特定故事或故事组运行测试,请按下侧边栏项目悬停时出现的菜单按钮(三个点)。然后,你可以选择要运行的测试类型。
¥To run tests for a specific story or group of stories, press the menu button (three dots) that appears on hover of a sidebar item. You can then select the test type you want to run.

运行测试后,你将在故事和组件上看到状态指示器,指示它们的通过、失败或错误状态。你可以将鼠标悬停在故事上时点击菜单按钮来查看该故事的测试结果。在菜单中选择一个结果将导航到该故事并打开相应的调试面板。例如,如果交互测试失败,你可以直接跳转到“交互”面板中的失败页面。该面板为你的测试提供了一个交互式调试器,允许你逐步执行每个模拟行为或断言。
¥After running your tests, you will now see status indicators on stories and components for their pass, fail, or error state. You can press on the menu button when hovering a story to see the test results for that story. Selecting a result in the menu will navigate you to that story and open the appropriate debugging panel. For example, if an interaction test fails, you can jump straight to the failure in the Interactions panel. That panel provides an interactive debugger for your test, allowing you to step through each simulated behavior or assertion.
测试小部件还会显示运行的测试总数、通过的测试数以及失败或出错的测试数。你可以点击失败编号来过滤侧边栏中失败的故事。
¥The testing widget will also show you the total number of tests run, the number of tests that passed, and the number of tests that failed or errored. You can press the failure number to filter the sidebar to only those stories that failed.
CLI
你还可以使用 Vitest CLI 运行测试。我们建议在你的 package.json 中添加一个脚本,以便更轻松地运行测试。以下是如何执行此操作的示例:
¥You can also run tests using the Vitest CLI. We recommend adding a script to your package.json to make running tests easier. Here's an example of how to do that:
{
"scripts": {
"test": "vitest",
"test-storybook": "vitest --project=storybook"
}
}在本例中,我们添加了两个脚本:test 用于运行项目中的所有测试(你可能已经拥有它),而 test-storybook 用于仅运行 Storybook 测试。--project=storybook 标志指示 Vitest 运行 Storybook 项目的测试。
¥In this example, we've added two scripts: test to run all tests in your project (you may already have this), and test-storybook to run only your Storybook tests. The --project=storybook flag tells Vitest to run the tests for the Storybook project.
然后,使用 Vitest CLI 运行以下命令运行你的测试(默认在 监视模式 中):
¥Then, run this command to run your tests (in watch mode, by default) using the Vitest CLI:
npm run test-storybook调试
¥Debugging
虽然插件在测试时不需要 Storybook 运行,但你可能仍希望运行 Storybook 来调试测试。要启用此功能,请在插件配置中提供 storybookScript 选项。当你在监视模式下运行 Vitest 时,插件将使用此脚本启动 Storybook,并在测试失败时在输出中提供故事链接。这允许你快速跳转到 Storybook 中的故事来调试问题。
¥While the plugin does not require Storybook to run when testing, you may still want to run Storybook to debug your tests. To enable this, provide the storybookScript option in the plugin configuration. When you run Vitest in watch mode, the plugin will start Storybook using this script and provide links to the story in the output on test failures. This allows you to quickly jump to the story in Storybook to debug the issue.
你还可以为插件配置提供 storybookUrl 选项。当你未使用监视模式且测试失败时,插件将在输出中使用此 URL 提供指向故事的链接。这在 在 CI 中运行测试 或 Storybook 尚未运行的其他环境中很有用。
¥You can also provide a storybookUrl option to the plugin configuration. When you're not using watch mode and tests fail, the plugin will provide a link to the story using this URL in the output. This is useful when running tests in CI or other environments where Storybook is not already running.

编辑器扩展
¥Editor extension
使用插件将你的故事转换为 Vitest 测试还使你能够使用 Vitest IDE 集成 运行和调试测试。这允许你直接从编辑器(例如 VSCode 和 JetBrains IDE)运行测试。
¥Transforming your stories into Vitest tests with the plugin also enables you to run and debug tests using Vitest IDE integrations. This allows you to run tests directly from your editor, such as VSCode and JetBrains IDE.
此屏幕截图显示了如何使用 Vitest 扩展 在 VSCode 中运行 Vitest 测试。故事带有测试状态注释,当测试失败时,将为 debugging 提供故事链接。
¥This screenshot shows how you can run your Vitest tests in VSCode using the Vitest extension. Stories are annotated with the test status, and, when a test fails, a link to the story is provided for debugging.

在 CI 中
¥In CI
在大多数情况下,在 CI 中运行 Storybook 测试是通过 通过 CLI 完成的。
¥For the most part, running your Storybook tests in CI is done via the CLI.
但是,要让测试输出在测试失败时链接到你已发布的 Storybook,你需要在插件配置中提供 storybookUrl 选项。请参考 CI 测试指南中的详细示例。
¥However, to have the test output link to your published Storybook on test failures, you need to provide the storybookUrl option in the plugin configuration. Please reference the detailed example in the Testing in CI guide.
工作原理
¥How it works
Vitest 插件的工作原理是使用 Vitest 插件将你的故事转换为使用 可移植故事 的 Vitest 测试。它还会配置 Vitest 使用 Playwright 的 Chromium 浏览器在 浏览器模式 中运行这些测试。由于该插件基于 Vitest 构建,因此需要基于 Vite 的 Storybook 框架。
¥The Vitest addon works by using a Vitest plugin to transform your stories into Vitest tests using portable stories. It also configures Vitest to run those tests in browser mode, using Playwright's Chromium browser. Because it is built on top of Vitest, the addon requires a Vite-based Storybook framework.
故事以两种方式进行测试:进行冒烟测试以确保其渲染,如果定义了 播放函数,则运行该函数并验证其中的任何 断言。
¥Stories are tested in two ways: a smoke test to ensure it renders and, if a play function is defined, that function is run and any assertions made within it are validated.
在 Storybook UI 中运行测试时,该插件会在后台运行 Vitest,并在侧边栏中报告结果。
¥When you run tests in the Storybook UI, the addon runs Vitest in the background and reports the results in the sidebar.
配置测试
¥Configuring tests
该插件运行的测试可以通过两种方式配置。你可以切换运行的测试类型,并包含、排除或跳过要测试的故事。
¥The tests run by the addon can be configured in two ways. You can toggle which test types are run and include, exclude, or skip stories from being tested.
切换测试类型
¥Toggling test types
除了组件测试之外,Vitest 插件还支持多种类型的测试,具体取决于你在项目中使用的其他插件。某些测试类型(例如 可视化测试)是独立运行的。其他插件(例如 accessibility)必须与组件测试一起运行。对于这些依赖的测试类型,你可以在测试小部件中通过选中或取消选中要运行的测试类型来打开或关闭它们。
¥In addition to component tests, the Vitest addon supports multiple types of tests, depending on which other addons you are using in your project. Some test types, like visual tests, are run independently. Others, like accessibility, must be run alongside component tests. For these dependent test types, you can toggle them on or off in the testing widget by checking or unchecking the test types you want to run.

请注意,你可能没有图中所示的所有测试类型,具体取决于你安装的插件。
¥Note that you may not have all of the test types pictured, depending on which addons you have installed.
包含、排除或跳过测试
¥Including, excluding, or skipping tests
你可以使用 tags 包含、排除或跳过测试故事。包含的故事会经过测试,排除的故事不会经过测试,跳过的故事不会经过测试,但会计入测试结果。
¥You can use tags to include, exclude, or skip stories from being tested. Included stories are tested, excluded stories are not tested, and skipped stories are not tested but are counted in the test results.
默认情况下,插件将运行所有带有 test 标签的故事。你可以通过在插件配置中提供 tags 选项 来调整此行为。这允许你根据故事的标签包含、排除或跳过故事。
¥By default, the plugin will run all stories with the test tag. You can adjust this behavior by providing the tags option in the plugin configuration. This allows you to include, exclude, or skip stories based on their tags.
在此示例中,我们将 stable 标签应用于所有 Button 组件的故事,ExperimentalFeatureStory 除外,它将具有 experimental 标签:
¥In this example, we'll apply the stable tag to all of the Button component's stories, except for ExperimentalFeatureStory, which will have the experimental tag:
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
import { Button } from './Button';
const meta = {
component: Button,
// 👇 Applies to all stories in this file
tags: ['stable'],
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
export const ExperimentalFeatureStory: Story = {
//👇 For this particular story, remove the inherited `stable` tag and apply the `experimental` tag
tags: ['!stable', 'experimental'],
};要将这些标签连接到我们的测试行为,我们可以调整插件配置以排除 experimental 标签:
¥To connect those tags to our test behavior, we can adjust the plugin configuration to exclude the experimental tag:
export default defineConfig({
// ...
test: {
// ...
projects: [
{
plugins: [
storybookTest({
// ...
tags: {
include: ['test'],
exclude: ['experimental'],
},
}),
],
// ...
},
],
},
});如果相同的标签同时存在于 include 和 exclude 数组中,则 exclude 行为优先。
¥If the same tag is in both the include and exclude arrays, the exclude behavior takes precedence.
与测试运行器的比较
¥Comparison to the test runner
测试运行器 需要一个正在运行的 Storybook 实例来测试你的故事,因为它会访问每个故事,执行播放函数并监听结果。但是,Vitest 插件使用 Vite 和可移植故事将你的故事转换为测试,因此无需运行 Storybook 即可测试你的故事。由于依赖 Vite,该插件只能与使用 Vite(和 Next.js)的 Storybook 框架一起使用。另一方面,测试运行器可以与任何 Storybook 框架一起使用。
¥The test runner requires a running Storybook instance to test your stories, because it visits each one, executes the play function, and listens for results. The Vitest plugin, however, transforms your stories into tests using Vite and portable stories, so it does not need to run Storybook to test your stories. Because of this reliance on Vite, the plugin can only be used with Storybook frameworks that use Vite (and Next.js). The test runner, on the other hand, can be used with any Storybook framework.
| 功能 | Vitest 插件 | test-runner |
|---|---|---|
| 测试类型 | ||
| * 交互测试 | ✅ | ✅ |
| * 可访问性测试 | ✅ | ✅ |
| * 视觉测试 | ✅ | ❌ |
| * 快照测试 | ❌ | ✅ |
| 测试上下文 | ||
| * Storybook UI | ✅ | ❌ |
| * 编辑器扩展 | ✅ | ❌ |
| * CLI | ✅ | ✅ |
| * 在 CI 中 | ✅ | ✅ |
| 测试运行方式: | Vitest | Jest |
| 适用于所有 Storybook 框架 | ❌ (需要 Vite) | ✅ |
| 在真实的浏览器环境中运行测试 | ✅ | ✅ |
| 计算代码覆盖率 | ✅ | ✅ (包含插件) |
| 需要正在运行或已发布的 Storybook | ❌ | ✅ |
| 可扩展到其他插件 | ✅ | ❌ |
测试运行器只是一个命令行工具。它没有用于运行测试的用户界面,也没有编辑器扩展。但是,该插件在 Storybook 中提供了一个用于运行测试的 UI,并允许你使用 Vitest IDE 集成来运行和调试测试。
¥The test runner is only a CLI tool. It does not have a UI for running tests, nor does it have an editor extension. The addon, however, provides a UI in Storybook for running tests, and it enables you to run and debug tests using Vitest IDE integrations.
此外,测试运行器将你的故事作为 Jest 中的编排测试运行,并且该编排带来了一些复杂性。相比之下,这个插件将你的故事转换成真正的测试,然后使用 Vitest 运行它们,这更简单,更易于配置。
¥Additionally, the test runner ran your stories as orchestrated tests in Jest, and that orchestration came with some complexity. By comparison, this plugin transforms your stories into real tests and then runs them using Vitest, which is simpler and more configurable.
最后,由于架构更简单并且使用 Vitest,这个插件应该比大多数项目的测试运行器更快。我们将在未来进行更多基准测试以量化这一点。
¥Finally, because of the simpler architecture and the use of Vitest, this plugin should be faster than the test runner for most projects. We'll do more benchmarking to quantify this in the future.
常见问题
¥FAQ
如果 Vitest 本身出现错误会发生什么?
¥What happens if Vitest itself has an error?
有时,测试可能会由于 Vitest 本身的错误而失败。发生这种情况时,Storybook UI 中的测试小部件将提醒你错误,你可以点击链接查看完整内容。错误也将记录到控制台。
¥Sometimes tests can fail because of errors within Vitest itself. When this happens, the testing widget in the Storybook UI will alert you to the error, and you can click a link to view it in full. The error will also be logged to the console.

Vitest 提供 常见错误故障排除帮助。
¥Vitest offers troubleshooting help for common errors.
如果在多个环境中测试结果不同会发生什么?
¥What happens when there are different test results in multiple environments?
使用此插件运行测试时,它们将以 Vitest 测试的形式运行,并采用你在项目中设置的任何配置。默认情况下,它们将以浏览器模式运行,使用 Playwright 的 Chromium 浏览器。有时,测试在插件中(或通过 CLI)运行时会失败,但在“交互”面板中查看时会通过(反之亦然)。发生这种情况的原因是测试在不同的环境中运行,而这些环境可能具有不同的行为。
¥When you run tests with this addon, they are run as Vitest tests with whatever configuration you have set up in your project. By default, they will run in browser mode, using Playwright's Chromium browser. Sometimes, tests will fail when run in the addon (or via CLI), but then pass when viewed in the Interactions panel (or vice versa). This can happen because the tests are run in different environments, which can have different behaviors.
如何在 Storybook 中调试 CLI 测试?
¥How do I debug my CLI tests in Storybook?
当 CLI 中的测试失败时,插件将尝试提供 Storybook 中的故事链接,以用于 debugging 的目的。
¥The plugin will attempt to provide links to the story in Storybook when tests fail in CLI, for debugging purposes.
如果在监视模式下运行测试时 URL 不起作用,你应该检查两个配置选项:
¥If the URLs are not working when running tests in watch mode, you should check two configuration options:
-
storybookUrl:确保此 URL 正确且可访问。例如,默认值为http://localhost:6006,它可能不使用你正在使用的相同端口号。¥
storybookUrl: Ensure this URL is correct and accessible. For example, the default ishttp://localhost:6006, which may not use the same port number you're using. -
storybookScript:确保此脚本正确启动 Storybook。¥
storybookScript: Ensure this script is correctly starting Storybook.
如果在 CI 中运行测试时 URL 不起作用,你应该确保在运行测试之前构建并发布 Storybook。然后,你可以使用 storybookUrl 选项提供已发布 Storybook 的 URL。请参阅 在 CI 中 部分以获取示例。
¥If the URLs are not working when running tests in CI, you should ensure the Storybook is built and published before running the tests. You can then provide the URL to the published Storybook using the storybookUrl option. See the In CI section for an example.
如何确保我的测试可以在公共目录中找到资源?
¥How do I ensure my tests can find assets in the public directory?
如果你的故事使用公共目录中的资源,并且你没有使用默认的公共目录位置(public),则需要调整 Vitest 配置以包含公共目录。你可以通过提供 Vitest 配置文件中的 publicDir 选项 来执行此操作。
¥If your stories use assets in the public directory and you're not using the default public directory location (public), you need to adjust the Vitest configuration to include the public directory. You can do this by providing the publicDir option in the Vitest configuration file.
如何将 Storybook 测试与其他测试隔离开来?
¥How do I isolate Storybook tests from others?
某些项目可能在其 Vite 配置中包含 test 属性。由于此插件使用的 Vitest 配置扩展了该 Vite 配置,因此 test 属性已合并。这种缺乏隔离可能会导致 Storybook 测试出现问题。
¥Some projects might contain a test property in their Vite configuration. Because the Vitest configuration used by this plugin extends that Vite config, the test properties are merged. This lack of isolation can cause issues with your Storybook tests.
要将你的 Storybook 测试与其他测试隔离,你需要将 test 属性从 Vite 配置移动到 Vitest 配置。插件使用的 Vitest 配置可以安全地扩展你的 Vite 配置,而无需合并 test 属性。
¥To isolate your Storybook tests from other tests, you need to move the test property from your Vite configuration to the Vitest configuration. The Vitest config used by the plugin can then safely extend your Vite config without merging the test property.
此外,如果你使用的是 Vitest 4.0 或更高版本,我们建议使用 测试项目;对于早期版本,我们建议使用工作区,以便为 Storybook 测试和其他测试定义不同的配置。这可确保每个故事可以根据你的需求单独运行或一起运行。
¥Additionally, we recommend using a test project if you're using Vitest ≥ 4.0, or a workspace for previous versions to define separate configurations for your Storybook tests and other tests. This ensures each can be run either in isolation or together, depending on your needs.
为什么我们推荐浏览器模式?
¥Why do we recommend browser mode?
Vitest 的浏览器模式在真实浏览器(默认配置中为 Chromium,通过 Playwright)中运行你的测试。替代方案是模拟浏览器环境,如 JSDom 或 HappyDom,与真实浏览器相比,其行为可能有所不同。对于通常依赖于浏览器 API 或功能的 UI 组件,在真实浏览器中运行测试更为准确。
¥Vitest's browser mode runs your tests in a real browser (Chromium, via Playwright, in the default configuration). The alternative is a simulated browser environment, like JSDom or HappyDom, which can have differences in behavior compared to a real browser. For UI components, which can often depend on browser APIs or features, running tests in a real browser is more accurate.
有关更多信息,请参阅 Vitest 关于有效使用浏览器模式的指南。
¥For more, see Vitest's guide on using browser mode effectively.
如何使用 WebDriver 而不是 Playwright?
¥How do I use WebDriver instead of Playwright?
我们建议使用 Playwright 在浏览器中运行测试,但你可以改用 WebDriverIO。为此,你需要调整 Vitest 配置文件中的浏览器提供程序。
¥We recommend running tests in a browser using Playwright, but you can use WebDriverIO instead. To do so, you need to adjust the browser provider in the Vitest configuration file.
如何使用 Chromium 以外的浏览器?
¥How do I use a browser other than Chromium?
我们建议使用 Chromium,因为它最有可能最好地匹配大多数用户的体验。但是,你可以通过调整 Vitest 配置文件中的浏览器名称 来使用其他浏览器。请注意 Playwright 和 WebDriverIO 支持不同的浏览器。
¥We recommend using Chromium, because it is most likely to best match the experience of a majority of your users. However, you can use other browsers by adjusting the browser name in the Vitest configuration file. Note that Playwright and WebDriverIO support different browsers.
如何自定义测试名称?
¥How do I customize a test name?
默认情况下,故事的导出名称会映射到测试名称。要创建更具描述性的测试描述,你可以为故事提供 name 属性。这允许你包含空格、括号或其他特殊字符。
¥By default, the export name of a story is mapped to the test name. To create a more descriptive test description, you can provide a name property for the story. This allows you to include spaces, brackets, or other special characters.
export const Story = {
name: 'custom, descriptive name'
};如何修复 m.createRoot is not a function 错误?
¥How do I fix the m.createRoot is not a function error?
在使用 React 18 以外版本的项目上使用该插件时,可能会出现此错误。要解决此问题,你可以提供别名以确保使用正确的 React 版本。以下是在 Vitest 配置文件中执行此操作的示例:
¥This error can occur when using the addon on a project that uses a React version other than 18. To work around the issue, you can provide an alias to ensure the correct React version is used. Here's an example of how to do that in the Vitest configuration file:
import { defineConfig } from 'vitest/config';
export default defineConfig({
// ...
resolve: {
alias: {
"@storybook/react-dom-shim": "@storybook/react-dom-shim/dist/react-16",
},
},
});如何修复 Error: Vitest failed to find the current suite 错误?
¥How do I fix the Error: Vitest failed to find the current suite error?
如果你遇到此错误,通常不是 Vitest 的问题,而是与你的故事转换方式有关。以下是故障排除步骤:
¥If you encounter this error, it's often not a Vitest issue but rather related to how your stories are being transformed. Here are steps to troubleshoot:
-
查看完整的错误日志以获取更多上下文,尤其是有关故事转换的信息。
¥Check the complete error logs for additional context, particularly around story transformation
-
注意 Vite 依赖优化警告(例如 "优化了新的依赖:lodash")
¥Pay attention to Vite dependency optimization warnings (e.g., "new dependencies optimized: lodash")
-
如果你看到依赖优化警告,这些警告可能会导致执行期间测试中断的重新加载。
¥If you see dependency optimization warnings, these can cause test-breaking reloads during execution
最常见的解决方法是预先优化依赖。你可以通过将依赖添加到 Vite 配置的 optimizeDeps.include 数组来实现此目的。
¥The most common fix is to pre-optimize your dependencies. You can do this by adding the dependencies to your Vite config's optimizeDeps.include array.
这可以防止测试中期的依赖优化,从而避免干扰 Vitest 的测试套件管理。
¥This prevents mid-test dependency optimization, which can interfere with Vitest's test suite management.
API
导出
¥Exports
此插件具有以下导出功能:
¥This addon has the following exports:
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'storybookTest
类型:function
¥Type: function
将你的故事转化为测试的 Vitest 插件。它接受 选项对象 进行配置。
¥A Vitest plugin that transforms your stories into tests. It accepts an options object for configuration.
选项
¥Options
该插件使用选项对象进行配置。以下是可用的属性:
¥The plugin is configured using an options object. Here are the available properties:
configDir
类型:string
¥Type: string
默认:.storybook
¥Default: .storybook
Storybook 配置所在的目录,相对于当前工作目录。
¥The directory where the Storybook configuration is located, relative to the current working directory.
如果你的 Storybook 配置 不在默认位置,你必须在此处指定位置,以便插件可以正常运行。
¥If your Storybook configuration is not in the default location, you must specify the location here so the plugin can function correctly.
storybookScript
类型:string
¥Type: string
运行 Storybook 的可选脚本。如果提供,Vitest 将在监视模式下运行时使用此脚本启动 Storybook。仅在 storybookUrl 中的 Storybook 尚不可用时运行。
¥Optional script to run Storybook. If provided, Vitest will start Storybook using this script when run in watch mode. Only runs if the Storybook in storybookUrl is not already available.
storybookUrl
类型:string
¥Type: string
默认:http://localhost:6006
¥Default: http://localhost:6006
Storybook 托管的 URL。这用于内部检查并提供 在失败时链接到测试输出中的故事。
¥The URL where Storybook is hosted. This is used for internal checks and to provide a link to the story in the test output on failures.
tags
类型:
¥Type:
{
include: string[];
exclude: string[];
skip: string[];
}默认:
¥Default:
{
include: ['test'],
exclude: [],
skip: [],
}标签 用于包含、排除或跳过。这些标签被定义为你的故事、元或预览中的注释。
¥Tags to include, exclude, or skip. These tags are defined as annotations in your story, meta, or preview.
-
include:带有这些标签的故事将被测试¥
include: Stories with these tags will be tested -
exclude:带有这些标签的故事将不会被测试,并且将不计入测试结果¥
exclude: Stories with these tags will not be tested, and will not be counted in the test results -
skip:带有这些标签的故事将不会被测试,并且将计入测试结果¥
skip: Stories with these tags will not be tested, and will be counted in the test results
disableAddonDocs
类型:boolean
¥Type: boolean
默认:true
¥Default: true
运行测试时是否禁用插件文档的 MDX 解析。
¥Whether to disable addon docs MDX parsing while running tests.
当预览配置或故事导入 mdx 文件时,它们会被模拟,因为通常测试不需要它们。只有当你的故事在渲染组件时确实需要读取和解析 MDX 文件时,你才可以将 disableAddonDocs 设置为 false。
¥When either the preview config or stories import mdx files, they are mocked as normally they are not needed for tests.
You might set disableAddonDocs to false only in case your stories actually need to read and parse MDX files as part of rendering your components.
更多测试资源
¥More testing resources
-
交互测试 提供有关用户行为模拟
¥Interaction testing for user behavior simulation
-
无障碍测试 用于可访问性
¥Accessibility testing for accessibility
-
可视化测试 用于外观
¥Visual testing for appearance
-
快照测试 提供有关渲染错误和警告
¥Snapshot testing for rendering errors and warnings
-
测试覆盖率 用于测量代码覆盖率
¥Test coverage for measuring code coverage
-
CI 用于在你的 CI/CD 流水线中运行测试
¥CI for running tests in your CI/CD pipeline
-
测试运行器 用于自动化测试执行
¥Test runner to automate test execution
-
端到端测试 提供有关模拟真实用户场景
¥End-to-end testing for simulating real user scenarios
-
单元测试 用于功能性
¥Unit testing for functionality
