Skip to content

Commit 1aaa79d

Browse files
authoredJan 9, 2023
fix: type issue with spyOn method (fix #2365) (#2582)
* Fixing type issue with spyOn method * Adding tests
1 parent 1c25938 commit 1aaa79d

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed
 

‎packages/spy/src/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,10 @@ export function spyOn<T, G extends Properties<Required<T>>>(
154154
methodName: G,
155155
accessType: 'set',
156156
): SpyInstance<[T[G]], void>
157-
export function spyOn<T, M extends (Methods<Required<T>> | Classes<Required<T>>)>(
157+
export function spyOn<T, M extends (Classes<Required<T>> | Methods<Required<T>>)>(
158158
obj: T,
159159
methodName: M,
160-
): Required<T>[M] extends (...args: infer A) => infer R | (new (...args: infer A) => infer R) ? SpyInstance<A, R> : never
160+
): Required<T>[M] extends ({ new (...args: infer A): infer R }) | ((...args: infer A) => infer R) ? SpyInstance<A, R> : never
161161
export function spyOn<T, K extends keyof T>(
162162
obj: T,
163163
method: K,

‎test/core/test/fixtures/hello-mock.ts

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export class HelloWorld {
2+
hello() {
3+
return 'Hello World!'
4+
}
5+
}

‎test/core/test/spy.test.ts

+20
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,32 @@
11
import { describe, expect, test, vi } from 'vitest'
2+
import * as mock from './fixtures/hello-mock'
23

34
/**
45
* @vitest-environment happy-dom
56
*/
67

78
describe('spyOn', () => {
9+
const hw = new mock.HelloWorld()
10+
811
test('correctly infers method types', async () => {
912
vi.spyOn(localStorage, 'getItem').mockReturnValue('world')
1013
expect(window.localStorage.getItem('hello')).toEqual('world')
1114
})
15+
16+
test('infers a class correctly', () => {
17+
vi.spyOn(mock, 'HelloWorld').mockImplementationOnce(() => {
18+
const Mock = vi.fn()
19+
Mock.prototype.hello = vi.fn(() => 'hello world')
20+
return new Mock()
21+
})
22+
23+
const mockedHelloWorld = new mock.HelloWorld()
24+
expect(mockedHelloWorld.hello()).toEqual('hello world')
25+
})
26+
27+
test('infers a method correctly', () => {
28+
vi.spyOn(hw, 'hello').mockImplementationOnce(() => 'hello world')
29+
30+
expect(hw.hello()).toEqual('hello world')
31+
})
1232
})

0 commit comments

Comments
 (0)
Please sign in to comment.