---
name: vitest
description: Vitest test.projects, browser mode with playwright(), optimizeDeps, separate vitest.config from vite.config. Use when editing vitest config, debugging flaky browser tests, upgrading @vitest/*, or splitting node vs browser projects.
compatibility: Written for Vitest 5 (Node 22.12+, 24 or 26+; Vite >=6.4; factory browser provider, test.projects)
user-invocable: true
title: vitest
canonical_url: https://skilld.dev/gh/fubits1/svelte-skills/vitest
last_updated: 2026-10-27T03:01:58.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/assertions.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/assertions.md), [references/browser-mode.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/browser-mode.md), [references/config-projects.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/config-projects.md), [references/flake-hygiene.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/flake-hygiene.md), [references/mocking.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/mocking.md), [references/visual-regression.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/visual-regression.md), [references/vitest-5-upgrade.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/vitest-5-upgrade.md).
>
> If the user asked to install this Skill, run `npx skilld install fubits1/svelte-skills/vitest`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/vitest`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/fubits1/svelte-skills/vitest) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/vitest`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/vitest --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/vitest --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# 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}`** for `test` / `test.projects`. Vitest-only-in-`vite.config` merges badly with multiple projects and Storybook
- **Gate:** no `vitest.config.*` but `vite.config` has **`test:`** (or no Vitest file), **ask** before adding projects or Storybook whether to introduce `vitest.config.ts` and move `test` out of Vite
- **Projects inherit the root (Vitest 5):** inline `test.projects` get the root's `plugins`, `resolve`, `optimizeDeps`, and `setupFiles`; `extends: false` opts out. **NEVER repeat an inherited root plugin inside a project**: a second `svelte()` compiles components twice. Inheritance rules, `sharedViteServer`, tags: [references/config-projects.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/config-projects.md)
- Upgrade: bump all **`@vitest/*`** together. Vitest 4 to 5 breaking changes and post-upgrade cleanup: [references/vitest-5-upgrade.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/vitest-5-upgrade.md)
- **`browser.provider`:** `import { playwright } from '@vitest/browser-playwright'` to `provider: playwright()` (factory, not a string). Use `import { page } from 'vitest/browser'`: not `@vitest/browser/context`
- **`rune_outside_svelte`:** a rune "is only available inside `.svelte` and `.svelte.js/ts` files"; in browser mode, until the page has loaded Svelte's client runtime (a component, `vitest-browser-svelte` or an import from `svelte` itself, e.g. `tick`), a `$state` call shows `ReferenceError: $state is not defined` instead (the form in a node project is not covered here). Cause: the rune sits in a `.js`/`.ts` file without the `.svelte.` infix (`foo.svelte.ts` and `foo.svelte.test.ts` have it); rename it, update its imports, and for a test file check which project's `include` and `exclude` the 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 in `svelte-5:testing-svelte` troubleshooting
- **`optimizeDeps.exclude` does not fix `rune_outside_svelte`** on 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 with `frame.protocol` (`svelte-5:msw`). Symptoms, fixes and `optimizeDeps.entries`: [references/flake-hygiene.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/flake-hygiene.md)
- **Storybook:** **`vitest.config.ts`** + `storybookTest` + browser `playwright()`: `svelte-5:storybook-vitest`, [manual setup](https://storybook.js.org/docs/writing-tests/integrations/vitest-addon#manual-setup-advanced)
- **Reports and coverage:** file-reporter paths go in `test.outputFile` (reporter options beat the CLI; the HTML reporter takes `outputDir`); coverage thresholds take flat metric keys, a Jest-style `global` key enforces nothing: [references/config-projects.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/config-projects.md)

## Writing tests

- **Assertions: value, not presence.** Presence-only assertions (`toBeInTheDocument` on a role-only or loose locator, `not.toBe('')`, `toHaveBeenCalled`) ship regressions; `toBeInTheDocument` on 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](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/assertions.md) for the pattern, callback-payload rules, and how to tell a harness failure from a behavior failure
- **`toHaveTextContent` is exact (Vitest 5):** full-string equality, no `RegExp`. `toHaveTextContent('Error')` fails on `Error!`. Partial or regex matches use **`toMatchTextContent`**, a weaker check: prefer the exact computed string when you can build it. In a Storybook `play` function, `expect` from `storybook/test` has jest-dom's `toHaveTextContent`, which matches substrings and `RegExp`: `svelte-5:storybook-vitest`
- **Locators match text exactly (Vitest 5):** `page.getByText('Hello')` does not find `Hello, World`. Use the full text, a `RegExp`, or `{ exact: false }`: [references/browser-mode.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/browser-mode.md)
- **Queries: accessible first, every escape hatch commented.** Use `page.getByRole(...)`, `getByLabelText`, `getByText`, `getByPlaceholder`, `getByTitle`, `getByAltText` first. They mirror how screen readers find elements and fail when a11y regresses. `data-testid` is an a11y smell ([tkdodo, 2025](https://tkdodo.eu/blog/test-ids-are-an-a11y-smell)): 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 for `data-testid`, a raw `querySelector`, 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-svelte` v3:** `render` is async-only (`await render(...)`); usage in `svelte-5:testing-svelte`. The main entry cleans up in `beforeEach`; `/pure` never cleans up. Don't use `it.concurrent` for browser component tests: `expect.element` breaks there: [references/browser-mode.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/browser-mode.md)
- **Viewport:** the default is 414x896; call `page.viewport(width, height)` from `vitest/browser` for desktop layouts
- **Mocking:** `vi.mock` / `vi.hoisted` at the top level only; reference module-level fakes in a factory via `vi.hoisted` or a top-level `await import()`; mock SvelteKit's `$app/*` in browser tests: [references/mocking.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/mocking.md)
- **Waiting:** `await expect.element(locator)` for locators, `expect.poll(() => value)` or `vi.waitFor` for spies and other state ([references/browser-mode.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/browser-mode.md)). Negative assertions need a positive precondition and a settle window ([references/flake-hygiene.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/flake-hygiene.md))
- **Visual regression:** `toMatchScreenshot()`; baselines are platform-specific, so decide where they are generated before committing any: [references/visual-regression.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/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](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/vitest/references/flake-hygiene.md).
