Skip to content

mock.instances has type void[] for constructors #8869

@matanui159

Description

@matanui159

Describe the bug

When using a class mock (e.g. via vi.mocked), the typings for the instances array is always void. They seem to use the same MockReturnType which will be void:
https://github.com/vitest-dev/vitest/blob/ed9fc71076f94f23320922f115e37bc9a84b6dbb/packages/spy/src/types.ts#L49C1-L53C1

I am unsure if this is intentional but it does not make sense, especially when instances are expected to be used for constructors. The test runs fine regardless.

Reproduction

// foobar.ts
export class Foobar {
    helloWorld(): void {}
}

// foobar.spec.ts
import { describe, expect, it, vi } from 'vitest';
import { Foobar } from './foobar.js';

vi.mock(import('./foobar.js'));

describe('Foobar', () => {
    it('has a helloWorld method', () => {
        new Foobar();
        const [instance] = vi.mocked(Foobar).mock.instances;
        expect(instance.helloWorld).toBeDefined();
    });
});

The test passes but running tsc emits:

src/foobar.spec.ts:10:25 - error TS2339: Property 'helloWorld' does not exist on type 'void'.

10         expect(instance.helloWorld).toBeDefined();
                           ~~~~~~~~~~


Found 1 error in src/foobar.spec.ts:10

System Info

System:
    OS: macOS 26.0.1
    CPU: (16) arm64 Apple M4 Max
    Memory: 200.88 MB / 64.00 GB
    Shell: 4.1.2 - /opt/homebrew/bin/fish
  Binaries:
    Node: 22.18.0 - /Users/matanui159/.local/state/fnm_multishells/12587_1761795789805/bin/node
    Yarn: 1.22.22 - /Users/matanui159/.local/state/fnm_multishells/12587_1761795789805/bin/yarn
    npm: 10.9.3 - /Users/matanui159/.local/state/fnm_multishells/12587_1761795789805/bin/npm
    pnpm: 10.20.0 - /Users/matanui159/.local/state/fnm_multishells/12587_1761795789805/bin/pnpm
  Browsers:
    Chrome: 141.0.7390.123
    Edge: 141.0.3537.99
    Safari: 26.0.1
  npmPackages:
    vitest: ^4.0.5 => 4.0.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