-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Closed
Description
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?
Activity
[-]`$effect` not working in tests[/-][+]`$effect` not working in tests, but `$derived` does[/+]7nik commentedon Jan 18, 2025
It means nothing -
$derived
works for both client and server, though it isn't reactive on the server.Did you read the docs about testing?
rChaoz commentedon Jan 18, 2025
Yes, that's what I meant. Isn't it reactive in my example above?
paoloricciuti commentedon Jan 18, 2025
This could be fixed by #14977 but I think you should change your resolve conditions to
browser
if you also want to test$effect
rChaoz commentedon Jan 18, 2025
I don't need that, as I mentioned it is reactive for me.
I tried doing that, but I'm getting blasted with various errors, like
also, this makes every server test to fail.
paoloricciuti commentedon Jan 18, 2025
Do you have other tests other than those? You need to run the svelte ones with condition browser and the others with condition node...take a look at this repo
https://github.com/dominikg/vitest-example-svelte5
rChaoz commentedon Jan 18, 2025
I will take a look at that repo, although not sure if it will help, running just a single file with the test in my original post fails with the errors I mentioned. Also, I managed to get the transformed module, which looks good I think:
Update: actually, I think I figured it out. Looking at the top of the generated module, I see this:
so, runes are transformed correctly, but
flushSync()
is imported from the server module, which is actually a no-op. I'll keep looking into this.rChaoz commentedon Jan 19, 2025
After upgrading to Vitest 3, I finally managed to get this working, using the example repo from above, with the workspace config.