Search code examples
svelte-5

How to unittest Runes?


I have a typescript library that contains svelte 5 runes. I want to test if reactivity is working but for some reasons runes are not working.

I modified vite.config.ts to accept unittests with the svelte compiler:

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
    plugins: [sveltekit()],
    test: {
        include: ['tests/**/*.test.svelte.{js,ts}'],
        restoreMocks: true,
    },
});

Then I create a X.test.svelte.ts:

test('Counter', () => {
    let count = $state(0);
    let double = $derived(count * 2);

    count = 5;

    expect(double).toEqual(10);
});

But the expect tells me that double is 0 instead of 10. Any hint how to make the file reactive?


Solution

  • By default SSR code is generated which is non-reactive.

    You need to set the environment to e.g. jsdom to test client-side code.

    This can either be done in the config or on a per-file basis using a comment like this at the top:

    // @vitest-environment jsdom
    

    (Environments like jsdom require the respective package, though Vitest should even tell you that.)