diff --git a/documentation/docs/07-misc/02-testing.md b/documentation/docs/07-misc/02-testing.md index c1bc69c1c2..0ad82a19b5 100644 --- a/documentation/docs/07-misc/02-testing.md +++ b/documentation/docs/07-misc/02-testing.md @@ -38,6 +38,21 @@ You can now write unit tests for code inside your `.js/.ts` files: ```js /// file: multiplier.svelte.test.js +// @filename: multiplier.svelte.ts +export function multiplier(initial: number, k: number) { + let count = $state(initial); + + return { + get value() { + return count * k; + }, + set: (c: number) => { + count = c; + } + }; +} +// @filename: multiplier.svelte.test.js +// ---cut--- import { flushSync } from 'svelte'; import { expect, test } from 'vitest'; import { multiplier } from './multiplier.svelte.js'; @@ -80,6 +95,16 @@ Since Vitest processes your test files the same way as your source files, you ca ```js /// file: multiplier.svelte.test.js +// @filename: multiplier.svelte.ts +export function multiplier(getCount: () => number, k: number) { + return { + get value() { + return getCount() * k; + } + }; +} +// @filename: multiplier.svelte.test.js +// ---cut--- import { flushSync } from 'svelte'; import { expect, test } from 'vitest'; import { multiplier } from './multiplier.svelte.js'; @@ -115,6 +140,10 @@ If the code being tested uses effects, you need to wrap the test inside `$effect ```js /// file: logger.svelte.test.js +// @filename: logger.svelte.ts +export function logger(fn: () => void) {} +// @filename: logger.svelte.test.js +// ---cut--- import { flushSync } from 'svelte'; import { expect, test } from 'vitest'; import { logger } from './logger.svelte.js'; @@ -213,7 +242,7 @@ test('Component', () => { expect(document.body.innerHTML).toBe(''); // Click the button, then flush the changes so you can synchronously write expectations - document.body.querySelector('button').click(); + document.body.querySelector('button')?.click(); flushSync(); expect(document.body.innerHTML).toBe(''); @@ -226,6 +255,7 @@ test('Component', () => { While the process is very straightforward, it is also low level and somewhat brittle, as the precise structure of your component may change frequently. Tools like [@testing-library/svelte](https://testing-library.com/docs/svelte-testing-library/intro/) can help streamline your tests. The above test could be rewritten like this: ```js +// @errors: 2339 /// file: component.test.js import { render, screen } from '@testing-library/svelte'; import userEvent from '@testing-library/user-event'; @@ -270,9 +300,9 @@ You can create stories for component variations and test interactions with the [ } }); - + - + {