diff --git a/src/stubs.ts b/src/stubs.ts index b077f90..d5a201f 100644 --- a/src/stubs.ts +++ b/src/stubs.ts @@ -33,7 +33,7 @@ export const configureMock = ( const behaviorStack = createBehaviorStack() const fallbackImplementation = getFallbackImplementation(mock) - const implementation = (...args: ParametersOf) => { + function implementation(this: ThisType, ...args: ParametersOf) { const behavior = behaviorStack.use(args)?.behavior ?? { type: BehaviorType.DO, callback: fallbackImplementation, @@ -59,7 +59,7 @@ export const configureMock = ( case BehaviorType.DO: { // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return behavior.callback?.(...args) + return behavior.callback?.call(this, ...args) } } } diff --git a/test/vitest-when.test.ts b/test/vitest-when.test.ts index 063df06..c04758d 100644 --- a/test/vitest-when.test.ts +++ b/test/vitest-when.test.ts @@ -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 { @@ -129,6 +130,26 @@ describe('vitest-when', () => { expect(callback).toHaveBeenCalledTimes(1) }) + it('should mock a constructor via thenDo', () => { + const Spy = subject + .when(vi.fn()) + .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()) + .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)