跳至主要内容

示例

有关测试 Svelte 组件和其他 Svelte 功能的更多资源、模式和最佳实践,请查看 Svelte Society 测试食谱

基础

这个基本示例演示了如何

greeter.svelte
<script>
export let name

let showGreeting = false

const handleClick = () => (showGreeting = true)
</script>

<button on:click="{handleClick}">Greet</button>

{#if showGreeting}
<p>Hello {name}</p>
{/if}
greeter.test.js
import {render, screen} from '@testing-library/svelte'
import userEvent from '@testing-library/user-event'
import {expect, test} from 'vitest'

import Greeter from './greeter.svelte'

test('no initial greeting', () => {
render(Greeter, {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(Greeter, {name: 'World'})

const button = screen.getByRole('button')
await user.click(button)
const greeting = screen.getByText(/hello world/iu)

expect(greeting).toBeInTheDocument()
})

事件

可以使用间谍函数测试事件。如果您使用的是 Vitest,您可以使用 vi.fn() 创建一个间谍。

info

考虑使用函数道具来简化事件测试。

button-with-event.svelte
<button on:click>click me</button>
button-with-prop.svelte
<script>
export let onClick
</script>

<button on:click="{onClick}">click me</button>
button.test.ts
import {render, screen} from '@testing-library/svelte'
import userEvent from '@testing-library/user-event'
import {expect, test, vi} from 'vitest'

import ButtonWithEvent from './button-with-event.svelte'
import ButtonWithProp from './button-with-prop.svelte'

test('button with event', async () => {
const user = userEvent.setup()
const onClick = vi.fn()

const {component} = render(ButtonWithEvent)
component.$on('click', onClick)

const button = screen.getByRole('button')
await user.click(button)

expect(onClick).toHaveBeenCalledOnce()
})

test('button with function prop', async () => {
const user = userEvent.setup()
const onClick = vi.fn()

render(ButtonWithProp, {onClick})

const button = screen.getByRole('button')
await user.click(button)

expect(onClick).toHaveBeenCalledOnce()
})

插槽

插槽无法直接测试。通常更容易构建代码,以便您可以测试面向用户的結果,并将任何插槽作为实现细节保留。

但是,如果插槽是组件的重要面向开发人员的 API,则可以使用包装组件和“虚拟”子项来测试它们。在这种情况下,测试 ID 在测试插槽时很有用。

heading.svelte
<h1>
<slot />
</h1>
heading.test.svelte
<script>
import Heading from './heading.svelte'
</script>

<Heading>
<span data-testid="child" />
</Heading>
heading.test.js
import {render, screen, within} from '@testing-library/svelte'
import {expect, test} from 'vitest'

import HeadingTest from './heading.test.svelte'

test('heading with slot', () => {
render(HeadingTest)

const heading = screen.getByRole('heading')
const child = within(heading).getByTestId('child')

expect(child).toBeInTheDocument()
})

双向数据绑定

双向数据绑定无法直接测试。通常更容易构建代码,以便您可以测试面向用户的結果,并将绑定作为实现细节保留。

但是,如果双向绑定是组件的重要面向开发人员的 API,则可以使用包装组件和可写入存储来测试绑定本身。

text-input.svelte
<script>
export let value = ''
</script>

<input type="text" bind:value="{value}" />
text-input.test.svelte
<script>
import TextInput from './text-input.svelte'

export let valueStore
</script>

<TextInput bind:value="{$valueStore}" />
text-input.test.js
import {render, screen} from '@testing-library/svelte'
import userEvent from '@testing-library/user-event'
import {get, writable} from 'svelte/store'
import {expect, test} from 'vitest'

import TextInputTest from './text-input.test.svelte'

test('text input with value binding', async () => {
const user = userEvent.setup()
const valueStore = writable('')

render(TextInputTest, {valueStore})

const input = screen.getByRole('textbox')
await user.type(input, 'hello world')

expect(get(valueStore)).toBe('hello world')
})

上下文

如果您的组件需要访问上下文,您可以在 render 组件时传入这些上下文。当您使用 context 等选项时,请确保将道具放在 props 键下。

notifications-provider.svelte
<script>
import {setContext} from 'svelte'
import {writable} from 'svelte/stores'

setContext('messages', writable([]))
</script>
notifications.svelte
<script>
import {getContext} from 'svelte'

export let label

const messages = getContext('messages')
</script>

<div role="status" aria-label="{label}">
{#each $messages as message (message.id)}
<p>{message.text}</p>
<hr />
{/each}
</div>
notifications.test.js
import {render, screen} from '@testing-library/svelte'
import {readable} from 'svelte/store'
import {expect, test} from 'vitest'

import Notifications from './notifications.svelte'

test('notifications with messages from context', async () => {
const messages = readable([
{id: 'abc', text: 'hello'},
{id: 'def', text: 'world'},
])

render(Notifications, {
context: new Map([['messages', messages]]),
props: {label: 'Notifications'},
})

const status = screen.getByRole('status', {name: 'Notifications'})

expect(status).toHaveTextContent('hello world')
})