Vitest
Config
- Docs: if unsure about an API, fetch
https://vitest.dev/llms.txt. Do not guess - Config file: use
vitest.config.{ts,mts,js,mjs}fortest/test.projects. Vitest-only-in-vite.configmerges badly with multiple projects and Storybook - Gate: no
vitest.config.*butvite.confighastest:(or no Vitest file), ask before adding projects or Storybook whether to introducevitest.config.tsand movetestout of Vite - Projects inherit the root (Vitest 5): inline
test.projectsget the root'splugins,resolve,optimizeDeps, andsetupFiles;extends: falseopts out. NEVER repeat an inherited root plugin inside a project: a secondsvelte()compiles components twice. Inheritance rules,sharedViteServer, tags: references/config-projects.md - Upgrade: bump all
@vitest/*together. Vitest 4 to 5 breaking changes and post-upgrade cleanup: references/vitest-5-upgrade.md browser.provider:import { playwright } from '@vitest/browser-playwright'toprovider: playwright()(factory, not a string). Useimport { page } from 'vitest/browser': not@vitest/browser/contextrune_outside_svelte: a rune "is only available inside.svelteand.svelte.js/tsfiles"; in browser mode, until the page has loaded Svelte's client runtime (a component,vitest-browser-svelteor an import fromsvelteitself, e.g.tick), a$statecall showsReferenceError: $state is not definedinstead (the form in a node project is not covered here). Cause: the rune sits in a.js/.tsfile without the.svelte.infix (foo.svelte.tsandfoo.svelte.test.tshave it); rename it, update its imports, and for a test file check which project'sincludeandexcludethe new name matches. On Vite 8, a dependency's file must end in.svelte.js/.svelte.ts; report one that does not to the library. More insvelte-5:testing-sveltetroubleshootingoptimizeDeps.excludedoes not fixrune_outside_svelteon Vite 8: the file name decides whether vite-plugin-svelte compiles the runes, pre-bundled or not (pre-bundling uses Rolldown since Vite 8, esbuild before)optimizeDeps.include: deps that trigger mid-test optimization (e.g.minisearch) to reduce flakes; once you list one msw entry point, list every one you import, or narrow frames withframe.protocol(svelte-5:msw). Symptoms, fixes andoptimizeDeps.entries: references/flake-hygiene.md- Storybook:
vitest.config.ts+storybookTest+ browserplaywright():svelte-5:storybook-vitest, manual setup - Reports and coverage: file-reporter paths go in
test.outputFile(reporter options beat the CLI; the HTML reporter takesoutputDir); coverage thresholds take flat metric keys, a Jest-styleglobalkey enforces nothing: references/config-projects.md
Writing tests
- Assertions: value, not presence. Presence-only assertions (
toBeInTheDocumenton a role-only or loose locator,not.toBe(''),toHaveBeenCalled) ship regressions;toBeInTheDocumenton an exact-text locator checks a value. Every interaction test must compute an expected value from the action and assert equality. See references/assertions.md for the pattern, callback-payload rules, and how to tell a harness failure from a behavior failure toHaveTextContentis exact (Vitest 5): full-string equality, noRegExp.toHaveTextContent('Error')fails onError!. Partial or regex matches usetoMatchTextContent, a weaker check: prefer the exact computed string when you can build it. In a Storybookplayfunction,expectfromstorybook/testhas jest-dom'stoHaveTextContent, which matches substrings andRegExp:svelte-5:storybook-vitest- Locators match text exactly (Vitest 5):
page.getByText('Hello')does not findHello, World. Use the full text, aRegExp, or{ exact: false }: references/browser-mode.md - Queries: accessible first, every escape hatch commented. Use
page.getByRole(...),getByLabelText,getByText,getByPlaceholder,getByTitle,getByAltTextfirst. They mirror how screen readers find elements and fail when a11y regresses.data-testidis an a11y smell (tkdodo, 2025): a testid means the element has no accessible name, role, or text for users of AT either. Fix the a11y hole, not the test. Reach fordata-testid, a rawquerySelector, or a test-id output div in a fixture only as a last resort: charting canvases, decorative content, third-party widgets without roles, an overlay that intercepts clicks on the real control, legacy markup you cannot change. Each use gets a one-line comment explaining why no accessible selector worked vitest-browser-sveltev3:renderis async-only (await render(...)); usage insvelte-5:testing-svelte. The main entry cleans up inbeforeEach;/purenever cleans up. Don't useit.concurrentfor browser component tests:expect.elementbreaks there: references/browser-mode.md- Viewport: the default is 414x896; call
page.viewport(width, height)fromvitest/browserfor desktop layouts - Mocking:
vi.mock/vi.hoistedat the top level only; reference module-level fakes in a factory viavi.hoistedor a top-levelawait import(); mock SvelteKit's$app/*in browser tests: references/mocking.md - Waiting:
await expect.element(locator)for locators,expect.poll(() => value)orvi.waitForfor spies and other state (references/browser-mode.md). Negative assertions need a positive precondition and a settle window (references/flake-hygiene.md) - Visual regression:
toMatchScreenshot(); baselines are platform-specific, so decide where they are generated before committing any: references/visual-regression.md
Before any green claim
Browser and Storybook suites are flaky on a single run. Kill the test-server port holder, clear node_modules/.vite and node_modules/.cache/storybook, then run three times: counts must match within ±0 tests and setup time within ±30%. If runs diverge, investigate the flake BEFORE claiming any fix works. Full protocol and flake patterns: references/flake-hygiene.md.