From ce5bc7042b0f5ad16e22d7bcfb85a987139d0dc4 Mon Sep 17 00:00:00 2001 From: fubits1 Date: Sun, 18 Oct 2026 23:01:37 +0200 Subject: [PATCH 1/2] refactor: msw 3 skill --- .gitignore | 1 + plugins/svelte-5/README.md | 1 + plugins/svelte-5/skills/msw/SKILL.md | 115 +++++---- .../skills/msw/references/handlers.md | 231 ++++++++++++++++-- .../svelte-5/skills/msw/references/msw-3.md | 157 ++++++++++++ .../msw/references/msw-storybook-addon-v3.md | 72 ++++-- .../skills/msw/references/storybook.md | 42 ++++ .../skills/msw/references/sveltekit.md | 114 +++++++-- 8 files changed, 610 insertions(+), 123 deletions(-) create mode 100644 plugins/svelte-5/skills/msw/references/msw-3.md create mode 100644 plugins/svelte-5/skills/msw/references/storybook.md 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..bb55bf4 100644 --- a/plugins/svelte-5/skills/msw/SKILL.md +++ b/plugins/svelte-5/skills/msw/SKILL.md @@ -1,87 +1,98 @@ --- 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: "MSW (Mock Service Worker, msw 3 and 2) in Svelte: Storybook, Vitest browser, SvelteKit. Use for any msw question and whenever you mock an API or fetch in stories, browser tests or the dev app: http.get handlers, mockServiceWorker.js, onUnhandledRequest or onUnhandledFrame, msw-storybook-addon and parameters.msw, fixtures, query strings, empty or blank stories, 'Failed to fetch', unmocked requests passing tests, 'Failed to replace a global value', upgrading msw 2 to 3." +compatibility: "msw 3 on Node 22.12 or later; msw 2 in a project that runs Storybook, until an msw-storybook-addon release supports msw 3" 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): [intercepting requests](https://mswjs.io/docs/http/intercepting-requests/), [mocking responses](https://mswjs.io/docs/http/mocking-responses/), [browser](https://mswjs.io/guides/integrations/browser), [node](https://mswjs.io/guides/integrations/node) and [Vite](https://mswjs.io/guides/integrations/vite) integration, [`msw init`](https://mswjs.io/api/cli/init), [structuring handlers](https://mswjs.io/guides/best-practices/structuring-handlers), [runtime overrides](https://mswjs.io/guides/best-practices/network-behavior-overrides), [WebSockets](https://mswjs.io/docs/websocket/), [debugging runbook](https://mswjs.io/docs/runbook), [2.x to 3.x migration](https://mswjs.io/docs/migrations/2.x-to-3.x), [Vitest browser mode](https://mswjs.io/guides/integrations/vitest). mswjs.io serves no `llms.txt`. 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. +Verified line: a "(measured)" mark means a minimal probe project reproduced the behaviour. The msw 3 measurements ran on msw 3, Vitest 5 browser mode with `@vitest/browser-playwright`, Vite 8 and Chromium, the Vitest setup file with two test files under default isolation and under `--isolate=false --no-file-parallelism` (one shared page); the msw 2 variant of the unmocked-request guard ran on msw 2 with the same tooling. The Storybook and addon measurements ran on a four-story Svelte CSF probe, two consecutive runs, with msw 2, `msw-storybook-addon` 2 and 3, Storybook 10, `@storybook/addon-svelte-csf` 5, `@storybook/addon-vitest` 10, Vitest 4, Vite 8 and Svelte 5; Storybook on msw 3 is not measured here. SvelteKit guidance is read from the docs and `@msw/sveltekit`'s source, not run. -**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. MSW applies `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). + +## Before upgrading to msw 3 + +- Storybook: the msw maintainer [advises against](https://github.com/mswjs/msw-storybook-addon/issues/200) msw 3 with `msw-storybook-addon` 3 until [addon PR #199](https://github.com/mswjs/msw-storybook-addon/pull/199) ships. Before bumping a project that runs Storybook, check whether an addon release contains that PR; if none does, keep msw 2 +- Node: msw 3 needs Node 22.12 or later (`engines` in [msw's `package.json`](https://github.com/mswjs/msw/blob/main/package.json); the migration guide names Node 22, which `engines` narrows) +- msw 3 renames `onUnhandledRequest` to `onUnhandledFrame` and ignores the old name at runtime, so a missed rename falls back to `'warn'` with no message; TypeScript flags it, JavaScript and `.svelte` files without type checks do not. A custom callback changes shape too: `(request, print)` becomes `({ frame, defaults })`, where `frame.protocol === 'http'` marks a request frame, `frame.data.request` holds the request, and `defaults.warn()` replaces `print.warning()` +- The codemod skips `.svelte` files. `@mswjs/data` and `@mswjs/socket.io-binding` work with msw 2 only; the data library's successor, `@msw/data`, declares no msw dependency + +Everything else for the upgrade: [msw-3](references/msw-3.md). ## 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`. +| 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; on SvelteKit with msw 3, `init` in `hooks.client`/`hooks.server` via `virtual:msw` | narrow: only what the backend lacks | -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 setup, in order, once msw is installed and the worker script is served (below): -## 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. +1. Put the `setupWorker` file in the browser project's `setupFiles`, not the root `test.setupFiles`. Inline projects inherit root `setupFiles` (arrays concatenate; measured on Vitest 5 with a generic setup file), so a root entry also loads `msw/browser` in node projects. A node project that must not inherit the root needs `extends: false` (`frontend:vitest`) +2. Start one worker per page. msw 3 allows one started worker per page and throws on a second one (measured). A test that imports `worker` from the setup file makes the page evaluate it twice, once as a setup file under its file-system URL and once as an import under its root URL, so module-scope code creates and starts a second worker. Keep the promise that `start()` returns in a `globalThis` slot, and let `start()` create and start the worker; the full file is in [msw-3](references/msw-3.md) -```ts -// .storybook/preview.ts -import { setupWorker } from "msw/browser"; -import { mswLoader } from "msw-storybook-addon/csf3"; -import { handlers } from "../src/mocks/handlers"; + ```ts + const page = globalThis as typeof globalThis & { + __msw?: Promise; + }; + page.__msw ??= start(); + export const worker = await page.__msw; + afterEach(() => worker.resetHandlers()); + ``` -export default { - loaders: [ - mswLoader(async () => { - const worker = setupWorker(...handlers); // the baseline resetHandlers() restores to - await worker.start({ onUnhandledRequest: "warn", quiet: true }); - return worker; - }), - ], -}; -``` +3. Register Vitest hooks at module scope, after the slot, and do not stop the worker in `afterAll`. With `--isolate=false` the files share one page and the setup file runs again before each file, so hooks registered inside `start()` exist for the first file only, and its `worker.stop()` leaves every later file unmocked (measured). `worker.events` listeners go inside `start()`: they attach to the one worker, and at module scope every evaluation adds another (measured: two calls per request). [msw's Vitest page](https://mswjs.io/guides/integrations/vitest) also skips `worker.stop()`, but its `test.extend` fixture calls `worker.start()` in every test, which msw 3 rejects from the second test on (`the worker is already started`, measured) +4. Add the unmocked-request guard from [handlers](references/handlers.md). Its example covers steps 2 to 4 in one file -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. +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 [`@msw/sveltekit`](https://github.com/mswjs/sveltekit) (`npx sv add @msw/sveltekit`) rather than hand-wiring hooks, unless the project runs Storybook and stays on msw 2 while the addon blocker above holds: [sveltekit](references/sveltekit.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`. +The browser needs the worker script, `mockServiceWorker.js`. The dev app defaults to the `msw/vite` plugin on msw 3. Vitest browser tests and Storybook use the committed file, which every measurement here ran on. Two ways to serve the script: -On SvelteKit, start from [`@msw/sveltekit`](https://github.com/mswjs/sveltekit) (`npx sv add @msw/sveltekit`) rather than hand-wiring hooks: `references/sveltekit.md`. +1. `msw/vite` plugin (msw 3): `import { msw } from "msw/vite"` and add `msw()` to the Vite plugins. It serves the worker script in dev and emits it only into client bundles that import `virtual:msw`, so a DEV guard around that import keeps it out of production ([Vite integration](https://mswjs.io/guides/integrations/vite)). `msw({ mode: "worker-only" })` serves the script without the virtual modules, for code that calls `setupWorker` itself; its `generateBundle` writes the worker script into every client build, production included (msw's `src/vite/plugin.ts`), although the Vite integration page says no mode writes it in production +2. Committed file: [`npx msw init --save`](https://mswjs.io/api/cli/init) into `public/` on Vite and `static/` on SvelteKit, with Storybook serving that directory through `staticDirs: ["../public"]` (`["../static"]` on SvelteKit) in `.storybook/main.ts`; the Vitest storybook project serves it through Vite's `publicDir` instead ([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)). Re-run it after every msw upgrade: msw 3 has no postinstall step that refreshes the file. 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 -### Old patterns: msw-storybook-addon 2.x +## Storybook wiring for Svelte CSF -On 2.x the baseline goes in `initialize(options, handlers)` at module scope, `loaders: [mswLoader]` takes a bare reference rather than a call, and `optimizeDeps.include` names the bare `msw-storybook-addon`. The `beforeEach={({ msw }) => msw.use(...)}` form does not work at all there, because v2's loader never assigns `context.msw`. Everything else above, including where the baseline must live, applies to both majors. +Baseline handlers go in `setupWorker(...)` inside `mswLoader(...)`, 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. The `preview.ts` snippet, the per-story override forms and the addon 2 and msw 2 patterns are in [storybook](references/storybook.md). ## Traps -- **`optimizeDeps.include` must name the specifier you import** (`msw-storybook-addon/csf3` on the loader path, `/preview` on the annotations path). Measured on Vite 8.1.5: an unresolvable entry aborts the run before any test executes; a stale-but-resolvable one passes silently while pre-bundling the wrong module; a **missing** one lets Vite discover the dependency mid-run and kills the suite with `Vitest failed to find the current suite` (`svelte-5:storybook-vitest` owns this trap). -- **Handler modules must be import-safe.** Warn on a missing fixture, never throw: Vitest tags skip a test _body_ but still import the file (`frontend:vitest`). -- **Run storybook tests with `--silent`** or MSW request logging drowns the output. -- **SvelteKit SSR cannot intercept your own `+server.js` routes**, and hydration will not cover for it either (`references/sveltekit.md`). +- `optimizeDeps.include` must name the specifier you import (`msw-storybook-addon/csf3` on the loader path, `/preview` on the annotations path); a missing entry kills the suite mid-run with `Vitest failed to find the current suite` (measured). The three outcomes are in [msw-storybook-addon-v3](references/msw-storybook-addon-v3.md), and `svelte-5:storybook-vitest` owns the trap. Listing `msw/browser` but not `msw/experimental` loads two copies of msw's classes, so `frame instanceof HttpNetworkFrame` is `false` for every frame (measured): once you list one msw entry point, list every one you import, or check `frame.protocol` +- `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 (measured). Record the request in a callback and assert in `afterEach`: [handlers](references/handlers.md) +- A string path ignores the query: `http.get('/api/items', ...)` also answers `/api/items?page=2` (measured) +- 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 (measured). 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 test that renders a same-origin `