Open charlie-map opened 1 year ago
I'm also having issues importing modules that import from '$app/environment' my errors is a bit different though:
Error: Cannot find package '__sveltekit' imported from C:\dev\DefaultTemplates\sveltekit\node_modules\.pnpm\@sveltejs+kit@1.24.1_svelte@4.2.0_vite@4.4.9\node_modules\@sveltejs\kit\src\runtime\app\environment.js
not sure if this is related.
@hahn-kev What version of vitest are you using?
@hahn-kev What version of vitest are you using?
0.34.3 looks like that's my issue, thanks! I'll just roll back for now.
Our first time using a dynamic env var in a test is also not going well. We have the exact same "Cannot read properties of undefined (reading 'env')" as above.
looks like this recent change broke the fallback and expects the global to be set always, which isn't the case in vitest env
leading to
TypeError: Cannot read properties of undefined (reading 'env')
❯ virtual:$env/dynamic/public:1:40
update: the fallback also uses the global env, so either browser would have to be false OR the globalThis.__sveltekit_dev.env needs to be initialized somehow.
workaround to stub it via vitest, use vites own tooling to load an env config and supply the public prefixes to globalThis.__sveltekit_dev.
Note that this is a workaround, and the code requires node 20.11 for import.meta.dirname
import { loadEnv } from 'vite';
// stub sveltekit client global env to avoid tests failing on import of $env/dynamic/public
vi.stubGlobal('__sveltekit_dev', { env: loadEnv('test', import.meta.dirname, 'PUBLIC_') });
put it in a global vitest setup file that is in the root of your app, alongside .env.test where you can set the needed values.
Might be a problem with the test environment - I had the problem with the jsdom
environment, but switching to the node
environment solved the issue. For example, adding this to the start of the test file:
// @vitest-environment node
Describe the bug
Attempted import:
Error during Vitest (
npm run test
):Another note: the carrot symbol (
^
) is confusingly placed one line above the error. For instance, switching the order to:causes the following error during
npm run test
:Reproduction
There are notes in the README for setup: https://github.com/charlie-map/sveltekit-vitest-issue
Logs
No response
System Info
Severity
serious, but I can work around it
Additional Information
No response