/svelte-5:mswfrom svelte-5
Mocks HTTP with MSW 3 in Svelte, Storybook, Vitest, and SvelteKit. Covers handler sets per surface, Vitest browser setup, and debugging blank stories or handler order.
Ships in svelte-5. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
MSW's API is documented at mswjs.io/docs, with a debugging runbook and integration guides for Vitest without Vite and Vite; mswjs.io serves no llms.txt. The Vitest page sends Vite projects to the Vite page, which has no Vitest setup; follow the Vitest browser steps below. This skill covers where the Svelte, Storybook and Vitest toolchain departs from those pages.
vi.mock replaces a module and MSW replaces the network. Use MSW to apply svelte-5:testing-svelte's "Mock at the right seam" to HTTP, so the component, fetch, Request and Response stay real. Not for replacing a module (vi.mock, svelte-5:testing-svelte) or for a one-off override in a Playwright test (page.route, see E2E below).
| Surface | Started in | Handler set |
|---|---|---|
| Storybook | mswLoader() in .storybook/preview.ts | full: every story must be hermetic |
| Vitest browser | setupWorker in a setup file, once per page | narrow: per-test worker.use(), plus a guard that fails on unmocked requests |
| Dev app | gated entry import (Vite integration); on SvelteKit, init in hooks.client/hooks.server via virtual:msw | narrow: only what the backend lacks |
Keep one handler set per surface; one shared array makes dev stop reaching your backend once a story adds a catch-all (handlers). On SvelteKit, start from the @msw/sveltekit add-on rather than hand-wiring hooks; read the code sv will run before running it (a community add-on): sveltekit.
Before step 1: install msw (pnpm add -D msw, or the @msw/sveltekit add-on on SvelteKit), serve the worker script (next section), and create the mocks index module the setup files import (handlers, "One handler set per surface").
Put the setupWorker file in the browser project's setupFiles, not the root test.setupFiles. Inline projects inherit root setupFiles (arrays concatenate), so a root entry also reaches node projects, where msw/browser does not resolve (its export map sets the node condition to null), and in the Vitest storybook project it starts a second worker next to mswLoader's, which fails every story with the WebSocket error from step 2. A node project that must not inherit the root needs extends: false (svelte-5:vitest)
Start one worker per page: keep the promise that start() returns in a globalThis slot, and let start() create and start the worker. msw 3 throws on a second worker (Failed to replace a global value at "WebSocket": already replaced.), and a test that imports worker from the setup file evaluates it a second time. The full file and the reasons are in msw-3
const page = globalThis as typeof globalThis & {
__msw?: Promise<SetupWorker>;
};
page.__msw ??= start();
export const worker = await page.__msw;
afterEach(() => worker.resetHandlers());
Place the rest of the setup file so it survives a second evaluation of the file and --isolate=false (reasons in msw-3):
worker.events listeners inside start()worker.stop() in afterAllonUnhandledFrame callback rather than plain 'warn': the test's own .svelte modules load through the worker and would each warn (the callback is in the msw-3 setup file; the step 4 guard file replaces it and skips everything outside your API paths)test.extend fixture from msw's Vitest page (written for Vitest without Vite): it calls worker.start() in every test, which msw 3 rejects from the second test on (the worker is already started)Add the unmocked-request guard from handlers. Its example covers steps 2 to 4 in one file
The browser needs the worker script, mockServiceWorker.js, served from the app root. Two ways to serve it:
msw/vite plugin (Vite 6 or later): import { msw } from "msw/vite" and add msw() to the Vite plugins (the @msw/sveltekit add-on does this)
vitest.config.ts loads it by listing msw() in its own pluginsstorybook dev gets it from the plugin: open /mockServiceWorker.js on its origin to confirm, and commit the file (item 2) if it is missingstorybook build never contains it, because a Storybook preview does not import virtual:msw (next bullet), so a built Storybook needs the committed file (item 2)virtual:msw, so a DEV guard around that import keeps it out of production. Keep the DEV guard, as the plugin's own doc comment says: "Guard mocking setup with import.meta.env.DEV to exclude both from production builds" (both: the mocking setup and the worker script) (and the Vite integration page's examples do); a build whose virtual:msw block is not DEV-gated ships msw's chunks and the worker scriptsetupWorker itself, at the Vite base (the root by default); with another base, pass serviceWorker: { url } to that start()msw({ mode: "worker-only" }) drops the virtual modules and writes the script into every client build, production included, although the Vite integration page says the worker script is "neither served nor written to your build output" in productionvitest.config.ts with svelte() or sveltekit() but no msw()), for a built Storybook, and for storybook dev when the check above fails:
pnpm exec msw init <dir> --save into public/ on Vite and static/ on SvelteKit, and re-run it after every msw upgrade: msw 3 has no postinstall step that refreshes the file, although the linked page says --save copies it on install. A stale file logs "The currently registered Service Worker has been generated by a different version of MSW"storybook dev, storybook build and the Vitest storybook project all pick it up from Vite's publicDir (static/ on SvelteKit, public/ by default), so no staticDirs entry is needed. For a script outside publicDir, add staticDirs in .storybook/main.ts for storybook dev and storybook build, and set publicDir in the Vitest config for the Vitest storybook project (addon-vitest FAQ)public/ "to the root of the dist directory as-is" (Vite assets docs), and SvelteKit does the same with static/, so the committed file ships with every production build; only code that registers it would activate it, which the DEV guard keeps outBaseline handlers go in setupWorker(...) inside mswLoader(...) from msw-storybook-addon/csf3, never in preview.parameters.msw: the loader resets to the setupWorker set before each story, and a story's own parameters.msw ([...] or { handlers: [...] }) replaces a project-level one; only the named-Record form merges by key. Write new per-story overrides as beforeEach={({ msw }) => msw.use(...)} on <Story>; existing parameters.msw overrides keep working on the mswLoader() path. The preview.ts snippet and the override details are in storybook.
onUnhandledFrame and ignores onUnhandledRequest, so a leftover onUnhandledRequest: 'error' falls back to 'warn', with no message about the ignored key. TypeScript flags the old key in an object literal passed to start() or listen() in a file your tsconfig includes (on an sv create SvelteKit project, .storybook/ and tests/ are not), while an options object built elsewhere can carry it unflagged; JavaScript and .svelte files without type checks do not flag it. A custom callback takes ({ frame, defaults }): frame.protocol === 'http' marks a request frame, frame.data.request holds the request, and defaults.warn() prints the default warningonUnhandledFrame: 'error' fails no browser test: MSW logs the request and answers it with a 500 itself, so a component that handles the failure stays green. Record the request in a callback and assert in afterEach: handlers'warn' and 'error' skip every request whose path ends in a common file extension, .json, .txt, .csv, .xml, .md and .pdf included: an unmocked GET /api/items.json gets no warning and no 500 and reaches the network. Guard API paths by prefix instead (handlers, list in msw-3)msw/browser but not msw/experimental in optimizeDeps.include loads two copies of msw's classes, so frame instanceof HttpNetworkFrame is false for every frame: once you list one msw entry point, list every one you import, or check frame.protocol. svelte-5:storybook-vitest owns optimizeDeps for the Vitest storybook projecthttp.get('/api/items', ...) also answers /api/items?page=2, and a ? in the path (http.get('/api/items?page=1', ...)) is dropped with Found a redundant usage of query parameters; match the query with a predicate (handlers)onUnhandledFrame never sees it. To leave other queries unhandled, match only the query you answer: handlers has a predicate handler for that<iframe> load goes through the worker like a fetch, so give the framed URL a handler or it is handled as an unmocked request (a warning, or a failure under the guard). A cross-origin frame document never reaches the page's worker; cross-origin fetch calls from the page still dosvelte-5:vitest)--silent (svelte-5:storybook-vitest), or console output buries the errors (msw logs every mocked request, plus a start message, when the setup leaves out quiet: true). --silent also hides the console warnings that name each unhandled request. In an AI agent's run, Vitest hides them for passing stories even without --silent when neither the config nor the CLI sets a reporter (it then uses its minimal reporter, silent: 'passed-only'). To find a missing fixture, run pnpm exec vitest run --project storybook --silent=false (storybook being your storybook project's name), with a story file <file> appended once you know which one makes the request; the test:story script from svelte-5:storybook-vitest always passes --silentevent.fetch calls to your own +server.js routes. With SSR on (the default) the browser worker does not mock them on first load either, and fetches from a server load never reach it (sveltekit)| Symptom | Cause | Fix |
|---|---|---|
every story fails, Failed to fetch, or [MSW] Failed to register | worker script not served: suspect it before the handlers | open /mockServiceWorker.js in the browser, or under Vitest look for GET /mockServiceWorker.js with a 404 or 500 in the test output; an error status or a MIME-type error means it is not served (browser integration), so serve it (worker script options above) |
console warns about an unhandled request (in a Vitest run, hidden by --silent, and for passing stories by the minimal reporter an AI agent's run uses when no reporter is set) | no handler for that URL; under storybook dev, Storybook's own requests can warn too, with the addon's default setup or yours (storybook) | in a Vitest run, rerun with --silent=false (command in the --silent trap above) to see the warnings; add a handler to the set, or filter Storybook's requests in the callback; a relative path only matches the page origin, so a backend on another origin needs */ or a full URL |
request answered with the wrong body: an empty 200, or a 404 with [mocks] no fixture naming a route you mocked | a catch-all ordered first, or a string path that ignores the query | catch-alls last; a predicate for the query (handlers) |
only stories with their own parameters.msw lose shared data | project-level parameters.msw replaced by the story's own | baseline in setupWorker(...) |
| handlers built by your own loader apply only sometimes, or not at all | loader writes after an await (races mswLoader), or sits on the component or story level (runs too late) | order and timing in handlers |
E2E is a separate surface: @msw/playwright binds MSW to Playwright fixtures (use a release whose msw peer range names msw 3). For a one-off override in a Playwright test without MSW, Playwright's own page.route is enough.
One run of a browser or MSW suite can pass by chance, so clear the caches and take three runs before calling it green (svelte-5:vitest flake hygiene). Only a test project that mounts a component or opens a story exercises the mocks, whatever its script is named.
.svelte files, the Vitest setup file, msw-storybook-addon 2 to 3, the old @msw/sveltekit scaffoldonUnhandledFrame callback, instanceof and optimizeDeps, the worker script, navigations and iframes, companion package supportpreview.ts loader, where the baseline lives, per-story overrides, choosing between mswLoader() and createPreviewAnnotations (the deprecation path, when to keep the addon out of main.ts addons), the addon codemod's blind spot for .stories.svelte@msw/sveltekit add-on, what it generates and how to adjust it, HMR in dev, the production build check, the SSR interception blind spot, Storybook and Vitest on SvelteKitsvelte-5:storybook-vitest: owns optimizeDeps and the Vitest storybook projectsvelte-5:storybook: story authoring, Svelte 4 store wrappers, Playwright verificationsvelte-5:testing-svelte: what to mock at the module seam insteadsvelte-5:vitest: browser projects, flake hygiene, test tagsfrontend:validate: what counts as verified before declaring done (in the frontend plugin)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub fubits1/svelte-skills --plugin svelte-58 skills in this plugin
/code-style-svelteSvelte component code style rules. Auto-invoke when creating .svelte files, editing component structure, transitions or layout reads, or SvelteKit URL state and navigation guards. Covers component docs and Svelte style conventions./composition-svelteUse when composing a Svelte 5 feature from provider/wrapper components, content snippets, reactive state, or third-party DOM bridging (maplibre, leaflet, d3, tippy, popper). Covers overlay wrappers, snippet APIs, and state location./doc-componentDocument a Svelte component using @component JSDoc. Auto-invoke when asked to document a .svelte component. Reads the component, analyzes its interface, and writes a structured @component comment block./storybookStorybook authoring and browser checks for Svelte: MCP instructions, previews, Svelte 4 store wrappers, CSS imports in preview.ts. Use when writing or reviewing .stories.svelte files, moving a CSS import that stories need, or a story renders empty./storybook-vitestSvelte CSF stories as Vitest browser tests via @storybook/addon-vitest: play, tags, decorators, asChild. Use when wiring or debugging them in Vitest/CI, or on 'Vitest failed to find the current suite' or props_invalid_value. Not for React/Vue./testing-svelteFix or write Svelte 5 tests with vitest-browser-svelte and Playwright. Use when debugging broken or flaky tests, 'Cannot connect to the iframe', strict mode violations, or writing unit/SSR/e2e tests.Other plugins' skills for the same job