sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
79.85k stars 4.24k forks source link

Effects in unit tests don't run #14239

Open DanielSidhion opened 3 days ago

DanielSidhion commented 3 days ago

Describe the bug

It seems that code inside an $effect.root() in unit tests doesn't run. I'm following the instructions on the docs to set up vitest and a simple test case, but no matter what I tried, the code inside $effect.root() doesn't run at all in the test.

Depending on how the test is set up (e.g. all the assertions are made in code inside $effect.root(), which is also what the example in the docs does), vitest reports the test as successful, but that's because no code ran at all. This is misleading.

This issue was also observed by someone else on the discord server, but no resolution was found yet over there.

Reproduction

https://www.sveltelab.dev/dnfqrcdar7xg6qw?files=.%2Fsrc%2Flib%2Feffect_test.svelte.test.ts

Please stop the dev server on sveltelab's console and run the test:unit npm script instead.

Logs

No response

System Info

System:
    OS: Linux 6.10 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Container: Yes
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.8.0 - /nix/store/xsrv93rg8vi05k9ig6v9mcvcyn01n6n2-nodejs-22.8.0/bin/node
    npm: 10.8.2 - /nix/store/xsrv93rg8vi05k9ig6v9mcvcyn01n6n2-nodejs-22.8.0/bin/npm
  Browsers:
    Chromium: 130.0.6723.69
  npmPackages:
    svelte: ^5.1.9 => 5.1.9

Severity

blocking all usage of svelte

abdel-17 commented 3 days ago

use environment: jsdom in your Vitest config

DanielSidhion commented 2 days ago

use environment: jsdom in your Vitest config

Thank you, this is what was missing. Just opened a PR to improve the docs and clarify this for other folks.

dominikg commented 2 days ago

enabling jsdom for all tests is not the right way either.

instead you need to split your tests into 2 different configs. not entirely intuitive at first you can do it with vitest workspaces, here is an example that does it in the kit demo app

https://github.com/dominikg/vitest-example-svelte5/blob/main/vitest.workspace.ts

(note the filename and how it uses defineWorkspace + extends vite.config)