पाठ 23 / 25
Testing With Vitest and Playwright
Unit, component and end-to-end tests.
A testing pyramid for Svelte
Vitest runs unit tests for plain modules and logic, and component tests through @testing-library/svelte (render, then query by role or text and fire events) in a jsdom or browser environment. Test files that use runes should be named with .svelte.test.ts so the compiler processes them. Playwright runs end-to-end tests against a built app in real browsers, which is the right level for routing, form actions, hooks and progressive enhancement. npx sv add vitest and npx sv add playwright set up both. Also run svelte-check (usually npm run check) in CI for type and template diagnostics.
A component test and an e2e test
Counter and signup flow.
// src/lib/Counter.test.ts (Vitest + @testing-library/svelte, jsdom environment)
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('increments on click', async () => {
render(Counter);
const button = screen.getByRole('button');
await userEvent.click(button);
expect(button).toHaveTextContent('Clicked 1 time'); // needs jest-dom matchers set up
});
// e2e/signup.test.ts (Playwright)
import { test, expect } from '@playwright/test';
test('shows a validation error for a bad email', async ({ page }) => {
await page.goto('/signup');
await page.getByRole('textbox').fill('not-an-email');
await page.getByRole('button', { name: 'Sign up' }).click();
await expect(page.getByRole('alert')).toHaveText('Enter a valid email');
});Test the no-JavaScript path too
Playwright can create a context with JavaScript disabled, which verifies that form actions still work before use:enhance takes over.
त्वरित जाँच: Which tool is best suited to verify a form action redirect end to end?
- Playwright against the running app
- A Vitest unit test of a utility function
- svelte-check
- The Svelte compiler warnings
Answer
Playwright against the running app — Routing and server behaviour need a real browser and server.