# Testing Svelte components

- Published: 2026-12-02
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-17-testing-svelte-components/

> Part 17 of a series on Svelte in 2026. [Part 16](/writing/why-svelte-16-migrating-to-sveltekit-3-with-sv-migrate/) ran the SvelteKit 3 migration over a real app. This part sets up tests for the components you migrated.

I had a five-line module, `logger.svelte.ts`, that pushes a value into an array from inside an `$effect`. I wrote a test for it in `logger.spec.ts`, called `flushSync()` the way the docs say, and asserted the log held one entry. It held none. No error, no warning, just `[]`.

The test was fine. The file name was wrong. In the setup `sv add vitest` gives you, a file without `.svelte` in its name runs in Node, and Node gets the server build of your module, where `$effect` compiles to nothing. Rename it `logger.svelte.spec.ts` and the same code runs in Chromium, where it fails loudly for a different reason, and then passes once you fix that.

That's most of what's Svelte-specific about testing. Get the file name right and the rest is ordinary Testing Library work. I built the lab with sv 1.1.1 on a minimal SvelteKit 3.1.0 app (Svelte 5.57.3, Vite 8.3.5, Playwright 1.64.1 Chromium), and ran every test again on Vitest 5.0.5 to check nothing moved.

## What sv sets up

`npx sv add vitest` asks whether you want unit tests, component tests or both.[^cli] With both, it adds Vitest, Playwright and `vitest-browser-svelte`, and writes two projects into `vite.config.ts`:

```ts title="vite.config.ts (generated, trimmed)"
projects: [
  {
    extends: "./vite.config.ts",
    test: {
      name: "client",
      browser: {
        enabled: true,
        provider: playwright(),
        instances: [{ browser: "chromium", headless: true }],
      },
      include: ["src/**/*.svelte.{test,spec}.{js,ts}"],
      exclude: ["src/lib/server/**"],
    },
  },
  {
    extends: "./vite.config.ts",
    test: {
      name: "server",
      environment: "node",
      include: ["src/**/*.{test,spec}.{js,ts}"],
      exclude: ["src/**/*.svelte.{test,spec}.{js,ts}"],
    },
  },
];
```

So `.svelte.spec.ts` goes to a real Chromium through Vitest's browser mode, and every other `.spec.ts` goes to Node. The `.svelte` part of the name was already doing a job before sv got here: it's how the compiler knows to process runes in a JS or TS file, the same rule part 8 hit with `.svelte.ts` modules. sv reuses it to pick the environment too, so one suffix answers two questions, and it's easy to answer them by accident.

One version note. sv 1.1.1 pins Vitest `^4.1.8` and `vitest-browser-svelte` `^2.1.1`, so I got 4.1.12 and 2.2.1, though Vitest 5 shipped on September 3 and `vitest-browser-svelte` 3 made `render` async-only.[^vbs] I upgraded a copy. sv's config ran unchanged on Vitest 5.0.5, and so did every Svelte behaviour below, but any test that did `const screen = render(Counter)` and then `screen.getByRole(...)` broke with "screen.getByRole is not a function". Write `await render(...)` now; awaiting works on 2.x too, so you won't have to touch it later.

## One module, eight file names

Here's what I saw for each case. The server-side ones are the interesting ones, because only some of them fail.

**Where a Svelte test runs.** The test file is…

