Skip to content

Commit

Permalink
fix(spy): correctly track constructor's "this" type
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Jul 8, 2024
1 parent 51c3242 commit 4776eca
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/spy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ export function spyOn<T, M extends Classes<Required<T>> | Methods<Required<T>>>(
): Required<T>[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<T, K extends keyof T>(
obj: T,
Expand Down
18 changes: 17 additions & 1 deletion test/core/test/jest-mock.test.ts
Original file line number Diff line number Diff line change
@@ -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 })
Expand Down Expand Up @@ -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<SpyClass>()
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)
Expand Down

0 comments on commit 4776eca

Please sign in to comment.