Skip to content

Commit 4776eca

Browse files
committed
fix(spy): correctly track constructor's "this" type
1 parent 51c3242 commit 4776eca

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

packages/spy/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ export function spyOn<T, M extends Classes<Required<T>> | Methods<Required<T>>>(
404404
): Required<T>[M] extends
405405
| { new (...args: infer A): infer R }
406406
| ((...args: infer A) => infer R)
407-
? MockInstance<(...args: A) => R>
407+
? MockInstance<(this: R, ...args: A) => R>
408408
: never
409409
export function spyOn<T, K extends keyof T>(
410410
obj: T,

test/core/test/jest-mock.test.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, expect, it, vi } from 'vitest'
1+
import { describe, expect, expectTypeOf, it, vi } from 'vitest'
22

33
describe('jest mock compat layer', () => {
44
const returnFactory = (type: string) => (value: any) => ({ type, value })
@@ -72,6 +72,22 @@ describe('jest mock compat layer', () => {
7272
expect(Spy.mock.contexts[2]).toBe(ctx2)
7373
})
7474

75+
it('tracks spied class contexts and instances', () => {
76+
interface SpyClass {}
77+
interface SpyConstructor {
78+
(): SpyClass
79+
new (): SpyClass
80+
}
81+
const Spy = (function () {}) as SpyConstructor
82+
const obj = { Spy }
83+
const spy = vi.spyOn(obj, 'Spy')
84+
const instance = new obj.Spy()
85+
86+
expectTypeOf(spy.mock.contexts[0]).toEqualTypeOf<SpyClass>()
87+
expect(spy.mock.instances).toEqual([instance])
88+
expect(spy.mock.contexts).toEqual([instance])
89+
})
90+
7591
it('implementation is set correctly on init', () => {
7692
const impl = () => 1
7793
const mock1 = vi.fn(impl)

0 commit comments

Comments
 (0)