Skip to content

Module crashes in Vitest with nuxt environment test suites #335

@janhoogeveen

Description

@janhoogeveen

Version

@nuxtjs/color-mode: v4.0.0
nuxt: v4.2.1

Reproduction Link

Relevant files are:

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:

  1. 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
  1. 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) {

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions