diff --git a/packages/spy/src/index.ts b/packages/spy/src/index.ts index 029ac0de4f32..17042b88bea9 100644 --- a/packages/spy/src/index.ts +++ b/packages/spy/src/index.ts @@ -404,7 +404,7 @@ export function spyOn> | Methods>>( ): Required[M] extends | { new (...args: infer A): infer R } | ((...args: infer A) => infer R) - ? MockInstance<(...args: A) => R> + ? MockInstance<(this: R, ...args: A) => R> : never export function spyOn( obj: T, diff --git a/test/core/test/jest-mock.test.ts b/test/core/test/jest-mock.test.ts index 8c633fceaf8d..10bd7c27dba7 100644 --- a/test/core/test/jest-mock.test.ts +++ b/test/core/test/jest-mock.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, expectTypeOf, it, vi } from 'vitest' describe('jest mock compat layer', () => { const returnFactory = (type: string) => (value: any) => ({ type, value }) @@ -72,6 +72,22 @@ describe('jest mock compat layer', () => { expect(Spy.mock.contexts[2]).toBe(ctx2) }) + it('tracks spied class contexts and instances', () => { + interface SpyClass {} + interface SpyConstructor { + (): SpyClass + new (): SpyClass + } + const Spy = (function () {}) as SpyConstructor + const obj = { Spy } + const spy = vi.spyOn(obj, 'Spy') + const instance = new obj.Spy() + + expectTypeOf(spy.mock.contexts[0]).toEqualTypeOf() + expect(spy.mock.instances).toEqual([instance]) + expect(spy.mock.contexts).toEqual([instance]) + }) + it('implementation is set correctly on init', () => { const impl = () => 1 const mock1 = vi.fn(impl)