docs/svelte-testing-library/example.mdx
:::tip
See the svelte-testing-library repository for detailed examples, including examples for testing older Svelte 3 and 4 components.
:::
This basic example demonstrates how to:
render()screen@testing-library/user-eventexpect, using matchers from
@testing-library/jest-domFor additional resources, patterns, and best practices about testing Svelte components and other Svelte features, take a look at the Svelte Society testing recipes.
<script>
let {name} = $props()
let showGreeting = $state(false)
const onclick = () => (showGreeting = true)
</script>
<button {onclick}>Greet</button>
{#if showGreeting}
<p>Hello {name}</p>
{/if}
import {render, screen} from '@testing-library/svelte'
import {userEvent} from '@testing-library/user-event'
import {expect, test} from 'vitest'
import Subject from './basic.svelte'
test('no initial greeting', () => {
render(Subject, {name: 'World'})
const button = screen.getByRole('button', {name: 'Greet'})
const greeting = screen.queryByText(/hello/iu)
expect(button).toBeInTheDocument()
expect(greeting).not.toBeInTheDocument()
})
test('greeting appears on click', async () => {
const user = userEvent.setup()
render(Subject, {name: 'World'})
const button = screen.getByRole('button')
await user.click(button)
const greeting = screen.getByText(/hello world/iu)
expect(greeting).toBeInTheDocument()
})