Testing Svelte components

By Esteban Trillonew today7 min readWhy SvelteSvelte

Same test, two doors. The name on the file decides whether it runs in a browser or in a room where $effect doesn't exist.
Same test, two doors. The name on the file decides whether it runs in a browser or in a room where $effect doesn't exist.

Part 17 of a series on Svelte in 2026. Part 16 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.1 With both, it adds Vitest, Playwright and vitest-browser-svelte, and writes two projects into vite.config.ts:

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.2 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.

The test file is…
Where sv's config runs it
server project, Node
What happened
Passes. This is what the server project is for.
Where sv's config runs it
server project, Node
What happened
ReferenceError: $state is not defined. Runes only compile in files with .svelte in the name.
Where sv's config runs it
server project, Node
What happened
lifecycle_function_unavailable: mount(...) is not available on the server.
Where sv's config runs it
server project, Node
What happened
No error. The module compiles for the server, where effects don't exist, so the log stays [] even after flushSync().
Where sv's config runs it
server project, Node
What happened
Passes: two items, total 10. $derived works on the server; only effects are missing.
Where sv's config runs it
client project, Chromium
What happened
effect_orphan: $effect can only be used inside an effect.
Where sv's config runs it
client project, Chromium
What happened
Passes, in a real browser.
Where sv's config runs it
jsdom project (not part of sv's setup)
What happened
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.3 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:

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”.

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?

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

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)”.4 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.3 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:

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.3 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.

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?

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.5 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.2 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.

Footnotes

  1. Svelte CLI docs, vitest. ↩

  2. vitest-browser-svelte README and v3.0.0 release notes (“Make render async-only”); Vitest blog, Vitest 5.0 is out. ↩ ↩2 ↩3

  3. Svelte docs, Testing. ↩ ↩2 ↩3

  4. Vitest docs, Assertion API. ↩

  5. React docs, act. ↩

Read next

  1. Observability in SvelteKitDec 2, 2026 Why Svelte · 6 min
  2. Svelte vs React: one component, two waysDec 2, 2026 Why Svelte · 7 min
  3. Migrating to SvelteKit 3 with sv migrateDec 1, 2026 Why Svelte · 7 min
  4. SvelteKit 3: what's newDec 1, 2026 Why Svelte · 8 min
  5. Remote functions in SvelteKitDec 1, 2026 Why Svelte · 8 min
Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.