Cypress loads stories as reusable test cases
With Cypress and Component Story Format, each named export (a story) is renderable within the testing setup. When Cypress runs a test, it loads Storybook's isolated iframe and can interact with the story and verify component behavior, such as checking if inputs match expected test values.
Storybook integrates with Cypress and Playwright for end-to-end testing
Storybook seamlessly integrates with end-to-end testing frameworks like Cypress and Playwright. By leveraging Component Story Format (CSF), developers can write test cases that simulate user interactions and verify component behavior. This approach enables developers to test components' functionality, responsiveness, and visual appearance across different scenarios.
Playwright loads stories as reusable test cases
With Playwright and Component Story Format, each named export (a story) is renderable within the testing setup. When Playwright executes, it opens a new browser window, loads Storybook's isolated iframe, and can assert if component states contain specified values. Test results are displayed in the terminal.
Override global configurations in portable stories tests
When using composeStory or composeStories functions, you can override global configurations by extending these functions to provide test-specific configurations. This prevents unforeseen side effects for tests that should not use global decorators or parameters. For example, you may want to test a story in a particular locale or apply specific decorators only for certain tests.
Testing Library screen queries with composed stories
When using Testing Library with composed stories that run inside a unit test renderer, use Testing Library's screen queries. In contrast, in a story's play function, prefer the provided canvas queries so interactions stay scoped to the rendered story.
Community addons for Vue 2 and Angular portable stories
Storybook provides community-led addons for Vue 2 and Angular frameworks to support portable stories, though these addons may lack support for the latest stable Storybook release. Maintainers can be reached via GitHub and Discord.
setProjectAnnotations requirement for portable stories
You must configure your test environment to use portable stories via setProjectAnnotations to ensure stories are composed with all aspects of your Storybook configuration, such as decorators and parameters from the preview file.
composeStories for multiple stories in one test
The composeStories function processes every component story specified and applies any args or decorators defined on them. Use composeStories when you intend to test multiple stories in a single test.
composeStory function for single story tests
The composeStory function allows tests to run on a single story. When using this method, you should supply the story metadata (the default export) to the composeStory function to ensure tests accurately determine the correct information about the story.
Stories as reusable test fixtures across tools
Stories in Storybook are standard JavaScript modules that can be imported into testing tools like Jest, Testing Library, Vitest, and Playwright. This allows teams to write component state once in stories and reuse it across multiple testing tools, reducing maintenance overhead compared to setting up the same component state repeatedly for each tool.
composeStories utility for portable stories
The composeStories utility converts stories from a test file into renderable elements that can be reused in Node tests with JSDOM. It applies Storybook features like decorators and args to tests, enabling stories to work in testing environments like Jest and Vitest. This feature is referred to as portable stories in Storybook.
Access args and parameters from composed stories
Components returned by composeStories or composeStory come with combined properties from the story, meta, and global configuration. This means you can access args or parameters from the composed component if you need them in your tests.
Vitest addon runs visual and accessibility tests
If other testing addons are installed, such as the Visual tests addon or the Accessibility addon, those tests can run alongside component tests.
Testing widget shows test summary
The testing widget shows 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.
Vitest addon transforms stories into component tests
The Vitest addon transforms stories into component tests which test rendering and behavior of components in a real browser environment. It also calculates project coverage provided by stories.
Running tests for specific stories
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, then select the test type you want to run.
Running tests from Storybook UI
The easiest way to run tests is through the Storybook UI. Press the Run tests button in the testing widget at the bottom of the sidebar to run all tests. You can expand the testing widget to run specific test types individually.
initialGlobals plugin option
initialGlobals is a Record<string, unknown> option with default value {}. It configures a set of initial global values that will be applied to every story this project runs. Useful for running tests with different options, such as testing every story in a specific theme. Can be configured with multiple Vitest projects, each pinning a different global value.
Test results may differ across environments
Sometimes tests will fail when run in the addon or via CLI but pass when viewed in the Interactions panel, or vice versa. This can happen because tests are run in different environments, which can have different behaviors.
Vitest CLI script for Storybook tests
To run only Storybook tests using the Vitest CLI, add a script to package.json: 'test-storybook': 'vitest --project=storybook'. This uses the --project=storybook flag to tell Vitest to run tests for the Storybook project.
Isolate Storybook tests from other tests
To isolate Storybook tests from other tests, move the test property from your Vite configuration to the Vitest configuration. This prevents the test properties from being merged when the Vitest config extends the Vite config. Also recommend using a test project (Vitest ≥ 4.0) or workspace (previous versions) to define separate configurations.
Browser mode recommended over simulation
Running tests in browser mode using Playwright's Chromium ensures 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.
Fix 'Failed to fetch dynamically imported module' or 'Cannot connect to the iframe' in CI
These errors in CI typically occur when running many tests simultaneously, overwhelming available resources. Two recommended approaches to fix: 1) Disable isolation mode by setting test.isolate to false in vitest.config.ts. 2) Use sharding to split tests across multiple CI jobs with vitest run --shard=1/3, etc.
Using browsers other than Chromium
While Chromium is recommended because it most likely matches the experience of a majority of users, you can use other browsers by adjusting the browser name in the Vitest configuration file. Note that Playwright and WebDriverIO support different browsers.
configDir plugin option
configDir is a string option with default value '.storybook'. It specifies the directory where the Storybook configuration is located, relative to the current working directory. If Storybook configuration is not in the default location, you must specify it here so the plugin can function correctly.
Test result navigation in Storybook
After running tests, status indicators appear on stories and components for their pass, fail, or error state. Pressing the menu button when hovering a story shows test results. Selecting a result navigates to that story and opens the appropriate debugging panel, such as the Interactions panel for interaction test failures.
tags option behavior
In the tags plugin option: include specifies stories with these tags will be tested; exclude specifies stories with these tags will not be tested and will not be counted in test results; skip specifies stories with these tags will not be tested but will be counted in test results.
Vitest plugin does not require running Storybook
The Vitest plugin transforms stories into tests using Vite and portable stories, so it does not need to run Storybook to test stories. However, you may still want to run Storybook to debug tests.
storybookScript option for debugging CLI tests
The storybookScript option in the plugin configuration enables you to provide a script to run Storybook. When running Vitest in watch mode, the plugin will start Storybook using this script and provide links to the story in the output on test failures.
storybookUrl option for CI test failures
The storybookUrl option provides a URL to the story in the output when tests fail in CI or other environments where Storybook is not already running. This is useful for quickly jumping to the story to debug the issue.
Debugging CLI tests in Storybook
The plugin will attempt to provide links to the story in Storybook when tests fail in CLI. If URLs are not working in watch mode, check storybookUrl and storybookScript configuration options. If URLs are not working in CI, ensure Storybook is built and published before running tests, then provide the URL to the published Storybook using the storybookUrl option.
Vitest addon features comparison
Vitest addon: runs tests via Vitest, requires Vite-based frameworks, runs tests in real browser environment, calculates code coverage, does not require running or published Storybook, and is extensible to other addons. Test runner: runs tests via Jest, works with all Storybook frameworks, runs tests in real browser environment, calculates code coverage with addon-coverage, requires running or published Storybook, and is not extensible to other addons.
Playwright browser binaries required for browser mode tests
Playwright browser binaries are required for running tests in browser mode, which is the recommended setup for component testing. They can be installed at any time by running playwright install.
Automatic setup configures Vitest and Playwright
The automatic setup command installs and registers the Vitest addon, inspects the project's Vite and Vitest setup, installs and configures Vitest with sensible defaults if necessary, sets up browser mode using Playwright's Chromium browser, and prompts to install Playwright browser binaries if needed.
Vitest addon testing contexts
Vitest addon supports testing in: Storybook UI, Editor extensions, CLI, and in CI. The test runner supports CLI and in CI only.
Vitest addon test type support
Vitest addon supports: Interaction tests, Accessibility tests, and Visual tests. Snapshot tests are not supported by the Vitest addon but are supported by the test runner.
Next.js Vitest addon requirements
The Vitest addon is supported in Next.js ≥ 14.1 projects, but you must be using the @storybook/nextjs-vite framework.
Vitest addon vs test runner comparison
The test runner requires a running Storybook instance and visits each story, executes the play function, and listens for results. The Vitest addon transforms stories into tests using Vite and portable stories, so it does not need to run Storybook. The Vitest addon can only be used with Vite-based Storybook frameworks, while the test runner works with any framework.
Exclude tag takes precedence over include tag
If the same tag is in both the include and exclude arrays in the tags configuration, the exclude behavior takes precedence.
Vitest error alerting in testing widget
When Vitest itself has an error, 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 addon requirements
Before installing the Vitest addon, your project must have: a Storybook framework that uses Vite (e.g. vue3-vite, react-vite, preact-vite, nextjs-vite, sveltekit), Vitest ≥ 3.0, and optionally MSW ≥ 2.0 if installed.
Assets in public directory configuration
If stories use assets in the public directory and you are not using the default public directory location (public), you need to adjust the Vitest configuration to include the public directory by providing the publicDir option in the Vitest configuration file.
Default tags configuration
By default, the Vitest addon plugin will run all stories with the test tag. You can adjust this behavior by providing the tags option in the plugin configuration.
Custom test name with name property
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. Example: export const Story = { name: 'custom, descriptive name' };
React version mismatch error workaround
The 'm.createRoot is not a function' error can occur when using the addon on a project with React version other than 18. To work around this, provide an alias in the Vitest configuration file to ensure the correct React version is used: resolve: { alias: { '@storybook/react-dom-shim': '@storybook/react-dom-shim/dist/react-16' } }
Fix 'Vitest failed to find the current suite' error
This error is often related to how stories are being transformed, not a Vitest issue. Steps to troubleshoot: 1) Check complete error logs for additional context, particularly around story transformation. 2) Pay attention to Vite dependency optimization warnings (e.g., 'new dependencies optimized: lodash'). 3) If you see dependency optimization warnings, pre-optimize your dependencies by adding them to your Vite config's optimizeDeps.include array.
Tags to include, exclude, or skip stories from testing
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.
WebDriver alternative to Playwright
While Playwright is recommended, you can use WebDriverIO instead by adjusting the browser provider in the Vitest configuration file.
Vitest addon runs in background during Storybook UI
When running tests in the Storybook UI, the addon runs Vitest in the background and reports the results in the sidebar.
storybookTest plugin export
The addon exports storybookTest from @storybook/addon-vitest/vitest-plugin. storybookTest is a function that acts as a Vitest plugin, transforming stories into tests and accepting an options object for configuration.
IDE extensions for running Vitest tests
Transforming stories into Vitest tests enables you to run and debug tests using Vitest IDE integrations, such as the Vitest extension in VSCode and JetBrains IDE. Stories are annotated with test status, and a link to the story is provided for debugging when tests fail.
storybookScript plugin option
storybookScript is an optional string option that specifies a script to run Storybook. If provided, Vitest will start Storybook using this script when run in watch mode, but only if the Storybook at storybookUrl is not already available.
storybookUrl plugin option
storybookUrl is a string option with default value 'http://localhost:6006'. It specifies the URL where Storybook is hosted, used for internal checks and to provide a link to the story in test output on failures.
tags plugin option structure
The tags option accepts an object with properties: include (string array), exclude (string array), and skip (string array). Default is { include: ['test'], exclude: [], skip: [] }. These tags are defined as annotations in your story, meta, or preview.
Watch mode for automatic test re-runs
Watch mode automatically re-runs tests when you make changes to your components or stories. To activate, press the watch mode toggle (the eye icon) in the testing widget.
disableAddonDocs plugin option
disableAddonDocs is a boolean option with default value true. It determines whether to disable addon docs MDX parsing while running tests. When either the preview config or stories import mdx files, they are mocked as they are normally not needed for tests. Set to false only if stories actually need to read and parse MDX files as part of rendering components.
initialGlobals example with theme configuration
Example of using initialGlobals to pin theme globals for multiple Vitest projects: each project (storybookProject('light'), storybookProject('dark')) gets its own initialGlobals: { theme } setting, allowing every story to be tested in both light and dark themes.
Code example:
```ts
const storybookProject = (theme: string) => ({
extends: true,
plugins: [
storybookTest({
configDir: path.join(dirname, '.storybook'),
initialGlobals: { theme },
}),
],
test: {
name: `storybook-${theme}`,
browser: {
enabled: true,
provider: 'playwright',
headless: true,
instances: [{ browser: 'chromium' }],
},
setupFiles: ['./.storybook/vitest.setup.ts'],
},
});
export default mergeConfig(
viteConfig,
defineConfig({
test: {
projects: [storybookProject('light'), storybookProject('dark')],
},
}),
);
```
initialGlobals takes precedence over Storybook globals
The initialGlobals option mirrors the initialGlobals configuration in .storybook/preview.*, applied per-project instead of globally. However, the plugin's own initialGlobals values always take precedence over Storybook's own values.
Test status shown in sidebar with filtering
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.
Vitest addon replaces Jest-based test-runner
The Vitest addon is a spiritual successor to the test-runner, which was created in 2021 and used Jest as a runner with Playwright as a browser environment. The Vitest addon uses Vitest as a runner instead of Jest, offering faster test execution and better integration with modern JavaScript tooling.