From 0b0a54fa04fd919b4d597aacac71a2cdf5378607 Mon Sep 17 00:00:00 2001 From: Tom Mrazauskas Date: Sat, 10 Sep 2022 02:10:13 +0300 Subject: [PATCH] feat(@jest/globals): add `jest.Mock` type helper (#13235) --- CHANGELOG.md | 1 + docs/MockFunctionAPI.md | 16 ++++++++++++++++ packages/jest-globals/src/index.ts | 6 ++++++ packages/jest-types/__typetests__/jest.test.ts | 5 +++++ 4 files changed, 28 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fec173370b0c..9e7cc0c566a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ### Features - `[@jest/environment, jest-runtime]` Allow passing a generic type argument to `jest.createMockFromModule()` method ([#13202](https://github.com/facebook/jest/pull/13202)) +- `[@jest/globals]` Add `jest.Mock` type helper ([#13235](https://github.com/facebook/jest/pull/13235)) ### Fixes diff --git a/docs/MockFunctionAPI.md b/docs/MockFunctionAPI.md index bf15e932482c..1ae3a0d43f77 100644 --- a/docs/MockFunctionAPI.md +++ b/docs/MockFunctionAPI.md @@ -515,6 +515,22 @@ test('calculate calls add', () => { }); ``` +### `jest.Mock` + +Constructs the type of a mock function, e.g. the return type of `jest.fn()`. It can be useful if you have to defined a recursive mock function: + +```ts +import {jest} from '@jest/globals'; + +const sumRecursively: jest.Mock<(value: number) => number> = jest.fn(value => { + if (value === 0) { + return 0; + } else { + return value + fn(value - 1); + } +}); +``` + ### `jest.Mocked` The `jest.Mocked` utility type returns the `Source` type wrapped with type definitions of Jest mock function. diff --git a/packages/jest-globals/src/index.ts b/packages/jest-globals/src/index.ts index a06db18df650..956d2b3fece7 100644 --- a/packages/jest-globals/src/index.ts +++ b/packages/jest-globals/src/index.ts @@ -11,10 +11,12 @@ import type {Global} from '@jest/types'; import type { ClassLike, FunctionLike, + Mock as JestMock, Mocked as JestMocked, MockedClass as JestMockedClass, MockedFunction as JestMockedFunction, MockedObject as JestMockedObject, + UnknownFunction, } from 'jest-mock'; export declare const expect: JestExpect; @@ -36,6 +38,10 @@ declare const jest: Jest; // eslint-disable-next-line @typescript-eslint/no-namespace declare namespace jest { + /** + * Constructs the type of a mock function, e.g. the return type of `jest.fn()`. + */ + export type Mock = JestMock; /** * Wraps a class, function or object type with Jest mock type definitions. */ diff --git a/packages/jest-types/__typetests__/jest.test.ts b/packages/jest-types/__typetests__/jest.test.ts index 188fe697072c..972e242cd93a 100644 --- a/packages/jest-types/__typetests__/jest.test.ts +++ b/packages/jest-types/__typetests__/jest.test.ts @@ -227,6 +227,11 @@ expectType(jest.fn); expectType(jest.spyOn); +// Mock + +expectType boolean>>({} as jest.Mock<() => boolean>); +expectType string>>({} as jest.Mock<(a: string) => string>); + // Mocked* class SomeClass {