Skip to content

Commit 5ee07dd

Browse files
sirlancelotmcous
andauthored
fix: support mocked constructors in Vitest v4 (#33)
Co-authored-by: Michael Cousins <michael@cousins.io>
1 parent 3b0eeee commit 5ee07dd

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/stubs.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export const configureMock = <TFunc extends AnyMockable>(
3333
const behaviorStack = createBehaviorStack<TFunc>()
3434
const fallbackImplementation = getFallbackImplementation(mock)
3535

36-
const implementation = (...args: ParametersOf<TFunc>) => {
36+
function implementation(this: ThisType<TFunc>, ...args: ParametersOf<TFunc>) {
3737
const behavior = behaviorStack.use(args)?.behavior ?? {
3838
type: BehaviorType.DO,
3939
callback: fallbackImplementation,
@@ -59,7 +59,7 @@ export const configureMock = <TFunc extends AnyMockable>(
5959

6060
case BehaviorType.DO: {
6161
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
62-
return behavior.callback?.(...args)
62+
return behavior.callback?.call(this, ...args)
6363
}
6464
}
6565
}

test/vitest-when.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, it, vi } from 'vitest'
22

33
import * as subject from '../src/vitest-when.ts'
4+
import { SimpleClass } from './fixtures.ts'
45

56
declare module 'vitest' {
67
interface AsymmetricMatchersContaining {
@@ -129,6 +130,26 @@ describe('vitest-when', () => {
129130
expect(callback).toHaveBeenCalledTimes(1)
130131
})
131132

133+
it('should mock a constructor via thenDo', () => {
134+
const Spy = subject
135+
.when(vi.fn<typeof SimpleClass>())
136+
.calledWith(42)
137+
.thenDo(function (this: SimpleClass) {
138+
this.simpleMethod = () => 'hello'
139+
})
140+
141+
expect(new Spy(42).simpleMethod()).toBe('hello')
142+
})
143+
144+
it('should mock a constructor via thenReturn', () => {
145+
const Spy = subject
146+
.when(vi.fn<typeof SimpleClass>())
147+
.calledWith(42)
148+
.thenReturn({ simpleMethod: () => 'hello' })
149+
150+
expect(new Spy(42).simpleMethod()).toBe('hello')
151+
})
152+
132153
it('should return multiple values', () => {
133154
const spy = subject.when(vi.fn()).calledWith(1, 2, 3).thenReturn(4, 5, 6)
134155

0 commit comments

Comments
 (0)