Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/stubs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const configureMock = <TFunc extends AnyMockable>(
const behaviorStack = createBehaviorStack<TFunc>()
const fallbackImplementation = getFallbackImplementation(mock)

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

case BehaviorType.DO: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return behavior.callback?.(...args)
return behavior.callback?.call(this, ...args)
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions test/vitest-when.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'

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

declare module 'vitest' {
interface AsymmetricMatchersContaining {
Expand Down Expand Up @@ -129,6 +130,26 @@ describe('vitest-when', () => {
expect(callback).toHaveBeenCalledTimes(1)
})

it('should mock a constructor via thenDo', () => {
const Spy = subject
.when(vi.fn<typeof SimpleClass>())
.calledWith(42)
.thenDo(function (this: SimpleClass) {
this.simpleMethod = () => 'hello'
})

expect(new Spy(42).simpleMethod()).toBe('hello')
})

it('should mock a constructor via thenReturn', () => {
const Spy = subject
.when(vi.fn<typeof SimpleClass>())
.calledWith(42)
.thenReturn({ simpleMethod: () => 'hello' })

expect(new Spy(42).simpleMethod()).toBe('hello')
})

it('should return multiple values', () => {
const spy = subject.when(vi.fn()).calledWith(1, 2, 3).thenReturn(4, 5, 6)

Expand Down