Skip to content

Commit

Permalink
fix: return types for vi.mocked are now equal to MaybeMocked (#1511)
Browse files Browse the repository at this point in the history
* fix: return types for vi.mocked are now equal to MaybeMocked

* chore: cleanup
  • Loading branch information
sheremet-va committed Jun 21, 2022
1 parent 4f01b89 commit b523120
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
10 changes: 2 additions & 8 deletions packages/vitest/src/integrations/spy.ts
Expand Up @@ -67,10 +67,10 @@ export type MaybeMockedConstructor<T> = T extends new (
) => infer R
? SpyInstanceFn<ConstructorParameters<T>, R>
: T
export type MockedFunction<T extends Procedure> = MockWithArgs<T> & {
export type MockedFunction<T extends Procedure> = SpyInstanceFn<Parameters<T>, ReturnType<T>> & {
[K in keyof T]: T[K];
}
export type MockedFunctionDeep<T extends Procedure> = MockWithArgs<T> & MockedObjectDeep<T>
export type MockedFunctionDeep<T extends Procedure> = SpyInstanceFn<Parameters<T>, ReturnType<T>> & MockedObjectDeep<T>
export type MockedObject<T> = MaybeMockedConstructor<T> & {
[K in Methods<T>]: T[K] extends Procedure
? MockedFunction<T[K]>
Expand All @@ -96,12 +96,6 @@ export type MaybeMocked<T> = T extends Procedure

export type EnhancedSpy<TArgs extends any[] = any[], TReturns = any> = SpyInstance<TArgs, TReturns> & SpyImpl<TArgs, TReturns>

export interface MockWithArgs<T extends Procedure>
extends SpyInstanceFn<Parameters<T>, ReturnType<T>> {
new (...args: T extends new (...args: any) => any ? ConstructorParameters<T> : never): T
(...args: Parameters<T>): ReturnType<T>
}

export const spies = new Set<SpyInstance>()

export function isMockFunction(fn: any): fn is EnhancedSpy {
Expand Down
11 changes: 11 additions & 0 deletions test/core/test/vi.spec.ts
Expand Up @@ -2,8 +2,11 @@
* @vitest-environment jsdom
*/

import type { MockedFunction, MockedObject } from 'vitest'
import { describe, expect, test, vi } from 'vitest'

const expectType = <T>(obj: T) => obj

describe('testing vi utils', () => {
test('global scope has variable', () => {
const IntersectionObserverMock = vi.fn()
Expand All @@ -29,6 +32,14 @@ describe('testing vi utils', () => {
expect(v1).toBe(v2)
})

test('vi mocked', () => {
expectType<MockedObject<{ bar: () => boolean }>>({
bar: vi.fn(() => true),
})
expectType<MockedFunction<() => boolean>>(vi.fn(() => true))
expectType<MockedFunction<() => boolean>>(vi.fn())
})

// TODO: it's unstable in CI, skip until resolved
test.skip('loads unloaded module', async () => {
let mod: any
Expand Down

0 comments on commit b523120

Please sign in to comment.