Skip to content

Vitest 4 mock types don't allow class implementation #8803

@notaphplover

Description

@notaphplover

Describe the bug

Docs suggests classes as contructor mock implementations:

const cart = {
  Apples: class Apples {
    getApples() {
      return 42
    }
  }
}

const Spy = vi.spyOn(cart, 'Apples')
  // with a function keyword
  .mockImplementation(function () {
    this.getApples = () => 0
  })
  // with a custom class
  .mockImplementation(class MockApples {
    getApples() {
      return 0
    }
  })

const mock = new Spy()

However, it seems mock types do not allow providing such implementations

Reproduction

Consider this sample code:

import { vitest, type Mocked, type Mock } from 'vitest';

class Foo {
  constructor(public readonly bar: string) {}

  public getBar(): string {
    return this.bar;
  }
}

class FooMock implements Mocked<Foo> {
  readonly barMock: Mock<() => string> = vitest.fn();

  public get bar(): string {
    return this.barMock();
  }

  public getBar: Mock<() => string> = vitest
    .fn()
    .mockImplementation(() => this.barMock());
}

vitest.mocked(Foo).mockImplementation(FooMock);
vitest.mocked(Foo).mockImplementation(Foo);

Typescript complains with the following errors:

Argument of type 'typeof FooMock' is not assignable to parameter of type '(bar: string) => Foo'.
  Type 'typeof FooMock' provides no match for the signature '(bar: string): Foo'.

Argument of type 'typeof Foo' is not assignable to parameter of type '(bar: string) => Foo'.
  Type 'typeof Foo' provides no match for the signature '(bar: string): Foo'.

Repro available here

System Info

System:
    OS: Linux 6.14 Ubuntu 24.04.3 LTS 24.04.3 LTS (Noble Numbat)
    CPU: (16) x64 AMD Ryzen 9 4900HS with Radeon Graphics
    Memory: 31.22 GB / 38.60 GB
    Container: Yes
    Shell: 5.2.21 - /bin/bash
  Binaries:
    Node: 24.10.0 - /home/bob/.nvm/versions/node/v24.10.0/bin/node
    npm: 11.6.1 - /home/bob/.nvm/versions/node/v24.10.0/bin/npm
    pnpm: 10.19.0 - /home/bob/.nvm/versions/node/v24.10.0/bin/pnpm
  Browsers:
    Chrome: 141.0.7390.122
    Firefox: 144.0
    Firefox Developer Edition: 144.0

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