As of Svelte 5.36+, you can use the `await` keyword directly inside component expressions in three places: at the top level of the component's `<script>`, inside `$derived(...)` declarations, and inside your markup. This enables cleaner code without needing explicit promise handling.
✅ **Use this pattern:**
```ts
<scriptlang="ts">
async function fetchData(): Promise<Data> {
// async logic here
return data;
}
let data = $derived(await fetchData());
</script>
<p>Data: {data}</p>
```
🚫 **Instead of:**
```ts
<scriptlang="ts">
async function fetchData(): Promise<Data> {
// async logic here
return data;
}
// Without await, this produces a Promise
let dataPromise = $derived(fetchData());
</script>
{#await dataPromise}
<p>Loading...</p>
{:then data}
<p>Data: {data}</p>
{:catch error}
<p>Error: {error.message}</p>
{/await}
```
This is much simpler than managing promises manually and avoids the need for `{#await}` blocks when you just need the final value.
For more details on async patterns in Svelte, see the [Svelte documentation on await expressions](https://svelte.dev/docs/svelte/await-expressions).
### Mock complete modules, spy on parts of module for specific tests
When testing a module, you have to decide for each imported module if you mock the entire module or if you spy on specific functions of the module
for specific tests and keep the real implementation for the other functions.
System modules (`node:fs`, etc) are most generally mocked, so you are sure that unit tests are executed in isolation of the system. For internal modules,
it's up to you to decide if you want to mock them or not, depending on the coverage you want for the unit tests.
#### Mock a complete module
Mock completely an imported module with `vi.mock('/path/to/module)`, and define mock implementation for each test with `vi.mocked(function).mock...()`.
Use `vi.resetAllMocks()` in the top-level `beforeEach` to reset all mocks to a no-op function returning `undefined` before to start each test.
```ts
import { existsSync } from 'node:fs';
import { beforeEach, describe, expect, test, vi } from 'vitest';
// completely mock the fs module, to be sure to
// run the tests in complete isolation from the filesystem
When you want to mock only one or a small number of functions of a module (for example a function of the module you are testing, or a function of an helper module from which you want to use real implementation for some functions) for a particular test, you can use `vi.spyOn(module, 'function')` to mock only `function` and keep the original implementation for the rest of the module.
To be sure that the spied function is restored to its original implementation for the other tests, use `vi.restoreAllMocks()` in the top-level `beforeEach`.
```ts
// helpers.ts
export function f1(): boolean {
return true;
}
// mymodule.ts
import { f1 } from './helpers.js';
export class MyModuleToTest {
f2(): boolean {
return f1();
}
}
// mymodule.spec.ts
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { MyModuleToTest } from './mymodule.js';
import * as helpers from './helpers.js';
let myModuleToTest: MyModuleToTest;
beforeEach(() => {
myModuleToTest = new MyModuleToTest();
// restore f1 to its original implementation
vi.restoreAllMocks();
});
describe('f1 returns false', () => {
beforeEach(() => {
vi.spyOn(helpers, 'f1').mockReturnValue(false);
});
test('f2 returns false', () => {
expect(myModuleToTest.f2()).toBeFalsy();
expect(helpers.f1).toHaveBeenCalledOnce();
});
});
test('f2 returns true', () => {
// use the original implementation of f1
expect(myModuleToTest.f2()).toBeTruthy();
// this won't work, as f1 is not spied for this test
When we need to ensure a given style is applied to an HTMLElement, we should be using [tohavestyle](https://github.com/testing-library/jest-dom?tab=readme-ov-file#tohavestyle)
Use `waitFor` (https://vitest.dev/api/vi.html#vi-waitfor) to retry an assertion until it passes, and `waitUntil` (https://vitest.dev/api/vi.html#vi-waituntil) to wait for a function to return a truthy value.
When testing Svelte components in the `packages/renderer` package, **always enable automatic time advancement** by using:
```ts
vi.useFakeTimers({ shouldAdvanceTime: true });
```
Avoid calling `vi.useFakeTimers()` without options.
If `shouldAdvanceTime` is not enabled, fake timers will **completely freeze time**, which can lead to deadlocks when:
- Svelte’s internal async updates wait for the next event loop tick
- Testing Library’s async queries (`findBy*`, `waitFor`) continuously poll for elements
By setting `shouldAdvanceTime: true`, timers will automatically advance during pending async operations. This prevents hangs while still allowing manual time control with `vi.advanceTimersByTime()`.
Vitest snapshots are a powerful tool to ensure UI components and complex data structures do not change unexpectedly. They are particularly effective for catching regressions in rendered HTML or large objects without writing manual assertions for every property. When a snapshot detects a diff, you can update it using the `-u` param:
#### Updating Snapshots
When a test fails due to an intentional change, you can update the stored snapshots by appending the `-u` (or `--update`) flag to your test command.
#### 1. Standard Snapshots (External Files)
Use standard snapshots for large outputs like rendered HTML. These are stored in a separate **snapshots** directory.
##### Example: Testing Rendered HTML
```ts
test('multiple container connection should display a dropdown', async () => {
Inline snapshots are preferred for small data structures. They are written directly back into your test file, making the expected output easier to review during code sessions.
#### Example: Testing an Object
```ts
test('should parse targets with some special characters', async () => {
const info = await containerFileParser.parseContent(`
FROM busybox as base
ARG TARGETPLATFORM
RUN echo $TARGETPLATFORM > /plt
FROM --platform=\${TARGETPLATFORM} base AS base-target
**Result:** Vitest replaces the code in your .spec.ts file with the updated values:
```ts
expect(info).toMatchInlineSnapshot(`
{
"targets": [
"base",
"base-build",
],
}
`);
```
**Best Practices**
- **Review Before Committing:** Always inspect the diff of a snapshot update. It is easy to accidentally "fix" a test by updating a snapshot that actually contains a bug.
- **Keep Snapshots Focused:** Avoid snapshotting entire massive objects if you only care about one or two fields; use specific assertions instead to keep tests readable.
- **Use Inline for Small Data:** If the snapshot is less than 10 lines, prefer `toMatchInlineSnapshot()` for better visibility.
For more details, see the [Vitest snapshot guide](https://vitest.dev/guide/snapshot.html).