Svelte Testing
Quick Start
// 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.
- Interact: click, type, select, submit
- Assert the outcome: the selected value text, the callback data content, the DOM state change
- Never silently skip: assert the precondition instead of guarding it with an
if (items.length > 0)that skips the interaction when it fails - 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
onChangethat passes objects instead of strings
Core Principles
- Prefer locators:
page.getBy*()methods first. A rawquerySelectorordata-testidneeds a one-line comment saying why no accessible locator works (svelte-5:vitestquery rule) - Multiple elements: use
.first(),.nth(),.last()to avoid strict mode violations - Real API objects: test with
FormDataandRequest, with minimal mocking - Mock at the right seam:
vi.mockfor module boundaries,mswfor the network boundary.mswis this rule applied to HTTP: keep the real component and the realfetch, swap only what crosses the wire (svelte-5:msw) vi.mock/vi.hoisted/vi.unmockat the top level only: insidedescribe,test, or a function they throw in Vitest 5 (was defined outside of the module's top level scope).vi.doMockmay go anywhere. Factories, SvelteKit$app/*stubs, component swaps:svelte-5:vitestmocking reference
Reference Files
- core-principles: read when choosing locators, handling strict mode, reading runes state, or deciding what to mock
- foundation-first: read when planning a test file before writing it
- client-examples: read for complete browser component, runes and API-route test files
- server-ssr-examples: read when testing server code or SSR output
- critical-patterns: read for forms, semantic queries, animations,
{@attach}wrappers, seeded module state and the clipboard - client-server-alignment: read when client and server share validation or request shapes
- troubleshooting: read when a test fails with a known error, including Astro + Svelte type errors
Running Tests
- Storybook + Vitest (
@storybook/addon-vitest):svelte-5:storybook-vitestskill:vitest.config.ts,test.projectsentry,pnpm test:storybook(runs the storybook project with--silent),storybookUrlfor CI links pnpm test:unit: the node and browser vitest projects (fast, no dev server needed);pnpm exec vitest run --project browserruns the browser project alone (clientin ansv add vitestsetup), andpnpm exec vitest runruns every project,storybookincluded but without--silent(preferpnpm test:unitpluspnpm test:storybook)- These skills target Vitest 5; if
package.jsonlists 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 vitestmakestestruntest:unit -- --run, andsv add playwrightmakes it also runtest:e2e(in theplaywright.configthatsv add playwrightwrites,webServerbuilds and previews the app first; in another config, itswebServersetting decides whether a server must already run). Script names:SETUP.mdpnpm validate: runstest:unitand the lint summary (knip, svelte-check, oxlint, eslint, stylelint) concurrently, thentest:storybook(CI pipeline, no e2e; the template inSETUP.md). Read its lint table: the template'slint-summary.tsexits 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 matchingTEST_GLOBS(src/**/*.test.tsandtests/**/*.test.tsby default), knip and svelte-check (with--tsgoby default) on whatknip.tests.jsoncandtsconfig.tests.jsoncover. Must exit 0. No exceptions. Lint a*.e2e.tstest fromsv add playwright, a*.spec.tstest, or a test file outside theTEST_GLOBSpatterns withpnpm lint:file. Setup and the cases where a step reports✓without checking:frontend:validateandSETUP.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 callspreventDefault()are safe to submit; assert the outcome withawait expect.element()(troubleshooting Error 4) - Test file names: the
.svelteinfix (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'includeglobs;.ssr.test.ts(SSR) andserver.test.ts(API) are naming conventions for node projects - Import
pagefromvitest/browser, not@vitest/browser/context vitest-browser-sveltev3:renderis async-only, alwaysawait render(...); the returnedunmount()is async too. The result isRenderResult(the locator selectors pluscontainer,baseElement,component,wrapper,debug,rerender,unmountandlocator, nopagefield), so getpagefromvitest/browser- Vitest 5 locators match text exactly:
getByText('Save')missesSave draft, and so doesgetByRole('button', { name: 'Save' }). Use the full text, aRegExp, or{ exact: false }.toHaveTextContentis exact too;toMatchTextContenttakes partial strings andRegExp - Label lookup is
page.getByLabelText(...);page.getByLabeldoes not exist - Locators have no
.focus()method: use.click()to focus elements, orlocator.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 callspreventDefault()are safe; for real navigation links assert thehrefinstead (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()orexpect.poll()for spies and non-DOM state (both work in browser mode). A fixedsetTimeoutsleep is only a settle window before a negative assertion, never a wait for a positive one