Unexpected behavior when in-source tests utilize vi.mock
without globals
#6829
Labels
p3-minor-bug
An edge case that only affects very specific usage (priority)
Description
In our project, we utilize in-source testing with Vitest and have disabled the globals option. This setup requires us to import vi at the top level to use mocks, while other test methods (e.g., it, expect) are imported from import.meta.vitest within each test block. However, importing vi at the top level introduces issues in production: it breaks the code by including test dependencies in the main application bundle, which should not reference any testing libraries outside of test contexts.
Ideally, vi should also be accessible directly from import.meta.vitest, allowing us to keep all testing-related imports consistent and limited to the test context. This would prevent production issues caused by top-level test imports while keeping the code cleaner and better scoped.
Error Stacktrace
Attempting to import vi from import.meta.vitest triggers the following error:
While importing vi directly from vitest at the top level resolves this error for testing purposes, it causes production errors when serving the web app:
Expected Behavior
The ideal solution would be to access vi directly from import.meta.vitest, alongside it and expect, so that all testing imports are consistent and scoped within the test context. This would eliminate the need for top-level imports solely for mocking, preventing test dependencies from affecting production code. Here’s the desired structure:
Relevant Code in Vitest
After some investigation, it seems that this part of Vitest’s codebase might be related, as it appears to control how mocks are hoisted.
Reproduction
https://github.com/deen13/vitest-vi-meta-import
System Info
Used Package Manager
npm
Validations
The text was updated successfully, but these errors were encountered: