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
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that reports the same bug to avoid creating a duplicate.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 4
- Comments: 16 (8 by maintainers)
Commits related to this issue
- Downgrade ChakraUI to 2.3.4 due to issue with Vite/Vitest - Related issue: https://github.com/vitest-dev/vitest/issues/1084 — committed to MartinSvarrer/time-logger by MartinSvarrer 2 years ago
Vitest is hoisting
vi.mockto top of the file, so it doesn’t have access to imported variables. We usually bypass it by also hoisting imports fromvitest, but you moved it to another file.So there are several workarounds to this:
vifromvitestglobalsoptionsvi.doMock(it doesn’t get hoisted), but you would need to move it before mocked import: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
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: