Config, setup, CLI and plugin options
Contents
- Vitest config file
- Setup (
@storybook/addon-vitest) - CLI & scripts
- FAQ links
- Plugin options (quick)
Vitest config file
- Use a dedicated
vitest.config.{ts,mts,js,mjs}at the package root (per monorepo package). PutstorybookTestandtest.projectshere - Storybook docs recommend a separate test project for Storybook vs other tests (manual setup)
- Do not define
testinvite.configif that config is extended/merged for Vitest: the FAQ's merge problem is Vite'stestfield, notmergeConfigitself - Every inline project inherits the merged root config by default (the official example writes
extends: trueanyway). With amergeConfig(vite.config, …)root, sibling node/browser projects get the root's Vite plugins and rootsetupFilestoo; a plain node project that must not get them needsextends: false. Alternative: rootdefineConfig({ test: { projects: [{ extends: './vite.config.ts', … }] } })with notestin Vite: same isolation goal - Do not add the root's plugins (e.g.
svelte(),sveltekit()) to the storybook project. They are inherited; a duplicate compiles components twice and fails with avite-plugin-svelte:compileerror such as'new.target' can only be used in functions and class static block. Leaveextendsunset: an explicitextends: truehides Vitest's "applies the same plugin multiple times" warning - Gate: if there is no
vitest.config.*and the only Vitest config is atest:block invite.config(or there is no Vitest file), ask before adding the addon whether to introducevitest.config.tsand movetestout of Vite - Isolation: if
vite.configdefinestest, it merges into configs that extend that Vite file and can break Storybook tests: movetesttovitest.config(FAQ).mergeConfig(viteConfig, defineConfig({ test: … }))invitest.config.tsis the pattern Storybook documents as long as Vite does not owntest
Setup (@storybook/addon-vitest)
Setup A is for a SvelteKit project without Storybook and without a Vitest config (no vitest.config.* and no test block in vite.config.ts). There, pnpm dlx sv@latest add storybook runs Storybook's own installer (create-storybook, interactive; a non-interactive form is not covered here). What it adds depends on the answers given there; it can write a test block with the storybook project into vite.config.ts, with extends: true. For such a project:
- Ask (Gate above) whether
testshould live invitest.config.ts - Run
pnpm dlx sv@latest add storybookand check thatpackage.jsonlists@storybook/addon-vitestandvite.config.tshas a project withstorybookTest(). If both are there, run the peer check (Setup B step 4), then continue with step 3 here; if either is missing, continue with Setup B step 2 (the Gate is answered; movingtestafterstorybook addis not covered here) - If agreed, move
testinto a newvitest.config.ts(target shape: "Vitest 5 shape" below) with the imports and helpers it uses:storybookTest,playwright, andpath,fileURLToPathand thedirnameconstant when nothing else invite.config.tsuses them. Then drop the/// <reference types="vitest/config" />line fromvite.config.ts. If declined, keeptestinvite.config.tsand continue with step 4 - Do Setup B step 5 (all four items)
Setup B is for every other project (Storybook already installed, an existing Vitest config, or outside SvelteKit); a repo whose vite.config.ts has a test block containing a project whose extends is that file's path (e.g. extends: './vite.config.ts', as sv add vitest writes its client and/or server projects, unless renamed) is not covered here. For the others:
- Ask the Gate question when there is no
vitest.config.*(Gate above). If the answer is yes, movingtestout ofvite.config.ts, or creatingvitest.config.ts, in Setup B is not covered here (rule: the Isolation bullet above; target shape: "Vitest 5 shape" below): stop and tell the user. If no, continue with step 2 - If Storybook is not installed, install it (Storybook install docs); the install steps are not covered here
- Wire the addon:
package.jsonlists@storybook/addon-vitestand the Vitest config has a project withstorybookTest(): go to step 4package.jsonlists the addon without such a project,vitest.config.*hastest.projects, andvite.config.tshas notestblock: run the peer check (step 4) first, then:- Check that
.storybook/main.tsaddonslists the addon, and add it if not (manual setup) - Add the storybook entry of
projectsin "Vitest 5 shape" below, with the imports and thedirnameconstant it uses, to thetest.projectsof yourvitest.config.* - Check that the root loads the Svelte plugin (e.g. by merging
vite.configas "Vitest 5 shape" does): the project inherits it, and with no Svelte plugin on the root every story file fails withFailed to parse source for import analysis. Other ways to load it are not covered here. Then continue with step 5
- Check that
package.jsonlists the addon without such a project, in any other layout (novitest.config.*, avitest.config.*withouttest.projects, or atestblock invite.config.ts): not covered herepackage.jsondoes not list the addon:- Ask whether
storybook addmay edit the config; if no, go to sub-step 4 - Run
pnpm exec storybook add @storybook/addon-vitest(automatic installation) - Check that
package.jsonlists the addon and the Vitest config has a project withstorybookTest(). If both are there, go to step 4 (the peer check); if the addon is listed without such a project, follow the matching case above; if it is not listed, stop and ask - Wiring by hand instead of
storybook add: whenvitest.config.*hastest.projectsandvite.config.tshas notestblock, followSETUP.md, wiring by hand (install at yourstorybookversion, peer check, addon registration,storiesglob, browser packages), which returns to the second case above from its sub-step 2; in any other layout, wiring by hand is not covered here
- Ask whether
- Check the addon's peers. List the installed versions with
pnpm ls @storybook/addon-vitest storybook vitest, then show the addon's peers withpnpm view @storybook/addon-vitest@<the installed addon version> peerDependencies. If your installedvitestis not 5 (or not installed), avitestor@vitest/browser*range lacks Vitest 5, or thestorybookrange excludes your installedstorybook, stop and ask - Finish. Ask whether the package installs, the Chromium download and the
test:storybookscript addition below may run; if no, give the user those commands instead of running them:- If the storybook project has
extends: true, remove it (inheriting is the default) - Run
pnpm ls vitest @vitest/browser-playwright playwright. If@vitest/browser-playwrightis missing or at another version thanvitest, runpnpm add -D @vitest/browser-playwright@<the installed vitest version>; ifplaywrightis missing, runpnpm add -D playwright. Then runpnpm exec playwright install chromium(CI on Linux:pnpm exec playwright install --with-deps chromium) - Svelte CSF addon: if
package.jsondoes not list@storybook/addon-svelte-csf, runpnpm add -D @storybook/addon-svelte-csf; if.storybook/main.tsaddonsdoes not list it, add'@storybook/addon-svelte-csf'; if the stories entry ofstorieslackssvelte, addsvelteto its extensions (in whatever shape the entry has) and keep the other entries (the addon's README:'../src/**/*.stories.@(js|jsx|mjs|ts|tsx|svelte)') - Add the
test:storybookscript ifpackage.jsonlacks it ("CLI & scripts" below), then runpnpm test:storybookas thesvelte-5:vitestflake-hygiene reference describes (once msw is set up, if your stories use it:svelte-5:msw)
- If the storybook project has
Playwright Chromium is required for default browser mode; Setup B step 5 installs it (Playwright browsers).
Manual wiring follows example configuration files. The example uses mergeConfig(viteConfig, defineConfig({ test: { projects: […] } })) and a Storybook project with extends: true. That is the default, and writing it out hides the duplicate-plugin warning, so the config below leaves it out.
setupFiles: the plugin applies preview annotations automatically: it always injects@storybook/addon-vitest/internal/setup-file, and injectssetup-file-with-project-annotationsonly when you have not supplied asetProjectAnnotationssetup file. So a manual.storybook/vitest.setup.tsis not required unless you have custom per-test setup beyondpreview.ts; if you keep one that callssetProjectAnnotations, the plugin defers to it. The doc example shows that file insetupFilesanywaystorybookScript: docs: "This should match yourpackage.jsonscript to run Storybook" (e.g.pnpm storybook --no-open). You may prefix the same command with setup steps (mock data, env) so watch-mode debugging matches devstorybookUrl: defaulthttp://localhost:6006: must be reachable for failure links (debugging). Set it when your Storybook runs on another URL. WhichstorybookUrlto set for astorybookscript without-por--portis not covered here. For CI, set the full URL of the published Storybook (including path prefix if hosted under a subpath) so output links work (CI, Testing in CI)storybookScriptbehavior: in watch mode, the plugin starts Storybook via this script only if nothing is already available atstorybookUrl(API)
Vitest 5 shape (aligned with Storybook doc; add sibling projects for node/browser/etc.):
import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig, mergeConfig } from "vitest/config";
import type { ConfigEnv, UserConfig, UserConfigExport } from "vite";
import { playwright } from "@vitest/browser-playwright";
import { storybookTest } from "@storybook/addon-vitest/vitest-plugin";
import vite from "./vite.config";
const dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* widened to UserConfigExport: with the object type defineConfig() returns,
* the function branch narrows to never and the call fails with TS2349
*/
const viteExport: UserConfigExport = vite;
async function resolveViteConfig(env: ConfigEnv): Promise<UserConfig> {
return typeof viteExport === "function" ? viteExport(env) : viteExport;
}
const testConfig: UserConfig = {
test: {
projects: [
// … other projects (node, browser) …
{
plugins: [
storybookTest({
configDir: path.join(dirname, ".storybook"),
storybookScript: "pnpm storybook --no-open",
}),
],
/**
* pre-bundle the deps that trigger an optimizeDeps reload mid-test
* ("Vitest failed to find the current suite")
*
* copy each specifier verbatim from your own imports. On Vite 8, an
* unexported subpath of an installed package aborts the run before any
* test executes, a package that is not installed only warns, and an
* entry that resolves but is not the one you import passes while
* pre-bundling the wrong module
*
* msw-storybook-addon: the storybook project pre-bundles
* "msw-storybook-addon/csf3" itself; add "msw-storybook-addon/preview"
* on the createPreviewAnnotations path (svelte-5:msw skill)
*/
optimizeDeps: {
include: [
"@storybook/addon-svelte-csf",
"@storybook/addon-docs",
],
},
test: {
name: "storybook",
// no setupFiles: the plugin auto-applies preview annotations (see setupFiles note above)
browser: {
enabled: true,
headless: true,
provider: playwright({}),
instances: [{ browser: "chromium" }],
},
},
},
],
},
};
// a function export also covers a vite.config that exports defineConfig(({ mode }) => …)
export default defineConfig(async (configEnv) =>
mergeConfig(await resolveViteConfig(configEnv), testConfig),
);CLI & scripts
vitest CLI, default watch; use vitest run in CI.
Docs example: vitest --project=storybook (CLI). SETUP.md runs --project storybook from a dedicated script and keeps test:unit on node + browser, with validate running both; the addon does not require that split. The script names below match SETUP.md and the frontend skills:
{
"scripts": {
"test:unit": "vitest run --project node --project browser",
"test:storybook": "vitest run --project storybook --silent",
"test:story": "node --experimental-strip-types scripts/bin/test-story.ts"
}
}--silent: run storybook tests with --silent (test:storybook above and pnpm test:story pass it). Without it, the errors are buried in console output from the stories and msw's warnings, plus msw's request logs when a setup leaves out quiet: true in worker.start. Vitest's default reporter prints that output for every story. When an AI agent runs Vitest and neither the config nor the CLI sets a reporter, Vitest uses its minimal reporter (silent: 'passed-only'), which prints it for failing stories only. --silent hides all of it, msw's unhandled-request warnings included, for failing stories too. To find a missing fixture, rerun with pnpm exec vitest run --project storybook --silent=false, with a story file <file> appended once you know which one makes the request (svelte-5:msw).
Debugging failures, props_invalid_value, and a decorator that works in the Storybook UI but not in the Vitest run: storybook-decorator.md.
Vitest IDE can run/debug these tests from the editor.
FAQ links
- CLI / Vitest vs Storybook Interactions panel can disagree: different environments (docs)
- Vitest internal errors: read the error in the Storybook UI's testing widget and in the console; Vitest common errors
- Non-default
publicdir: setpublicDir(FAQ) - CI: dynamic import / iframe:
test.isolate: falseand/or--shard=i/n. Without isolation, several files share one page, so state onglobalThis, such as a started msw worker, carries over between them (svelte-5:msw); sharding splits by file, so it does not help failures concentrated in one file (FAQ, sharding) - Playwright (WebGL / maps / Canvas): optional
browser.provider: playwright({ launchOptions: { args: … } })per Vitest browser: not in Storybook's doc, but common for headless Chromium
Plugin options (quick)
| Option | Notes |
|---|---|
configDir |
Storybook config directory (default .storybook) (API) |
tags |
{ include, exclude, skip }, defaults include: ['test'], exclude: [], skip: []; exclude wins for the same tag in both (API) |
storybookScript |
Command to start Storybook; used in watch when storybookUrl is not already up (API) |
storybookUrl |
Used for checks + failure links in output (API) |
disableAddonDocs |
Default true, MDX mocked unless you need real MDX parsing in tests (API) |