Index of every page on this site: llms.txt
All skills
fubits1 avatar

/testing-svelte

@a024d57
by Iljafubits1/svelte-skills11 stars
2
Run it yourself

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.

Use this Skill: https://skilld.dev/gh/fubits1/svelte-skills/testing-svelte

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

SKILL.md

≈54 tokens for metadata: the name and description. ≈1.9k when used: this file. ≈9.5k more on demand in 7 files.

Description uses 2.7% of example budget

Before choosing a Skill, your Agent reads its name and description. All available Skills share that space.

  • A shorter description leaves more room for other Skills. This entry exceeds our 1% size suggestion.

In our Claude Code example, all Skill names and descriptions share 8,000 characters. This Skill uses ≈216 characters, or 2.7%.

The 1% threshold is a size suggestion. Longer descriptions can still fit.

Your model, settings, and other Skills decide how much text your Agent can read.

Example settings and source

The example uses a 200k-token context and default Claude Code settings. The count includes the name, description, separators, and when_to_use when present. Codex also counts local file paths.

Skit's source and limits: Codex 0.160.1, Claude Code 2.1.292.

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.

  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: 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-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
  • 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

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides comprehensive instructions and best practices for testing Svelte 5 applications using Vitest and Playwright. It covers unit, SSR, and E2E testing, with a focus on resilient locators, accessibility, and the use of real web API objects like FormData and Request. No security issues were detected.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at a024d57. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub last month.

Activeupdated last month
user-invocable
true

README badge

README badge for fubits1/svelte-skills/testing-svelte