Module crashes in Vitest with nuxt environment test suites
Version
@nuxtjs/color-mode: v4.0.0 nuxt: v4.2.1
Reproduction Link
- https://github.com/janhoogeveen/color-mode
Relevant files are:
- https://github.com/janhoogeveen/color-mode/blob/main/test/nuxt/app.nuxt.spec.ts
- https://github.com/janhoogeveen/color-mode/blob/main/src/runtime/plugin.client.ts
Steps to reproduce
I've previously submitted a patch to address the access of unknown properties. It seems the patch as-merged does not work as intended.
The only way to reproduce this accordingly is to write a test suite that uses the Nuxt environment to run a test. E.g. write a test that renders the ColorModePicker component from the playground in a nuxt environment in Vitest.
This will trigger an error.
TypeError: Cannot read properties of undefined (reading 'preference')
❯ playground/components/ColorModePicker.vue:16:85
What is Expected?
I expect the colorModule return values to always be defined. OR, be typed truthfully and indicate some values might be undefined.
What is actually happening?
When running in Vitest nuxt environment, I suspect window is not defined and as such helper is not defined either. The current solution does not stub the module correctly.
I see multiple reasons:
- The type declaration of the Helper is untruthful.
The following snippet tells TypeScript that helper will always be of type Helper. This is false.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let helper = window[globalName as any] as unknown as Helper
- Conditional stubbing not firing correctly
For some reason, the following snippet will not evaluate as truthy in a nuxt vitest environment. I think because it needs to be
import.meta.TEST.
if (import.meta.test && !helper) {
any updates on this ? i can't run tests at all