Skip to content

Commit

Permalink
fix: type issue with spyOn method (fix #2365) (#2582)
Browse files Browse the repository at this point in the history
* Fixing type issue with spyOn method

* Adding tests
  • Loading branch information
samkevin1 committed Jan 9, 2023
1 parent 1c25938 commit 1aaa79d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/spy/src/index.ts
Expand Up @@ -154,10 +154,10 @@ export function spyOn<T, G extends Properties<Required<T>>>(
methodName: G,
accessType: 'set',
): SpyInstance<[T[G]], void>
export function spyOn<T, M extends (Methods<Required<T>> | Classes<Required<T>>)>(
export function spyOn<T, M extends (Classes<Required<T>> | Methods<Required<T>>)>(
obj: T,
methodName: M,
): Required<T>[M] extends (...args: infer A) => infer R | (new (...args: infer A) => infer R) ? SpyInstance<A, R> : never
): Required<T>[M] extends ({ new (...args: infer A): infer R }) | ((...args: infer A) => infer R) ? SpyInstance<A, R> : never
export function spyOn<T, K extends keyof T>(
obj: T,
method: K,
Expand Down
5 changes: 5 additions & 0 deletions test/core/test/fixtures/hello-mock.ts
@@ -0,0 +1,5 @@
export class HelloWorld {
hello() {
return 'Hello World!'
}
}
20 changes: 20 additions & 0 deletions test/core/test/spy.test.ts
@@ -1,12 +1,32 @@
import { describe, expect, test, vi } from 'vitest'
import * as mock from './fixtures/hello-mock'

/**
* @vitest-environment happy-dom
*/

describe('spyOn', () => {
const hw = new mock.HelloWorld()

test('correctly infers method types', async () => {
vi.spyOn(localStorage, 'getItem').mockReturnValue('world')
expect(window.localStorage.getItem('hello')).toEqual('world')
})

test('infers a class correctly', () => {
vi.spyOn(mock, 'HelloWorld').mockImplementationOnce(() => {
const Mock = vi.fn()
Mock.prototype.hello = vi.fn(() => 'hello world')
return new Mock()
})

const mockedHelloWorld = new mock.HelloWorld()
expect(mockedHelloWorld.hello()).toEqual('hello world')
})

test('infers a method correctly', () => {
vi.spyOn(hw, 'hello').mockImplementationOnce(() => 'hello world')

expect(hw.hello()).toEqual('hello world')
})
})

0 comments on commit 1aaa79d

Please sign in to comment.