Skip to content

vitest@4: Non-deterministic module mocking behavior #8815

@evan-sift

Description

@evan-sift

Describe the bug

I've been upgrading a sizable TS codebase (~400 test files, ~4000 test cases) to vite 7 and vitest 4. I'm nearly done, but a very strange problem that I am running into is that I sometimes get this following error:

Error: [vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock
...
Caused by: Error: Module "/path/to/internal/fileModule.ts" was mistakenly invalidated during fetch phase.

This is happening with 2 different reusable component files (let's just call them fileModule.ts), and in a non-deterministic set of test files (which import and test functions that themselves import the problematic invalidated module files).

In some cases, I am mocking the internals of fileModule.ts with a factory vi.mock, spreading the results of importOriginal. And I also have actual test files that test the contents of fileModule.ts

Digging in, it seems to possibly be related to vite's module caching (https://github.com/vitejs/vite/blob/bb85bd751e4568c707612b708deaba67f8af4ca3/packages/vite/src/module-runner/runner.ts#L293).

I've tried a number of things, including messing with the vitest config settings, vite config settings, vi.hoisted on some of the mocked functions.

~50% of the time, running the test suite passes all tests. ~50% of the time there are >1 of these mistakenly invalidated during fetch phase errors (often 1 or 2, sometimes up to 4).

We never experienced these issues in vitest@3

I thought that this could be some sort of race condition, but I also tried using maxWorkers: 1 and the problem was still present.

Any ideas what might be going on here?

Reproduction

unknown

System Info

System:
    OS: macOS 15.6.1
    CPU: (14) arm64 Apple M3 Max
    Memory: 479.00 MB / 36.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.14.0 - /Users/username/.nvm/versions/node/v22.14.0/bin/node
    Yarn: 1.22.21 - /usr/local/bin/yarn
    npm: 10.9.2 - /Users/username/.nvm/versions/node/v22.14.0/bin/npm
  Browsers:
    Chrome: 141.0.7390.123
    Edge: 141.0.3537.99
    Firefox: 143.0.4
    Safari: 18.6
  npmPackages:
    @vitejs/plugin-react: 5.0.4 => 5.0.4
    @vitest/coverage-v8: 4.0.3 => 4.0.3
    @vitest/web-worker: 4.0.3 => 4.0.3
    vite: 7.1.12 => 7.1.12
    vitest: 4.0.3 => 4.0.3
    vitest-canvas-mock: 0.3.3 => 0.3.3
    vitest-fetch-mock: 0.4.5 => 0.4.5

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions