Publié · en amélioration
Guide SvelteKit · 5/6
Ce chapitre n'est disponible qu'en anglais pour le moment.
SvelteKit projects are usually tested with two tools. Vitest, which shares your Vite configuration, covers functions and components, while Playwright checks that the whole app works in a real browser.
The sv add-ons set up both tools in one go.
npx sv add vitest playwright
npm run test:unit # Vitest
npm run test:e2e # PlaywrightThe vitest add-on installs the packages, adds package.json scripts and writes a Vite test configuration that runs server and client code separately. What it generates can change between sv releases, so open vite.config.ts and package.json afterwards to see what you got. The examples below follow the setup described in the official Svelte docs: jsdom with Testing Library.
Pure functions in src/lib can be imported and tested directly. Test files usually sit next to the code they test, named *.test.ts or *.spec.ts.
// src/lib/price.ts
export function formatPrice(cents: number) {
return `$${(cents / 100).toFixed(2)}`;
}
// src/lib/price.test.ts
import { describe, expect, it } from 'vitest';
import { formatPrice } from './price.js';
describe('formatPrice', () => {
it('formats cents as dollars', () => {
expect(formatPrice(1250)).toBe('$12.50');
});
});Runes such as $state are only compiled inside .svelte and .svelte.ts files. To test logic that uses them, name the test file *.svelte.test.ts.
// src/lib/counter.svelte.ts
export function createCounter() {
let count = $state(0);
const double = $derived(count * 2);
return {
get count() { return count; },
get double() { return double; },
increment() { count += 1; }
};
}// src/lib/counter.svelte.test.ts
import { expect, test } from 'vitest';
import { createCounter } from './counter.svelte.js';
test('double follows count', () => {
const counter = createCounter();
expect(counter.double).toBe(0);
counter.increment();
expect(counter.count).toBe(1);
expect(counter.double).toBe(2);
});When the code under test uses $effect, wrap the test body in $effect.root, and call flushSync() from svelte to run pending effects synchronously.
Render components in a jsdom environment with Testing Library, and query elements the way users see them: by role and by text.
npm install -D jsdom @testing-library/svelte @testing-library/user-event @testing-library/jest-dom// part of vite.config.ts
export default defineConfig({
plugins: [sveltekit({ adapter: adapter() })],
test: {
environment: 'jsdom',
setupFiles: ['./vitest-setup.ts']
},
resolve: process.env.VITEST ? { conditions: ['browser'] } : undefined
});The browser resolve condition makes Vitest load Svelte's browser build during tests. Put a single line, import '@testing-library/jest-dom/vitest';, in vitest-setup.ts to add matchers such as toHaveTextContent. Import defineConfig from vitest/config so the test block is typed as well.
// src/lib/components/Counter.test.ts
import { render, screen } from '@testing-library/svelte';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import Counter from './Counter.svelte';
test('clicking the button increments the count', async () => {
const user = userEvent.setup();
render(Counter, { props: { initial: 1 } });
const button = screen.getByRole('button');
await user.click(button);
expect(button).toHaveTextContent('2');
});Load functions and form actions are ordinary async functions, so you can also call them with a stub event object that contains just the fields they use, and assert on the result.
Playwright builds the app, serves it with the preview server and drives a real browser against it. The configuration created by sv add playwright looks much like this:
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run build && npm run preview',
port: 4173
},
testDir: 'tests'
});// tests/home.test.ts
import { expect, test } from '@playwright/test';
test('home page shows a heading', async ({ page }) => {
await page.goto('/');
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
});Run npx playwright install once to download the browsers. Flows that involve both server and browser, such as form actions with progressive enhancement, are best verified end to end.
npx sv add vitest playwright.*.svelte.test.ts.
0 commentaire
Se connecter · Connectez-vous pour laisser un commentaire.
Soyez le premier à commenter.