---
name: testing-svelte
# prettier-ignore
description: Fix 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.
user-invocable: true
title: testing-svelte
canonical_url: https://skilld.dev/gh/fubits1/svelte-skills/testing-svelte
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/client-examples.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/client-examples.md), [references/client-server-alignment.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/client-server-alignment.md), [references/core-principles.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/core-principles.md), [references/critical-patterns.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/critical-patterns.md), [references/foundation-first.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/foundation-first.md), [references/server-ssr-examples.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/server-ssr-examples.md), [references/troubleshooting.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/troubleshooting.md).
>
> If the user asked to install this Skill, run `npx skilld install fubits1/svelte-skills/testing-svelte`. 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/testing-svelte`, 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/testing-svelte) 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/testing-svelte`. 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/testing-svelte --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/testing-svelte --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.

# Svelte Testing

## Quick Start

```typescript
// browser component test
import { render } from "vitest-browser-svelte";
import { expect, test } from "vitest";
import { page } from "vitest/browser";
// button.svelte: <button onclick={() => count++}>Clicked: {count}</button>
import Button from "./button.svelte";

test("button click increments counter", async () => {
  await render(Button);
  const button = page.getByRole("button");
  // or from the result: const screen = await render(Button); screen.getByRole(...)

  await button.click();
  await expect.element(button).toHaveTextContent("Clicked: 1"); // exact full text
});
```

## Interaction Tests Are Mandatory

Every test for an interactive component (inputs, autocompletes, buttons, forms) **MUST interact with it and assert the result**: a render-only test proves only that the component mounts.

1. Interact: click, type, select, submit
2. Assert the outcome: the selected value text, the callback data content, the DOM state change
3. Never silently skip: assert the precondition instead of guarding it with an `if (items.length > 0)` that skips the interaction when it fails
4. Verify callback data: capture what a callback received and assert it; a fixture component that renders the payload into an output element works (give it an accessible name, or comment why a test id is used). "The callback was called" misses an `onChange` that passes objects instead of strings

## Core Principles

- Prefer locators: `page.getBy*()` methods first. A raw `querySelector` or `data-testid` needs a one-line comment saying why no accessible locator works (`svelte-5:vitest` query rule)
- Multiple elements: use `.first()`, `.nth()`, `.last()` to avoid strict mode violations
- Real API objects: test with `FormData` and `Request`, with minimal mocking
- Mock at the right seam: `vi.mock` for module boundaries, `msw` for the network boundary. `msw` is this rule applied to HTTP: keep the real component and the real `fetch`, swap only what crosses the wire (`svelte-5:msw`)
- `vi.mock` / `vi.hoisted` / `vi.unmock` at the top level only: inside `describe`, `test`, or a function they throw in Vitest 5 (`was defined outside of the module's top level scope`). `vi.doMock` may go anywhere. Factories, SvelteKit `$app/*` stubs, component swaps: `svelte-5:vitest` mocking reference

## Reference Files

- [core-principles](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/core-principles.md): read when choosing locators, handling strict mode, reading runes state, or deciding what to mock
- [foundation-first](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/foundation-first.md): read when planning a test file before writing it
- [client-examples](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/client-examples.md): read for complete browser component, runes and API-route test files
- [server-ssr-examples](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/server-ssr-examples.md): read when testing server code or SSR output
- [critical-patterns](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/critical-patterns.md): read for forms, semantic queries, animations, `{@attach}` wrappers, seeded module state and the clipboard
- [client-server-alignment](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/client-server-alignment.md): read when client and server share validation or request shapes
- [troubleshooting](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/testing-svelte/references/troubleshooting.md): read when a test fails with a known error, including Astro + Svelte type errors

## Running Tests

