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

feat(@jest/environment, jest-runtime): allow requireActual and requireMock to take a type argument #13253

Merged
merged 3 commits into from Sep 13, 2022
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

### Features

- `[feat(@jest/environment, jest-runtime)]` Allow `jest.requireActual` and `jest.requireMock` to take a type argument ([#13253](https://github.com/facebook/jest/pull/13253))
- `[@jest/fake-timers]` Add `jest.now()` to return the current fake clock time ([#13244](https://github.com/facebook/jest/pull/13244), [13246](https://github.com/facebook/jest/pull/13246))

### Fixes
Expand Down
36 changes: 31 additions & 5 deletions docs/JestObjectAPI.md
Expand Up @@ -416,9 +416,7 @@ _Note It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-optio

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

Example:

```js
```js tab
jest.mock('../myModule', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('../myModule');
Expand All @@ -435,6 +433,24 @@ const getRandom = require('../myModule').getRandom;
getRandom(); // Always returns 10
```

```ts tab
jest.mock('../myModule', () => {
// Require the original module to not be mocked...
const originalModule =
jest.requireActual<typeof import('../myModule')>('../myModule');

return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
getRandom: jest.fn<() => number>().mockReturnValue(10),
};
});

const getRandom = require('../myModule').getRandom;

getRandom(); // Always returns 10
```

### `jest.requireMock(moduleName)`

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.
Expand Down Expand Up @@ -491,7 +507,7 @@ const otherCopyOfMyModule = require('myModule');

Returns a new, unused [mock function](MockFunctionAPI.md). Optionally takes a mock implementation.

```js
```js tab
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
Expand All @@ -501,9 +517,19 @@ const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;
```

```ts tab
const mockFn = jest.fn<() => void>();
mockFn();
expect(mockFn).toHaveBeenCalled();

// With a mock implementation:
const returnsTrue = jest.fn<() => boolean>(() => true);
console.log(returnsTrue()); // true;
```

:::tip

See [Mock Functions](MockFunctionAPI.md#jestfnimplementation) page for details on TypeScript usage.
See [Mock Functions](MockFunctionAPI.md#jestfnimplementation) page for more details on TypeScript usage.

:::

Expand Down
4 changes: 2 additions & 2 deletions packages/jest-environment/src/index.ts
Expand Up @@ -205,7 +205,7 @@ export interface Jest {
getRandom(); // Always returns 10
```
*/
requireActual: (moduleName: string) => unknown;
requireActual<T = unknown>(moduleName: string): T;
/**
* Wraps types of the `source` object and its deep members with type definitions
* of Jest mock function. Pass `{shallow: true}` option to disable the deeply
Expand All @@ -216,7 +216,7 @@ export interface Jest {
* Returns a mock module instead of the actual module, bypassing all checks
* on whether the module should be required normally or not.
*/
requireMock: (moduleName: string) => unknown;
requireMock<T = unknown>(moduleName: string): T;
/**
* Resets the state of all mocks. Equivalent to calling `.mockReset()` on
* every mocked function.
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-runtime/src/index.ts
Expand Up @@ -2129,8 +2129,8 @@ export default class Runtime {
mock,
mocked,
now: () => _getFakeTimers().now(),
requireActual: this.requireActual.bind(this, from),
requireMock: this.requireMock.bind(this, from),
requireActual: moduleName => this.requireActual(from, moduleName),
requireMock: moduleName => this.requireMock(from, moduleName),
Comment on lines -2132 to +2133
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this fine? Not sure I understand what bind does here. Rework it, because I couldn’t find a clean way to return T through bind. Only work around was though casting, but this way it looked cleaner. All test are passing locally, let’s see what CI thinks.

resetAllMocks,
resetModules,
restoreAllMocks,
Expand Down
6 changes: 6 additions & 0 deletions packages/jest-types/__typetests__/jest.test.ts
Expand Up @@ -118,9 +118,15 @@ expectType<typeof jest>(
);

expectType<unknown>(jest.requireActual('./pathToModule'));
expectType<{some: 'module'}>(
jest.requireActual<{some: 'module'}>('./pathToModule'),
);
expectError(jest.requireActual());

expectType<unknown>(jest.requireMock('./pathToModule'));
expectType<{some: 'module'}>(
jest.requireMock<{some: 'module'}>('./pathToModule'),
);
expectError(jest.requireMock());

expectType<typeof jest>(jest.resetModules());
Expand Down