Testing Svelte 5 Runes and reactive state
mainWhen testing Svelte 5 reactive state (runes), you can pass $state objects as props to the render function.
Handling $derived runes and avoiding warnings
When accessing $derived values directly in test files, you may encounter state_referenced_locally warnings. To resolve this, use the untrack function from svelte. This allows you to assert on derived values without creating unwanted reactive dependencies in the test environment.
When to use untrack:
- Accessing
$derivedvalues in test assertions. - Testing reactive logic that uses
$derived.by()functions. - Any time you encounter
state_referenced_locallywarnings.
When to use flushSync():
While locators automatically retry for DOM updates, you still need flushSync() when:
- Testing synchronous code paths.
- Testing non-DOM state (reactive state that doesn't immediately affect the DOM).
- Testing complex derived state that requires immediate evaluation before an assertion.
import { flushSync, untrack } from 'svelte';
test('derived state logic', async () => {
let scrollState = $state({
current: 0,
previous: 0,
});
let shouldShowButton = $derived(
scrollState.current > scrollState.previous &&
scrollState.current > 0,
);
// Use untrack to access derived values without warnings
expect(untrack(() => shouldShowButton)).toBe(false);
scrollState.previous = scrollState.current;
scrollState.current = 100;
flushSync();
expect(untrack(() => shouldShowButton)).toBe(true);
});