vitest: ReferenceError: Cannot access '__vite_ssr_import_0__' before initialization when using mocks

Describe the bug

I get the ReferenceError: Cannot access '__vite_ssr_import_0__' before initialization when i try to use the API vi.mock.

Reproduction

This is a failing workflow: https://github.com/gdorsi/vite-mock-error-repro/runs/5804962645?check_suite_focus=true

This is the test file: https://github.com/gdorsi/vite-mock-error-repro/blob/redaxios/frontend/src/components/LoginForm/LoginForm.test.jsx

This is the repro: https://github.com/gdorsi/vite-mock-error-repro

System Info

System:
    OS: macOS 11.6
    CPU: (8) arm64 Apple M1
    Memory: 186.25 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.13.1 - ~/.volta/tools/image/node/16.13.1/bin/node
    Yarn: 3.1.1 - ~/.volta/tools/image/yarn/1.22.17/bin/yarn
    npm: 8.1.2 - ~/.volta/tools/image/node/16.13.1/bin/npm
  Browsers:
    Chrome: 100.0.4896.60
    Firefox: 98.0.2
    Safari: 14.1.2
  npmPackages:
    @vitejs/plugin-react: ^1.3.0 => 1.3.0 
    vite: ^2.9.1 => 2.9.1 
    vitest: ^0.8.2 => 0.8.2

Used Package Manager

yarn

Validations

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 4
  • Comments: 16 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Vitest is hoisting vi.mock to top of the file, so it doesn’t have access to imported variables. We usually bypass it by also hoisting imports from vitest, but you moved it to another file.

So there are several workarounds to this:

  • import vi from vitest
  • enable globals options
  • use vi.doMock (it doesn’t get hoisted), but you would need to move it before mocked import:
import { render, screen, expect, describe, it, vi, userEvent, waitFor } from '../../test-utils'
vi.doMock('redaxios')
import LoginForm from './LoginForm' // LoginForm also uses `axios`
import axios from 'redaxios'

No, I don’t think it’s safe to hoist other “potential” imports. I think the current solution works as expected.

Maybe better error message would be preferable

@dudintv Looking at the posted files seems that you are not importing vi in mediaImage.spec.ts

Correct, I use global “vi” in spec files

There is a bug actually, the fix I did should provide a user friendly error but it isn’t catching your case.

Could you share more code about how you are using vi.mock?

The general advice to fix this issue is either:

  • switch to the vitest globals
  • when using vi.mock import vi directly from vitest