javascript / expert
Snippet
Synchronizing Svelte 5 Effect Runes in Automated Unit Tests
In Svelte 5, state mutations trigger reactivity batching where `$effect` runes execute asynchronously within microtasks. In unit tests, assertions made immediately after mutating reactive state will fail unless synchronized using Svelte's `tick()` function, which flushes pending DOM and effect queues.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { tick } from 'svelte';import { expect, test } from 'vitest';import { render } from '@testing-library/svelte';import EffectComponent from './EffectComponent.svelte';test('flushes $effect state mutations asynchronously before DOM assertions', async () => {const { getByTestId } = render(EffectComponent, { props: { initialCount: 0 } });const displayEl = getByTestId('counter-display');expect(displayEl.textContent).toBe('Count: 0');const incrementBtn = getByTestId('increment-btn');incrementBtn.click();await tick();expect(displayEl.textContent).toBe('Count: 1');});
svelte
Breakdown
1
import { tick } from 'svelte';
Imports Svelte's core utility that returns a Promise resolving once pending state updates are applied.
2
incrementBtn.click();
Triggers a state modification that schedules reactive $effect updates asynchronously.
3
await tick();
Pauses test execution until Svelte flushes pending DOM mutations and rune effects to completion.
4
expect(displayEl.textContent).toBe('Count: 1');
Asserts the DOM text content after reactive effect batching has fully synchronized.