Skip to content

$effect not working in tests, but $derived does #15051

Closed
@rChaoz

Description

@rChaoz

Describe the bug

I'm having this weird issue where $effect is not working in tests. Interestingly, $derived does work, which means Svelte is not compiling in SSR mode. For example, in this test:

let num = $state(0)
let doubled = $derived(num * 2)
num = 5
expect(doubled).toBe(10)

$effect.root(() => {
    let a = 0
    $effect(() => {
        a = 5
    })
    flushSync()
    expect(a).toBe(5)
})

it errors at the very end: expected +0 to be 5, but it should work. Here's my Vite config:

export default defineConfig({
    plugins: [
        enhancedImages(),
        sveltekit(),
        ...
    ],
    test: {
        include: ["src/**/*.test.{js,ts}"],
        coverage: { ... },
        environmentMatchGlobs: [["src/**/*.svelte.test.{js,ts}", "jsdom"]],
        setupFiles: "src/vitest.setup.ts",
    },
    build: { ... },
})

I also have this mock in my global setup as I use if (browser) in other places in my tests:

vi.mock(import("esm-env"), async (importOriginal): Promise<typeof import("esm-env")> => {
    const module = await importOriginal()
    if (typeof window == "object")
        return {
            ...module,
            BROWSER: true,
        }
    else return module
})

I tried removing it, but without success. I'm not quite sure how to reproduce this yet. Is there something obviously wrong with my config, or something I can try?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions