Svelte 51: Testing Components
easy⏱ 5 mincoursesvelte
What a real component test checks
Tests render the component, simulate a real user interaction, then assert the resulting DOM or state matches expectations — no manual clicking required ever again once the test exists.
// LikeButton.spec.js
import { render, fireEvent, screen } from '@testing-library/svelte';
import LikeButton from './LikeButton.svelte';
test('toggles liked state and increments count', async () => {
render(LikeButton, { props: { initialLikes: 4 } });
const btn = screen.getByRole('button');
await fireEvent.click(btn);
expect(screen.getByText('5 likes')).toBeTruthy();
expect(btn.getAttribute('aria-pressed')).toBe('true');
});
Read the fake runner
In defaultCode, runTests() programmatically clicks the real like button twice and checks two assertions afterward: the count returned to its starting value, and aria-pressed reflects the liked state. Try clicking the heart yourself first, then hit 'Run tests' — watch how the assertions still hold no matter the starting state, because the test computes deltas.
Test behavior, not implementation
Notice the real spec above queries by role and visible text — not by internal variable names. That's deliberate: tests that only care what the USER sees keep passing even after you refactor the component's internals.