Vitest helps you check if your Svelte code works correctly by running tests automatically.
0
0
Vitest setup in Svelte
Introduction
You want to make sure your Svelte components behave as expected.
You want to catch mistakes early before your app goes live.
You want to run tests quickly during development.
You want to add confidence when changing or adding new features.
Syntax
Svelte
npm install -D vitest @testing-library/svelte @sveltejs/vite-plugin-svelte // vitest.config.ts import { defineConfig } from 'vitest/config' import { svelte } from '@sveltejs/vite-plugin-svelte' export default defineConfig({ plugins: [svelte()], test: { globals: true, environment: 'jsdom' } })
Install Vitest and Svelte testing tools as developer dependencies.
Configure Vitest to use the Svelte plugin and set the test environment to simulate a browser.
Examples
Installs Vitest and helpers for testing Svelte components.
Svelte
npm install -D vitest @testing-library/svelte @sveltejs/vite-plugin-svelte
Basic Vitest config to enable Svelte support and browser-like testing environment.
Svelte
// vitest.config.ts import { defineConfig } from 'vitest/config' import { svelte } from '@sveltejs/vite-plugin-svelte' export default defineConfig({ plugins: [svelte()], test: { globals: true, environment: 'jsdom' } })
Sample Program
This test renders a simple Button component, checks if the label appears, and verifies the click event works.
Svelte
// Example test file: src/__tests__/Button.test.ts import { render, fireEvent } from '@testing-library/svelte' import Button from '../Button.svelte' import { describe, it, expect } from 'vitest' describe('Button component', () => { it('shows the correct label and reacts to click', async () => { const { getByText } = render(Button, { props: { label: 'Click me' } }) const button = getByText('Click me') expect(button).toBeTruthy() let clicked = false button.addEventListener('click', () => { clicked = true }) await fireEvent.click(button) expect(clicked).toBe(true) }) })
OutputSuccess
Important Notes
Use jsdom environment to simulate browser features in tests.
Use @testing-library/svelte for easy component rendering and user event simulation.
Run tests with npx vitest or add a script in package.json like "test": "vitest".
Summary
Vitest helps test Svelte components quickly and simply.
Install Vitest and configure it with the Svelte plugin and jsdom environment.
Write tests using @testing-library/svelte to check component behavior.