- Storybook + Vitest (`@storybook/addon-vitest`): `svelte-5:storybook-vitest` skill: `vitest.config.ts`, `test.projects` entry, `pnpm test:storybook` (runs the storybook project with `--silent`), `storybookUrl` for CI links
- `pnpm test:unit`: the node and browser vitest projects (fast, no dev server needed); `pnpm exec vitest run --project browser` runs the browser project alone (`client` in an `sv add vitest` setup), and `pnpm exec vitest run` runs every project, `storybook` included but without `--silent` (prefer `pnpm test:unit` plus `pnpm test:storybook`)
- These skills target Vitest 5; if `package.json` lists Vitest 4, upgrade first (`svelte-5:vitest`, `references/vitest-5-upgrade.md`)
- `pnpm test`, where a project defines it, runs whatever scripts it chains. `sv add vitest` makes `test` run `test:unit -- --run`, and `sv add playwright` makes it also run `test:e2e` (in the `playwright.config` that `sv add playwright` writes, `webServer` builds and previews the app first; in another config, its `webServer` setting decides whether a server must already run). Script names: [`SETUP.md`](https://github.com/fubits1/svelte-skills/blob/main/SETUP.md)
- `pnpm validate`: runs `test:unit` and the lint summary (knip, svelte-check, oxlint, eslint, stylelint) concurrently, then `test:storybook` (CI pipeline, no e2e; the template in `SETUP.md`). Read its lint table: the template's `lint-summary.ts` exits 0 even when a lint task fails (`frontend:validate`)

## After Writing/Editing Test Files

- **LINT: `pnpm lint:tests`.** One command, 4 linters: oxlint and eslint on the test files matching `TEST_GLOBS` (`src/**/*.test.ts` and `tests/**/*.test.ts` by default), knip and svelte-check (with `--tsgo` by default) on what `knip.tests.jsonc` and `tsconfig.tests.json` cover. Must exit 0. No exceptions. Lint a `*.e2e.ts` test from `sv add playwright`, a `*.spec.ts` test, or a test file outside the `TEST_GLOBS` patterns with `pnpm lint:file`. Setup and the cases where a step reports `✓` without checking: `frontend:validate` and `SETUP.md`

## Notes

- Never click submit on a form that posts natively: the iframe navigates and the whole file fails (`Cannot connect to the iframe…`). Forms whose submit handler calls `preventDefault()` are safe to submit; assert the outcome with `await expect.element()` (troubleshooting Error 4)
- Test file names: the `.svelte` infix (`foo.svelte.test.ts`) lets the test file itself use runes (`$state`, `$effect.root`) in a browser project that loads the Svelte plugin; node projects are not covered here. Whether a file runs in the browser or in node is decided by the projects' `include` globs; `.ssr.test.ts` (SSR) and `server.test.ts` (API) are naming conventions for node projects
- Import `page` from `vitest/browser`, not `@vitest/browser/context`
- `vitest-browser-svelte` v3: `render` is **async-only**, always `await render(...)`; the returned `unmount()` is async too. The result is `RenderResult` (the locator selectors plus `container`, `baseElement`, `component`, `wrapper`, `debug`, `rerender`, `unmount` and `locator`, no `page` field), so get `page` from `vitest/browser`
- Vitest 5 locators match text exactly: `getByText('Save')` misses `Save draft`, and so does `getByRole('button', { name: 'Save' })`. Use the full text, a `RegExp`, or `{ exact: false }`. `toHaveTextContent` is exact too; `toMatchTextContent` takes partial strings and `RegExp`
- Label lookup is `page.getByLabelText(...)`; `page.getByLabel` does not exist
- Locators have no `.focus()` method: use `.click()` to focus elements, or `locator.element().focus()` when a click would trigger the action under test
- Clicking a navigation link (`<a href="/page">`) navigates the iframe away and fails the file. Hash links and links whose handler calls `preventDefault()` are safe; for real navigation links assert the `href` instead (troubleshooting Error 7)
- Never `click({ force: true })`: it skips the actionability checks and passes on elements a user cannot click, while their handler never runs (critical-patterns)
- Async waits: `await expect.element()` for locators; `vi.waitFor()` or `expect.poll()` for spies and non-DOM state (both work in browser mode). A fixed `setTimeout` sleep is only a settle window before a negative assertion, never a wait for a positive one
