|
| 1 | +# Basic |
| 2 | + |
| 3 | +This basic example demonstrates how to: |
| 4 | + |
| 5 | +- Pass props to your Svelte component using [render()] |
| 6 | +- [Query][] the structure of your component's DOM elements using screen |
| 7 | +- Interact with your component using [@testing-library/user-event][] |
| 8 | +- Make assertions using expect, using matchers from |
| 9 | + [@testing-library/jest-dom][] |
| 10 | + |
| 11 | +[query]: https://testing-library.com/docs/queries/about |
| 12 | +[render()]: https://testing-library.com/docs/svelte-testing-library/api#render |
| 13 | +[@testing-library/user-event]: https://testing-library.com/docs/user-event/intro |
| 14 | +[@testing-library/jest-dom]: https://github.com/testing-library/jest-dom |
| 15 | + |
| 16 | +## Table of contents |
| 17 | + |
| 18 | +- [`basic.svelte`](#basicsvelte) |
| 19 | +- [`basic.test.js`](#basictestjs) |
| 20 | + |
| 21 | +## `basic.svelte` |
| 22 | + |
| 23 | +```svelte file=./basic.svelte |
| 24 | +<script> |
| 25 | + let { name } = $props() |
| 26 | + |
| 27 | + let showGreeting = $state(false) |
| 28 | + |
| 29 | + const onclick = () => (showGreeting = true) |
| 30 | +</script> |
| 31 | + |
| 32 | +<button {onclick}>Greet</button> |
| 33 | + |
| 34 | +{#if showGreeting} |
| 35 | + <p>Hello {name}</p> |
| 36 | +{/if} |
| 37 | +``` |
| 38 | + |
| 39 | +## `basic.test.js` |
| 40 | + |
| 41 | +```js file=./basic.test.js |
| 42 | +import { render, screen } from '@testing-library/svelte' |
| 43 | +import { userEvent } from '@testing-library/user-event' |
| 44 | +import { expect, test } from 'vitest' |
| 45 | + |
| 46 | +import Subject from './basic.svelte' |
| 47 | + |
| 48 | +test('no initial greeting', () => { |
| 49 | + render(Subject, { name: 'World' }) |
| 50 | + |
| 51 | + const button = screen.getByRole('button', { name: 'Greet' }) |
| 52 | + const greeting = screen.queryByText(/hello/iu) |
| 53 | + |
| 54 | + expect(button).toBeInTheDocument() |
| 55 | + expect(greeting).not.toBeInTheDocument() |
| 56 | +}) |
| 57 | + |
| 58 | +test('greeting appears on click', async () => { |
| 59 | + const user = userEvent.setup() |
| 60 | + render(Subject, { name: 'World' }) |
| 61 | + |
| 62 | + const button = screen.getByRole('button') |
| 63 | + await user.click(button) |
| 64 | + const greeting = screen.getByText(/hello world/iu) |
| 65 | + |
| 66 | + expect(greeting).toBeInTheDocument() |
| 67 | +}) |
| 68 | +``` |
0 commit comments