diff --git a/.gitignore b/.gitignore index 8f32210..b264291 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .DS_Store .dex +plugins/*/evals/* diff --git a/plugins/svelte-5/README.md b/plugins/svelte-5/README.md index c30c685..602c552 100644 --- a/plugins/svelte-5/README.md +++ b/plugins/svelte-5/README.md @@ -16,6 +16,7 @@ For installation and setup, see the [root README](https://github.com/fubits1/sve | `code-style-svelte` | Svelte component style -- docs, reactivity, Svelte 5 syntax, interop rules | | `composition-svelte` | Composing Svelte 5 features by role -- Composition shape and Non-Svelte Host (Provider is a behaviour within Composition), snippet API, state location, third-party DOM bridging, overlay a11y | | `doc-component` | `@component` JSDoc for Svelte components | +| `msw` | Mock Service Worker 3 in Storybook, Vitest browser tests and SvelteKit -- handler sets, unmocked-request guard, msw 2 to 3 upgrade | | `storybook` | Storybook workflow -- MCP tools, fixtures, CSS imports, wrapper pattern | | `storybook-vitest` | Svelte CSF + addon-vitest -- `.stories.svelte` as Vitest browser tests | | `testing-svelte` | Svelte 5 tests with vitest-browser-svelte and Playwright | diff --git a/plugins/svelte-5/skills/msw/SKILL.md b/plugins/svelte-5/skills/msw/SKILL.md index 4e6aa55..b7a31d7 100644 --- a/plugins/svelte-5/skills/msw/SKILL.md +++ b/plugins/svelte-5/skills/msw/SKILL.md @@ -1,87 +1,111 @@ --- name: msw # prettier-ignore -description: "MSW 2 (Mock Service Worker) mocking in Svelte: Storybook, Vitest browser tests, SvelteKit dev/SSR. Use when writing handlers or fixtures, when a story renders blank or errors Failed to fetch, or when migrating msw-storybook-addon v2 to v3." -compatibility: "Run 2026-07 against msw 2.15.0 with msw-storybook-addon 2.0.7 and 3.0.0, Storybook 10.5, @storybook/addon-svelte-csf 5.1, @storybook/addon-vitest 10.5.3, Vitest 4.1.10, Vite 8.1.5, Svelte 5. One msw version only; SvelteKit guidance is unrun." +description: "Mocks HTTP with msw 3 in Svelte, Storybook, Vitest and SvelteKit. Use when writing http.get handlers or parameters.msw, upgrading from msw 2, or debugging blank stories, handler order, query strings, onUnhandledFrame or mockServiceWorker.js." +compatibility: "msw 3 on Node 22.12 or later (on SvelteKit 3: Node 22.17, and TypeScript 6 if you use TypeScript); Vitest 5; SvelteKit 3; msw-storybook-addon 3 with Storybook 9 or later (Storybook 10 on SvelteKit 3 and for the Vitest storybook project on Vitest 5)" user-invocable: true --- # MSW (Mock Service Worker) -**The API lives in the docs, not here.** [mswjs.io/docs](https://mswjs.io/docs): [intercepting requests](https://mswjs.io/docs/http/intercepting-requests/), [mocking responses](https://mswjs.io/docs/http/mocking-responses/), [browser](https://mswjs.io/docs/integrations/browser) and [node](https://mswjs.io/docs/integrations/node) integration, [`msw init`](https://mswjs.io/docs/cli/init), [structuring handlers](https://mswjs.io/docs/best-practices/structuring-handlers), [runtime overrides](https://mswjs.io/docs/best-practices/network-behavior-overrides), [WebSockets](https://mswjs.io/docs/websocket/), [debugging runbook](https://mswjs.io/docs/runbook). There is no `llms.txt`. +MSW's API is documented at [mswjs.io/docs](https://mswjs.io/docs), with a [debugging runbook](https://mswjs.io/docs/runbook) and integration guides for [Vitest without Vite](https://mswjs.io/guides/integrations/vitest) and [Vite](https://mswjs.io/guides/integrations/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. -This skill carries what those pages do not: where the Svelte and Storybook toolchain contradicts them, and the traps written down nowhere. - -**Which seam:** `vi.mock` replaces a module, MSW replaces the network. MSW is `svelte-5:testing-svelte`'s "only mock external services" applied to HTTP, so keep the real component, the real `fetch`, real `Request`/`Response`. +`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). ## Three surfaces, three handler sets | Surface | Started in | Handler set | | --- | --- | --- | | Storybook | `mswLoader()` in `.storybook/preview.ts` | full: every story must be hermetic | -| Vitest browser | `setupWorker` in a setup file | narrow: per-test `worker.use()` | -| Dev app | gated entry import (`hooks.client.ts` on SvelteKit) | narrow: only what the backend lacks | - -For Vitest browser, 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 loads `msw/browser` in node projects. That inheritance was measured on Vitest 5 with a generic setup file; the MSW runs in the compatibility line above predate it. A node project that must not inherit the root needs `extends: false` (`frontend:vitest`). - -One shared array across all three means dev stops talking to your backend the moment someone adds a catch-all for a story. The rest, including the catch-all failure signature and stateful factories, is in `references/handlers.md`. - -The worker script comes from [`msw init --save`](https://mswjs.io/docs/cli/init), into `public/` on Vite and `static/` on SvelteKit, and Storybook must serve it via `staticDirs`. When every story fails at once rather than one of them, suspect the worker before the handlers: open `/mockServiceWorker.js` in the browser, and a 404 or a MIME-type error there means it is not being served ([browser integration](https://mswjs.io/docs/integrations/browser)). +| 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](https://mswjs.io/guides/integrations/vite)); 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](references/handlers.md)). On SvelteKit, start from the [`@msw/sveltekit`](https://github.com/mswjs/sveltekit) add-on rather than hand-wiring hooks; read the code `sv` will run before running it (a community add-on): [sveltekit](references/sveltekit.md). + +## Vitest browser setup + +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"). + +1. 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` (`frontend:vitest`) +2. 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](references/msw-3.md) + + ```ts + const page = globalThis as typeof globalThis & { + __msw?: Promise; + }; + page.__msw ??= start(); + export const worker = await page.__msw; + afterEach(() => worker.resetHandlers()); + ``` + +3. Place the rest of the setup file so it survives a second evaluation of the file and `--isolate=false` (reasons in [msw-3](references/msw-3.md)): + - Vitest hooks at module scope, after the slot + - `worker.events` listeners inside `start()` + - no `worker.stop()` in `afterAll` + - an `onUnhandledFrame` 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) + - no `test.extend` fixture from [msw's Vitest page](https://mswjs.io/guides/integrations/vitest) (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`) +4. Add the unmocked-request guard from [handlers](references/handlers.md). Its example covers steps 2 to 4 in one file + +## The worker script + +The browser needs the worker script, `mockServiceWorker.js`, served from the app root. Two ways to serve it: + +1. `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) + - it serves the worker script to the dev server and to every Vitest browser project whose config loads the plugin, the Vitest storybook project included; a standalone `vitest.config.ts` loads it by listing `msw()` in its own `plugins` + - `storybook dev` gets it from the plugin: open `/mockServiceWorker.js` on its origin to confirm, and commit the file (item 2) if it is missing + - a `storybook 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) + - it emits the script only into client bundles that import `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](https://mswjs.io/guides/integrations/vite) page's examples do); a build whose `virtual:msw` block is not DEV-gated ships msw's chunks and the worker script + - the default mode also serves the script to code that calls `setupWorker` 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 production +2. Committed file, for a project without the plugin, for a Vitest config that does not load it (a standalone `vitest.config.ts` with `svelte()` or `sveltekit()` but no `msw()`), for a built Storybook, and for `storybook dev` when the check above fails: + - run [`pnpm exec msw init --save`](https://mswjs.io/api/cli/init) 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](https://storybook.js.org/docs/writing-tests/integrations/vitest-addon#how-do-i-ensure-my-tests-can-find-assets-in-the-public-directory)) + - Vite copies `public/` "to the root of the dist directory as-is" ([Vite assets docs](https://vite.dev/guide/assets.html)), 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 out ## Storybook wiring for Svelte CSF -Two upstream sources mislead a Svelte reader. The addon's README and MIGRATION.md route you to CSF Next, which `@storybook/addon-svelte-csf` does not support. [Storybook's MSW page](https://storybook.js.org/docs/writing-stories/mocking-data-and-modules/mocking-network-requests) documented the addon v2 API well after v3 shipped; check which API it shows before copying from it. - -```ts -// .storybook/preview.ts -import { setupWorker } from "msw/browser"; -import { mswLoader } from "msw-storybook-addon/csf3"; -import { handlers } from "../src/mocks/handlers"; - -export default { - loaders: [ - mswLoader(async () => { - const worker = setupWorker(...handlers); // the baseline resetHandlers() restores to - await worker.start({ onUnhandledRequest: "warn", quiet: true }); - return worker; - }), - ], -}; -``` - -Only the `...handlers` argument differs from the addon's own example, and it is the load-bearing part: **baseline handlers go in `setupWorker(...)`, never in `preview.parameters.msw`**, which the README's CSF 3 example gets wrong. The loader resets handlers before each story and `combineParameters` overwrites arrays, so project-level parameters vanish for exactly the stories that override anything. +Baseline 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 ``; existing `parameters.msw` overrides keep working on the `mswLoader()` path. The `preview.ts` snippet and the override details are in [storybook](references/storybook.md). -Per-story overrides use `parameters={{ msw: { handlers: [...] } }}`. Upstream has scheduled both this and the CSF 3 loader API for removal. There is a non-deprecated alternative that works in Svelte CSF (`createPreviewAnnotations` from `msw-storybook-addon/preview`), but it ignores `parameters.msw` entirely, so taking it means rewriting every override as `beforeEach={({ msw }) => msw.use(...)}`. Both paths, with what was measured: `references/msw-storybook-addon-v3.md`. - -On SvelteKit, start from [`@msw/sveltekit`](https://github.com/mswjs/sveltekit) (`npx sv add @msw/sveltekit`) rather than hand-wiring hooks: `references/sveltekit.md`. +## Traps -### Old patterns: msw-storybook-addon 2.x +- msw 3 reads `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 warning +- `onUnhandledFrame: '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](references/handlers.md) +- The built-in `'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](references/handlers.md), list in [msw-3](references/msw-3.md)) +- Listing `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 project +- A string path ignores the query: `http.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](references/handlers.md)) +- A matched handler whose resolver returns nothing does not make the request unhandled. MSW falls through to the next matching handler and, if none answers, sends the request to the network; `onUnhandledFrame` never sees it. To leave other queries unhandled, match only the query you answer: [handlers](references/handlers.md) has a predicate handler for that +- msw 3 intercepts navigations, including iframe loads ([msw#2721](https://github.com/mswjs/msw/pull/2721)): a same-origin `