Skip to content

Mocking a module that is a class will have all of its instances to share the same 'mock' #4281

@rafaelmaiolla

Description

@rafaelmaiolla

Describe the bug

When using vi.mock('./SomeClass.ts'); to mock a module that is a class exported as default export class SomeClass {...}, it will have all of its instances to share the same 'mock' attribute in the methods.

And if your code create multiple instances of that SomeClass, it is not possible to check if a method was called from one or the other instance as both will share the mock attribute.

This works fine in Jest, both checks above will be false.

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-i4zx4z?file=test%2Fbasic.test.ts

System Info

System:
    OS: Windows 10 10.0.19045
    CPU: (12) x64 Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz   
    Memory: 5.79 GB / 31.91 GB
  Binaries:
    Node: 18.15.0 - ~\.nvm\versions\node\v18.15.0\bin\node.EXE
    npm: 9.5.0 - ~\.nvm\versions\node\v18.15.0\bin\npm.CMD    
  npmPackages:
    @vitejs/plugin-react-swc: 3.4.0 => 3.4.0
    @vitest/coverage-v8: 0.34.6 => 0.34.6
    vite: 4.4.11 => 4.4.11
    vitest: 0.34.6 => 0.34.6

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions