Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: type issue with spyOn method (fix #2365) #2582

Merged
merged 3 commits into from Jan 9, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/vitest/src/integrations/spy.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')
})
})