javascript / beginner
Snippet
Writing Component Unit Assertions with Svelte Testing Library
Unit tests for Svelte components verify that UI elements render expected content based on passed props. Using the render method mounts the component into an isolated testing DOM, while queries like screen.getByText locate the rendered node.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
import { render, screen } from '@testing-library/svelte';import { test, expect } from 'vitest';import StatusBadge from './StatusBadge.svelte';test('renders active status badge correctly', () => {render(StatusBadge, { status: 'Online' });const badge = screen.getByText('Online');expect(badge).toBeDefined();});
svelte
Breakdown
1
import { render, screen } from '@testing-library/svelte';
Imports the component rendering and DOM querying utilities.
2
render(StatusBadge, { status: 'Online' });
Mounts the target Svelte component with a mock prop payload.
3
const badge = screen.getByText('Online');
Searches the virtual document tree for an element displaying the specified text.
4
expect(badge).toBeDefined();
Asserts that the element was successfully located in the output DOM.