Skip to content

Commit

Permalink
feat(@jest/globals): add jest.Mock type helper (#13235)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrazauskas committed Sep 9, 2022
1 parent 1b20fa9 commit 0b0a54f
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -3,6 +3,7 @@
### Features

- `[@jest/environment, jest-runtime]` Allow passing a generic type argument to `jest.createMockFromModule<T>()` 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

Expand Down
16 changes: 16 additions & 0 deletions docs/MockFunctionAPI.md
Expand Up @@ -515,6 +515,22 @@ test('calculate calls add', () => {
});
```

### `jest.Mock<T>`

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<Source>`

The `jest.Mocked<Source>` utility type returns the `Source` type wrapped with type definitions of Jest mock function.
Expand Down
6 changes: 6 additions & 0 deletions packages/jest-globals/src/index.ts
Expand Up @@ -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;
Expand All @@ -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<T extends FunctionLike = UnknownFunction> = JestMock<T>;
/**
* Wraps a class, function or object type with Jest mock type definitions.
*/
Expand Down
5 changes: 5 additions & 0 deletions packages/jest-types/__typetests__/jest.test.ts
Expand Up @@ -227,6 +227,11 @@ expectType<ModuleMocker['fn']>(jest.fn);

expectType<ModuleMocker['spyOn']>(jest.spyOn);

// Mock<T>

expectType<Mock<() => boolean>>({} as jest.Mock<() => boolean>);
expectType<Mock<(a: string) => string>>({} as jest.Mock<(a: string) => string>);

// Mocked*<T>

class SomeClass {
Expand Down

0 comments on commit 0b0a54f

Please sign in to comment.