| File | Where sv's config runs it | What happened |
| --- | --- | --- |
| greet.spec.ts, testing a plain function | server project, Node | Passes. This is what the server project is for. |
| count.spec.ts, with let count = $state(0) in the test | server project, Node | ReferenceError: $state is not defined. Runes only compile in files with .svelte in the name. |
| Counter.spec.ts, calling render or mount | server project, Node | lifecycle_function_unavailable: mount(...) is not available on the server. |
| logger.spec.ts, importing a .svelte.ts module that uses $effect | server project, Node | No error. The module compiles for the server, where effects don't exist, so the log stays [] even after flushSync(). |
| cart.spec.ts, importing a class with $state and $derived fields | server project, Node | Passes: two items, total 10. $derived works on the server; only effects are missing. |
| logger.svelte.spec.ts, calling the same module without $effect.root | client project, Chromium | effect_orphan: $effect can only be used inside an effect. |
| Counter.svelte.spec.ts, rendering and clicking | client project, Chromium | Passes, in a real browser. |
| Toast.jsdom.spec.ts, dismissing a transition:fade element | jsdom project (not part of sv's setup) | element.animate is not a function, as an unhandled error. The <p> was still in the DOM 600 ms later. In Chromium it was gone a little over 400 ms after the click. |

A rune in a plain `.spec.ts` throws `$state is not defined`, which is at least honest. Mounting a component there throws `lifecycle_function_unavailable`, since Node gets Svelte's server entry, where `mount` only exists to throw. The effect case is the quiet one. vite-plugin-svelte compiles the imported `.svelte.ts` for SSR, and the server build drops effects (part 5 showed the same thing in compiled output), so `logger()` returns an array nothing will ever write to. `flushSync` from the server entry has nothing to flush.

That doesn't mean the server project is useless for runes. A `Cart` class with a `$state` array and a `$derived` total passed in Node: two items, total 10. Deriveds still compute on the server. If the logic under test is state and derived values, Node is fine and faster. Once there's an effect anywhere in the path, the test belongs in a `.svelte.spec.ts`.

## Testing runes without a component

The docs' advice before any component test is to ask whether you're really testing the logic inside it, and to pull that logic out if so.[^docs] Runes make that easy, since a `.svelte.ts` module can hold the same state a component would. Effects need one more thing: an owner. Called straight from a test, `logger()` threw `effect_orphan` in Chromium, the same error part 8 got from a module-level `$effect`. The fix is to wrap the test in `$effect.root`:

```ts title="src/lib/logger.svelte.spec.ts"
import { flushSync } from "svelte";
import { expect, test } from "vitest";
import { logger } from "./logger.svelte";

test("logs each value", () => {
  const stop = $effect.root(() => {
    let count = $state(0);
    const log = logger(() => count);

    flushSync();
    expect(log).toEqual([0]);

    count = 1;
    flushSync();
    expect(log).toEqual([0, 1]);
  });
  stop();
});
```

I logged the array at each step: `[]` before the first `flushSync`, `[0]` after it, still `[0]` right after `count = 1`, and `[0, 1]` after the second flush. Effects are scheduled, not run on write, and `flushSync` is how a test says "now".

**Quiz:** A teammate moves logger.svelte.spec.ts to logger.spec.ts to get it out of the slow browser project. The test body stays the same, $effect.root and all. What happens?

- It passes, faster
- It fails on the first assertion, expected [] to equal [0]
- It fails with ReferenceError: $effect is not defined

**Answer:** It fails with ReferenceError: $effect is not defined — The test file's own runes don't compile without the .svelte suffix, and $effect.root is the first one it hits. Remove them and you get the quieter failure: an empty log, no error.

- Not "It passes, faster": It would only pass if the effect ran. In the server project the module is compiled for SSR, so the log stays [].
- Not "It fails on the first assertion, expected [] to equal [0]": Close, but it never gets there: the test body itself uses $effect.root and $state, and runes don't compile in a file without .svelte in its name.

## Component tests in a real browser

For components, sv's choice is `vitest-browser-svelte` in Chromium, and the test looks like Testing Library because the package is a fork of it:[^vbs]

```ts title="src/lib/Counter.svelte.spec.ts"
import { expect, test } from "vitest";
import { page } from "vitest/browser";
import { render } from "vitest-browser-svelte";
import Counter from "./Counter.svelte";

test("counts by step", async () => {
  await render(Counter, { step: 2 });
  await page.getByRole("button").click();
  await expect.element(page.getByRole("button")).toHaveTextContent("Clicked 2");
  await expect.element(page.getByText("Doubled: 4")).toBeInTheDocument();
});
```

`expect.element` retries until the assertion passes or times out, which Vitest's docs pitch for exactly the case where a condition is "delayed (by a timeout, network request, or animation)".[^assert] That turned out to matter. My `Toast` component removes a `<p>` with `transition:fade` over 400 ms. Right after the click, the text was still in the page, because an outro keeps the node until it finishes. A one-shot `expect(...).toBeNull()` there fails. `expect.element(...).not.toBeInTheDocument()` waited a little over 400 ms and passed.

The docs suggest a wrapper component for tests that need two-way binding or snippet props.[^docs] For simple cases I didn't need one. A `.svelte.spec.ts` can use runes, so a `$bindable` prop can be a getter and setter over local state:

```ts
let name = $state("");
await render(NameInput, {
  get value() {
    return name;
  },
  set value(v) {
    name = v;
  },
});
await page.getByLabelText("Name").fill("ada");
// name is now "ada"
```

Svelte warned `state_referenced_locally` where I read `name` in the test body afterwards, and the value was right anyway; the warning is about components, where that read would go stale. Props work the same way. Passing a `$state({ name: "ada" })` object and setting `props.name = "grace"` updated the rendered text, while a plain object did nothing (part 6 is why: props are read through getters). For `children`, `createRawSnippet` from `svelte` builds a snippet from an HTML string, which covered my `Card` test. It wants HTML for a single element (anything else gets an `invalid_raw_snippet_render` warning in dev), so anything richer is still wrapper-component territory.

## What about jsdom

The Svelte docs still lead with jsdom: install it, set `environment: 'jsdom'`, and add `resolve.conditions: ['browser']` when `VITEST` is set.[^docs] Skip that last line and Svelte resolves to its server entry even though `document` exists; my jsdom project failed every test with the same `mount(...) is not available on the server` as the Node one. `@testing-library/svelte` ships a `svelteTesting()` Vite plugin that adds the condition for you.

With the condition in place, the docs' examples worked: `mount`, click, `flushSync`, and Testing Library with `user-event`. The toast didn't. jsdom has no `element.animate`, which Svelte's transitions run on, so the outro threw `element.animate is not a function` as an unhandled error and the `<p>` was still there 600 ms later. Vitest flagged the error. A test that only checked the toast appeared would have passed and printed it as noise.

That's my case for staying with sv's browser setup. jsdom is quicker to start, but a component with a transition, or anything that depends on layout, needs a real browser to tell you the truth.

**Quiz:** In a jsdom test, you click Dismiss on a toast whose <p> has transition:fade, then wait a full second. What does the DOM hold?

- Nothing; the outro finished and removed the <p>
- The <p>, still there, plus an unhandled element.animate error
- Nothing, because Svelte skips transitions when there's no animation API

**Answer:** The <p>, still there, plus an unhandled element.animate error — jsdom doesn't implement the Web Animations API, so the outro never runs and never finishes.

- Not "Nothing; the outro finished and removed the <p>": That's what Chromium did, a little over 400 ms after the click.
- Not "Nothing, because Svelte skips transitions when there's no animation API": It doesn't check. It calls element.animate and throws.

## React has act; Svelte has flushSync

React's testing story revolves around `act()`, which "makes sure all updates related to these 'units' have been processed and applied to the DOM before you make any assertions," and React Testing Library wraps its helpers in it so you rarely type it.[^act] Svelte's version is `flushSync`, and in practice you need it less. If you click with a bare `button.click()`, the text still reads "Clicked 0" until you flush; I saw that in jsdom and in Chromium. If you click through `user-event` or a browser-mode locator, the click is awaited and Svelte's microtask has run by the time it returns: a plain `expect` right after `await button.click()` read "Clicked 1". `vitest-browser-svelte` says outright that it doesn't use `act` and leans on retrying assertions instead.[^vbs] I didn't run React for this part; that comparison is from the docs.

## What I'd set up

`sv add vitest` with both usages, then upgrade to Vitest 5 and `vitest-browser-svelte` 3 and write `await render` from day one. Logic with state and deriveds goes in a `.svelte.ts` module and gets a plain `.spec.ts` that runs in Node. Anything with an effect, and every component, goes in a `.svelte.spec.ts`. And when a test of a `.svelte.ts` module passes with suspiciously little happening, check the file name before the code.

Next: observability in SvelteKit.

[^cli]: Svelte CLI docs, [vitest](https://svelte.dev/docs/cli/vitest).

[^docs]: Svelte docs, [Testing](https://svelte.dev/docs/svelte/testing).

[^vbs]: [vitest-browser-svelte](https://github.com/vitest-community/vitest-browser-svelte) README and v3.0.0 release notes ("Make render async-only"); Vitest blog, [Vitest 5.0 is out](https://vitest.dev/blog/vitest-5).

[^assert]: Vitest docs, [Assertion API](https://vitest.dev/api/browser/assertions).

[^act]: React docs, [act](https://react.dev/reference/react/act).

- **Part 18 — Observability in SvelteKit**: Tracing, logging and error reporting in SvelteKit 3
