Skip to content

Virtual module mocking issue in Vitest 4 #9742

@HiDeoo

Description

@HiDeoo

Describe the bug

This discussion is a follow-up to this discussion that I initially opened before this issue._

In a test file, I have different describe blocks where in each of them, I mock a virtual module, e.g. using vi.doMock() and mock a function from that virtual module making it return different values.

The behavior seems to be different between Vitest 3 and Vitest 4:

  • Vitest 3: everything seems to work as expected, and calling some code that uses that virtual module returns the mocked value.
  • Vitest 4: the first mocked value seems to be returned for all tests.

Reproduction

I've setup a minimal repro available here: https://github.com/HiDeoo/vitest-4-mock-repro

  1. Clone the repository
  2. Run pnpm install
  3. Run pnpm test

Some tests that are checking that the expected returned mocked value is correct will fail.

A few extra notes:

  • Running pnpm add vitest@3 and pnpm test will make the test pass
  • I tried swapping the order of vi.resetModules() and vi.doMock() as suggested but this didn't change the behavior

System Info

System:
    OS: macOS 26.3
    CPU: (8) arm64 Apple M1
    Memory: 197.14 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.14.0 - /Users/hideoo/.local/state/fnm_multishells/36543_1772008897917/bin/node
    npm: 10.9.2 - /Users/hideoo/.local/state/fnm_multishells/36543_1772008897917/bin/npm
    pnpm: 9.15.9 - /Users/hideoo/.local/state/fnm_multishells/36543_1772008897917/bin/pnpm
    bun: 1.3.9 - /opt/homebrew/bin/bun
  Browsers:
    Firefox: 147.0.4
    Safari: 26.3
  npmPackages:
    vitest: ^4.0.18 => 4.0.18

Used Package Manager

pnpm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p3-minor-bugAn edge case that only affects very specific usage (priority)

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions