Skip to content

vi.mock with spy: true stops working in Vitest 4 #9558

@patrickshipe

Description

@patrickshipe

Describe the bug

Vitest provides the { spy: true } option when using vi.mock. This preserves the original implementation, but spies on all methods. In Vitest 3, deeply nested methods were appropriately spied on when using this feature. However, this breaks in Vitest 4. The method is not replaced with a spy and cannot be observed. This can be seen by logging the mocked module in question (see reproduction).

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-czkpuime?file=test%2Findex.spec.ts

In this file, running Vitest 3 npm run test, you see that the "deep" function squared is replaced with a spy:

Image

If you run Vitest 4 (currently installed), this no longer occurs:

Image

System Info

Stackblitz

  System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 20.19.1 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.8.2 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @vitest/ui: latest => 4.0.18 
    vite: ^7.3.1 => 7.3.1 
    vitest: ^4.0.18 => 4.0.18

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions