Component testing helps you check if your Svelte parts work right. Testing Library makes this easy by focusing on what users see and do.
Component testing with Testing Library in Svelte
import { render, fireEvent } from '@testing-library/svelte'; import ComponentName from './ComponentName.svelte'; test('description', async () => { const { getByText } = render(ComponentName); const button = getByText('Click me'); await fireEvent.click(button); expect(getByText('Changed text')).toBeInTheDocument(); });
render() creates a test version of your component.
fireEvent simulates user actions like clicks or typing.
import { render } from '@testing-library/svelte'; import Hello from './Hello.svelte'; test('shows greeting', () => { const { getByText } = render(Hello); getByText('Hello, world!'); });
import { render, fireEvent } from '@testing-library/svelte'; import Counter from './Counter.svelte'; test('increments count on click', async () => { const { getByText } = render(Counter); const button = getByText('Count: 0'); await fireEvent.click(button); getByText('Count: 1'); });
This example shows a simple counter button. The test renders the button, checks the initial count, clicks it, and then checks the updated count. It uses an accessible label for the button to help find it in the test.
/* Counter.svelte */ <script> let count = 0; function increment() { count += 1; } </script> <button on:click={increment} aria-label="Increment count">Count: {count}</button> /* Counter.test.js */ import { render, fireEvent } from '@testing-library/svelte'; import Counter from './Counter.svelte'; test('button increments count when clicked', async () => { const { getByRole } = render(Counter); const button = getByRole('button', { name: 'Increment count' }); expect(button).toHaveTextContent('Count: 0'); await fireEvent.click(button); expect(button).toHaveTextContent('Count: 1'); });
Use accessible roles and labels to find elements in tests for better clarity and reliability.
Testing Library encourages testing what users see, not internal details.
Always await user events like clicks to handle async updates correctly.
Component testing checks if your Svelte parts behave as users expect.
Testing Library helps simulate user actions and find elements by what they show.
Write tests that focus on visible output and user interaction, not internal code.