-
-
Couldn't load subscription status.
- Fork 1.5k
Labels
Description
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.0Used Package Manager
npm
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
LukeNotable