javascript / beginner
Snippet
Testing Svelte Components with Testing Library
Unit testing Svelte components involves rendering the component in a virtual DOM environment using Vitest and Svelte Testing Library. Assertions verify that props are rendered correctly and accessible elements exist.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { render, screen } from '@testing-library/svelte';import { test, expect } from 'vitest';import Counter from './Counter.svelte';test('renders initial count property', () => {render(Counter, { props: { initialCount: 5 } });const heading = screen.getByRole('heading', { level: 2 });expect(heading).toBeInTheDocument();expect(heading).toHaveTextContent('Count: 5');});
svelte
Breakdown
1
render(Counter, { props: { initialCount: 5 } });
Mounts the Svelte component in the test environment with the specified initial props.
2
expect(heading).toHaveTextContent('Count: 5');
Asserts that the queried heading node contains the expected text content based on the input prop.