docs: add code of files being tested (#14925)

* docs: add code of files being tested

closes #14900

* fix

* Apply suggestions from code review

Co-authored-by: Rich Harris <rich.harris@vercel.com>

* Update documentation/docs/07-misc/02-testing.md

Co-authored-by: Rich Harris <rich.harris@vercel.com>

* Apply suggestions from code review

Co-authored-by: Rich Harris <rich.harris@vercel.com>

* rename import

* from https://github.com/sveltejs/svelte.dev/pull/1094

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
pull/14936/head
Simon H 4 days ago committed by GitHub
parent 77378688b9
commit a1f371e786
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -44,12 +44,7 @@ todos[0].done = !todos[0].done;
If you push a new object to the array, it will also be proxified:
```js
// @filename: ambient.d.ts
declare global {
const todos: Array<{ done: boolean, text: string }>
}
// @filename: index.js
let todos = [{ done: false, text: 'add more todos' }];
// ---cut---
todos.push({
done: false,

@ -40,7 +40,7 @@ You can now write unit tests for code inside your `.js/.ts` files:
/// file: multiplier.svelte.test.js
import { flushSync } from 'svelte';
import { expect, test } from 'vitest';
import { multiplier } from './multiplier.js';
import { multiplier } from './multiplier.svelte.js';
test('Multiplier', () => {
let double = multiplier(0, 2);
@ -53,9 +53,30 @@ test('Multiplier', () => {
});
```
```js
/// file: multiplier.svelte.js
/**
* @param {number} initial
* @param {number} k
*/
export function multiplier(initial, k) {
let count = $state(initial);
return {
get value() {
return count * k;
},
/** @param {number} c */
set: (c) => {
count = c;
}
};
}
```
### Using runes inside your test files
It is possible to use runes inside your test files. First ensure your bundler knows to route the file through the Svelte compiler before running the test by adding `.svelte` to the filename (e.g `multiplier.svelte.test.js`). After that, you can use runes inside your tests.
Since Vitest processes your test files the same way as your source files, you can use runes inside your tests as long as the filename includes `.svelte`:
```js
/// file: multiplier.svelte.test.js
@ -75,6 +96,21 @@ test('Multiplier', () => {
});
```
```js
/// file: multiplier.svelte.js
/**
* @param {() => number} getCount
* @param {number} k
*/
export function multiplier(getCount, k) {
return {
get value() {
return getCount() * k;
}
};
}
```
If the code being tested uses effects, you need to wrap the test inside `$effect.root`:
```js
@ -105,6 +141,27 @@ test('Effect', () => {
});
```
```js
/// file: logger.svelte.js
/**
* @param {() => any} getValue
*/
export function logger(getValue) {
/** @type {any[]} */
let log = $state([]);
$effect(() => {
log.push(getValue());
});
return {
get value() {
return log;
}
};
}
```
### Component testing
It is possible to test your components in isolation using Vitest.

Loading…
Cancel
Save