Skip to content

mockOnce methods don't track call count on automocked class methods #8331

@claabs

Description

@claabs

Describe the bug

Starting with vitest@3.2.0, automocked class methods setup with mockReturnValueOnce and mockResolvedValueOnce (perhaps others) do not track calls properly.

index.ts

import { MockMe } from "./mock-me";

export const main = (): { result1: boolean; result2: boolean } => {
    const mockMe = new MockMe();
    const result1 = mockMe.mockMethod();
    const result2 = mockMe.mockMethod();
    return { result1, result2 };
};

index.test.ts

vi.mock("../src/mock-me");

vi.mocked(MockMe.prototype.mockMethod).mockReturnValueOnce(true).mockReturnValueOnce(false);

main();

// Fails with 0 calls
expect(vi.mocked(MockMe.prototype.mockMethod)).toHaveBeenCalledTimes(2);

This does not occur with the non-Once return/resolve methods (e.g. mockReturnValue).
The latest version these tests pass on is v3.2.0-beta.3.
I couldn't produce this issue by just automocking an exported function, only a class method mocked with prototype.

Reproduction

https://github.com/claabs/vitest-repro

  1. Clone the repo
  2. npm i
  3. npm run test, notice that the first two tests fail on vitest>=3.2.0
  4. npm i vitest@3.2.0-beta.3
  5. npm run test, notice that the first two tests pass

System Info

System:
    OS: macOS 15.5
    CPU: (8) arm64 Apple M3
    Memory: 88.98 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.13.1 - ~/.nvm/versions/node/v22.13.1/bin/node
    npm: 10.9.2 - ~/.nvm/versions/node/v22.13.1/bin/npm
    bun: 1.2.12 - ~/.bun/bin/bun
  Browsers:
    Chrome: 138.0.7204.158
    Safari: 18.5
  npmPackages:
    vitest: ^3.2.4 => 3.2.4

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