Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 35 ยท Quality

Testing Svelte Components and Logic

Test Svelte 5 apps with Vitest, @testing-library/svelte and Playwright - unit tests for logic, component tests, testing runes in .svelte.js files and end-to-end tests.

Tests let you change code without fear. In a Svelte project there are three useful layers: unit tests for plain functions and rune-based logic, component tests that render a component in a fake DOM and click things, and end-to-end tests that drive a real browser against your running app. Vitest covers the first two, Playwright the third.

Vitest and Playwright need Node and a real project, so the test code is read-only here. The <TryIt> blocks run a tiny test runner, a fake component and a fake DOM in plain JavaScript to show how the pieces fit together.

Setting up Vitest

If you chose Vitest when running npx sv create, it is already configured. Manually, install vitest, @testing-library/svelte, @testing-library/jest-dom and jsdom, then extend vite.config.js:

JavaScript
import { defineConfig } from 'vitest/config';
import { sveltekit } from '@sveltejs/kit/vite';
import { svelteTesting } from '@testing-library/svelte/vite';

export default defineConfig({
  plugins: [sveltekit(), svelteTesting()],
  test: {
    environment: 'jsdom',
    include: ['src/**/*.{test,spec}.{js,ts}'],
    setupFiles: ['./vitest-setup.js'],
  },
});

svelteTesting() makes Svelte resolve its browser build (otherwise components would compile for the server) and cleans up the DOM after each test. vitest-setup.js usually only imports @testing-library/jest-dom/vitest to add matchers like toBeInTheDocument(). Run tests with npx vitest (watch mode) or npx vitest run.

Unit tests for plain logic

Pure functions are the easiest and most valuable tests. Keep rules (pricing, validation, formatting) out of components and in $lib modules:

JavaScript
// src/lib/cart.js
export function total(items) {
  return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
JavaScript
// src/lib/cart.test.js
import { describe, it, expect } from 'vitest';
import { total } from './cart.js';

describe('total', () => {
  it('sums price times quantity', () => {
    expect(total([{ price: 5, qty: 2 }, { price: 1.5, qty: 2 }])).toBe(13);
  });

  it('is 0 for an empty cart', () => {
    expect(total([])).toBe(0);
  });
});

describe groups, it (or test) defines a case, expect(...).toBe(...) asserts. Here is the shape of what the runner does:

JS A tiny describe / it / expect runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Testing runes outside components

Runes work in .svelte.js and .svelte.ts files, so shared reactive logic can be tested without a component. Name the test file something.svelte.test.js so the compiler handles runes:

JavaScript
// src/lib/counter.svelte.js
export function createCounter(start = 0) {
  let count = $state(start);
  const doubled = $derived(count * 2);
  return {
    get count() { return count; },
    get doubled() { return doubled; },
    increment() { count += 1; },
  };
}
JavaScript
// src/lib/counter.svelte.test.js
import { describe, it, expect } from 'vitest';
import { flushSync } from 'svelte';
import { createCounter } from './counter.svelte.js';

describe('createCounter', () => {
  it('derives doubled', () => {
    const c = createCounter(2);
    c.increment();
    expect(c.count).toBe(3);
    expect(c.doubled).toBe(6);
  });

  it('runs effects after flushSync', () => {
    const seen = [];
    const cleanup = $effect.root(() => {
      const c = createCounter();
      $effect(() => { seen.push(c.count); });
      flushSync();
      c.increment();
      flushSync();
    });
    expect(seen).toEqual([0, 1]);
    cleanup();
  });
});

$derived values update right away when read. Effects are batched, so call flushSync() to run them in the test, and wrap effects in $effect.root() because effects need an owner outside of a component.

Component tests with Testing Library

Testing Library encourages tests that look like what a user does: find things by their accessible role or text, click, type, then check the page.

JavaScript
// src/lib/Counter.test.js
import { render, screen } from '@testing-library/svelte';
import userEvent from '@testing-library/user-event';
import { describe, it, expect } from 'vitest';
import Counter from './Counter.svelte';

describe('Counter', () => {
  it('increments when the button is clicked', async () => {
    const user = userEvent.setup();
    render(Counter, { start: 5 });

    expect(screen.getByText('Count: 5')).toBeInTheDocument();
    await user.click(screen.getByRole('button', { name: /add one/i }));
    expect(screen.getByText('Count: 6')).toBeInTheDocument();
  });
});

render(Component, props) mounts the component into document.body. Queries come in three families: getBy... (throws if missing), queryBy... (returns null, for asserting absence) and findBy... (async, waits). Prefer getByRole, getByLabelText and getByText over CSS selectors: tests then double as an accessibility check.

Here is a miniature version using a fake component and a fake DOM:

JS Render, find by role, click, assert

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real library does the same with the real DOM and accessible-name computation. Notice the test never touches count: it only looks at the output and uses the button the way a person would.

End-to-end tests with Playwright

Playwright launches real browsers against your running app (often the production preview). It tests routing, forms, server code and the browser together:

JavaScript
// tests/todos.test.js
import { test, expect } from '@playwright/test';

test('adds a todo', async ({ page }) => {
  await page.goto('/todos');
  await page.getByLabel('New todo').fill('Write more tests');
  await page.getByRole('button', { name: 'Add' }).click();
  await expect(page.getByText('Write more tests')).toBeVisible();
});

Set webServer in playwright.config.js to { command: 'npm run build && npm run preview', port: 4173 } and run npx playwright test. Playwright auto-waits for elements, so you rarely need sleeps.

What to test

Layer Tests Speed
Unit (Vitest) pure functions, stores, rune logic milliseconds
Component (Testing Library) rendering, events, props tens of ms
E2E (Playwright) critical user journeys: sign up, checkout seconds

Write many unit tests, a fair number of component tests and a few E2E tests for the paths that must never break. Avoid asserting internal state or class names; test visible behavior.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file name lets you use runes in a test?

    Runes only compile in .svelte, .svelte.js and .svelte.ts files, so the test needs the .svelte.test.js suffix.
  2. 2. Why call flushSync() in a rune test?

    Effects are batched and run asynchronously; flushSync runs them now so you can assert on their results.
  3. 3. Which query should you prefer in Testing Library?

    Role and text queries match how users and assistive technology find things and make tests robust to markup changes.
  4. 4. What does Playwright test that Vitest with jsdom cannot?

    Playwright drives real Chromium, Firefox or WebKit against your running app, so it covers the whole stack.

Summary

  • Use Vitest for unit and component tests (with jsdom and svelteTesting()), Playwright for end-to-end.
  • Test runes in .svelte.test.js files; use flushSync and $effect.root for effects.
  • render plus role-based queries and userEvent test behavior, not implementation.
  • Keep business rules in plain modules so they are easy to unit test.

Next: Svelte Accessibility