Skip to content

Commit c665f22

Browse files
authored
feat: add createMockFromModule to replace genMockFromModule (#9962)
1 parent 8147af1 commit c665f22

File tree

26 files changed

+76
-33
lines changed

26 files changed

+76
-33
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
- `[jest-environment-jsdom]` [**BREAKING**] Upgrade `jsdom` to v16 ([#9606](https://github.com/facebook/jest/pull/9606))
66
- `[@jest/fake-timers]` Add possibility to use a modern implementation of fake timers, backed by `@sinonjs/fake-timers` ([#7776](https://github.com/facebook/jest/pull/7776))
7+
- `[jest-runtime]` Add `createMockFromModule` as an alias for `genMockFromModule` ([#9962](https://github.com/facebook/jest/pull/9962))
78

89
### Fixes
910

docs/JestObjectAPI.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,11 @@ test('original implementation', () => {
9090

9191
_Note: this method was previously called `autoMockOn`. When using `babel-jest`, calls to `enableAutomock` will automatically be hoisted to the top of the code block. Use `autoMockOn` if you want to explicitly avoid this behavior._
9292

93-
### `jest.genMockFromModule(moduleName)`
93+
### `jest.createMockFromModule(moduleName)`
94+
95+
##### renamed in Jest **26.0.0+**
96+
97+
Also under the alias: `.genMockFromModule(moduleName)`
9498

9599
Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you.
96100

@@ -109,17 +113,17 @@ export default {
109113
```
110114

111115
```js
112-
// __tests__/genMockFromModule.test.js
113-
const utils = jest.genMockFromModule('../utils').default;
116+
// __tests__/createMockFromModule.test.js
117+
const utils = jest.createMockFromModule('../utils').default;
114118
utils.isAuthorized = jest.fn(secret => secret === 'not wizard');
115119

116-
test('implementation created by jest.genMockFromModule', () => {
120+
test('implementation created by jest.createMockFromModule', () => {
117121
expect(utils.authorize.mock).toBeTruthy();
118122
expect(utils.isAuthorized('not wizard')).toEqual(true);
119123
});
120124
```
121125

122-
This is how `genMockFromModule` will mock the following data types:
126+
This is how `createMockFromModule` will mock the following data types:
123127

124128
#### `Function`
125129

@@ -176,7 +180,7 @@ module.exports = {
176180

177181
```js
178182
// __tests__/example.test.js
179-
const example = jest.genMockFromModule('./example');
183+
const example = jest.createMockFromModule('./example');
180184

181185
test('should run example code', () => {
182186
// creates a new mocked function with no formal arguments.

docs/ManualMocks.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ Since we'd like our tests to avoid actually hitting the disk (that's pretty slow
6464

6565
const path = require('path');
6666

67-
const fs = jest.genMockFromModule('fs');
67+
const fs = jest.createMockFromModule('fs');
6868

6969
// This is a custom function that our tests can use during setup to specify
7070
// what the files on the "mock" filesystem should look like when any of the
@@ -124,7 +124,7 @@ describe('listFilesInDirectorySync', () => {
124124
});
125125
```
126126

127-
The example mock shown here uses [`jest.genMockFromModule`](JestObjectAPI.md#jestgenmockfrommodulemodulename) to generate an automatic mock, and overrides its default behavior. This is the recommended approach, but is completely optional. If you do not want to use the automatic mock at all, you can export your own functions from the mock file. One downside to fully manual mocks is that they're manual – meaning you have to manually update them any time the module they are mocking changes. Because of this, it's best to use or extend the automatic mock when it works for your needs.
127+
The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md#jestcreatemockfrommodulemodulename) to generate an automatic mock, and overrides its default behavior. This is the recommended approach, but is completely optional. If you do not want to use the automatic mock at all, you can export your own functions from the mock file. One downside to fully manual mocks is that they're manual – meaning you have to manually update them any time the module they are mocking changes. Because of this, it's best to use or extend the automatic mock when it works for your needs.
128128

129129
To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it.
130130

e2e/runtime-internal-module-registry/__mocks__/fs.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
'use strict';
99

10-
const fs = jest.genMockFromModule('fs');
10+
const fs = jest.createMockFromModule('fs');
1111

1212
let mkdirWasCalled = false;
1313

examples/automatic-mocks/__tests__/genMockFromModule.test.js renamed to examples/automatic-mocks/__tests__/createMockFromModule.test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ test('implementation created by automock', () => {
77
expect(utils.isAuthorized()).toBeUndefined();
88
});
99

10-
test('implementation created by jest.genMockFromModule', () => {
11-
const utils = jest.genMockFromModule('../utils').default;
10+
test('implementation created by jest.createMockFromModule', () => {
11+
const utils = jest.createMockFromModule('../utils').default;
1212
utils.isAuthorized = jest.fn(secret => secret === 'not wizard');
1313

1414
expect(utils.authorize.mock).toBeTruthy();

examples/manual-mocks/__mocks__/fs.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
const path = require('path');
66

7-
const fs = jest.genMockFromModule('fs');
7+
const fs = jest.createMockFromModule('fs');
88

99
// This is a custom function that our tests can use during setup to specify
1010
// what the files on the "mock" filesystem should look like when any of the

examples/manual-mocks/__mocks__/lodash.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright 2004-present Facebook. All Rights Reserved.
22

3-
const lodash = jest.genMockFromModule('lodash');
3+
const lodash = jest.createMockFromModule('lodash');
44

55
lodash.head = arr => 5;
66

examples/manual-mocks/models/__mocks__/user.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright 2004-present Facebook. All Rights Reserved.
22

3-
const user = jest.genMockFromModule('../user');
3+
const user = jest.createMockFromModule('../user');
44

55
user.getAuthenticated = () => ({
66
age: 622,

examples/module-mock/__tests__/partial_mock.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import defaultExport, {apple, strawberry} from '../fruit';
99

1010
jest.mock('../fruit', () => {
1111
const originalModule = jest.requireActual('../fruit');
12-
const mockedModule = jest.genMockFromModule('../fruit');
12+
const mockedModule = jest.createMockFromModule('../fruit');
1313

1414
//Mock the default export and named export 'apple'.
1515
return {

packages/jest-config/src/__mocks__/fs.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
'use strict';
99

10-
const fs = jest.genMockFromModule('fs');
10+
const fs = jest.createMockFromModule('fs');
1111

1212
const mockFiles = new Map();
1313
function __setMockFiles(newMockFiles) {

packages/jest-config/src/__mocks__/os.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
'use strict';
99

10-
const os = jest.genMockFromModule('os');
10+
const os = jest.createMockFromModule('os');
1111

1212
let cpus;
1313
function __setCpus(newCpus) {

packages/jest-environment-jsdom/src/__mocks__/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
const vm = jest.requireActual('vm');
1010

11-
const JSDOMEnvironment = jest.genMockFromModule('../index') as jest.Mock;
11+
const JSDOMEnvironment = jest.createMockFromModule('../index') as jest.Mock;
1212

1313
JSDOMEnvironment.mockImplementation(function (config) {
1414
// @ts-ignore

packages/jest-environment/src/index.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,18 @@ export interface Jest {
126126
*
127127
* This is useful when you want to create a manual mock that extends the
128128
* automatic mock's behavior.
129+
*
130+
* @deprecated Use `jest.createMockFromModule()` instead
129131
*/
130132
genMockFromModule(moduleName: string): unknown;
133+
/**
134+
* Given the name of a module, use the automatic mocking system to generate a
135+
* mocked version of the module for you.
136+
*
137+
* This is useful when you want to create a manual mock that extends the
138+
* automatic mock's behavior.
139+
*/
140+
createMockFromModule(moduleName: string): unknown;
131141
/**
132142
* Determines if the given function is a mocked function.
133143
*/

packages/jest-haste-map/src/__tests__/worker.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ jest.mock('graceful-fs', () => {
3838
};
3939

4040
return {
41-
...jest.genMockFromModule('graceful-fs'),
41+
...jest.createMockFromModule('graceful-fs'),
4242
readFileSync: jest.fn((path, options) => {
4343
if (mockFs[path]) {
4444
return options === 'utf8' ? mockFs[path] : Buffer.from(mockFs[path]);

packages/jest-haste-map/src/lib/__tests__/dependencyExtractor.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,4 +243,24 @@ describe('dependencyExtractor', () => {
243243
`;
244244
expect(extract(code)).toEqual(new Set(['dep1', 'dep2', 'dep3', 'dep4']));
245245
});
246+
247+
it('should extract dependencies from `jest.createMockFromModule` calls', () => {
248+
const code = `
249+
// Good
250+
jest.createMockFromModule('dep1');
251+
const dep2 = jest.createMockFromModule(
252+
"dep2",
253+
);
254+
if (jest.createMockFromModule(\`dep3\`).cond) {}
255+
jest
256+
.requireMock('dep4');
257+
258+
// Bad
259+
${COMMENT_NO_NEG_LB} foo . jest.createMockFromModule('inv1')
260+
xjest.createMockFromModule('inv2');
261+
jest.createMockFromModulex('inv3');
262+
jest.createMockFromModule('inv4', 'inv5');
263+
`;
264+
expect(extract(code)).toEqual(new Set(['dep1', 'dep2', 'dep3', 'dep4']));
265+
});
246266
});

packages/jest-haste-map/src/lib/dependencyExtractor.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ const IMPORT_OR_EXPORT_RE = createRegExp(
6363
const JEST_EXTENSIONS_RE = createRegExp(
6464
[
6565
...functionCallStart(
66-
'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule)',
66+
'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)',
6767
),
6868
CAPTURE_STRING_LITERAL(1),
6969
WHITESPACE,

packages/jest-regex-util/src/__tests__/index.test.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ describe('replacePathSepForRegex()', () => {
1010

1111
describe('posix', () => {
1212
beforeAll(() => {
13-
jest.mock('path', () => ({...jest.genMockFromModule('path'), sep: '/'}));
13+
jest.mock('path', () => ({
14+
...jest.createMockFromModule('path'),
15+
sep: '/',
16+
}));
1417
jest.isolateModules(() => {
1518
replacePathSepForRegex = require('../').replacePathSepForRegex;
1619
});
@@ -24,7 +27,10 @@ describe('replacePathSepForRegex()', () => {
2427

2528
describe('win32', () => {
2629
beforeAll(() => {
27-
jest.mock('path', () => ({...jest.genMockFromModule('path'), sep: '\\'}));
30+
jest.mock('path', () => ({
31+
...jest.createMockFromModule('path'),
32+
sep: '\\',
33+
}));
2834
jest.isolateModules(() => {
2935
replacePathSepForRegex = require('../').replacePathSepForRegex;
3036
});

packages/jest-reporters/src/__tests__/coverage_reporter.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ jest
1313
summarizers: {pkg: jest.fn(() => ({visit: jest.fn()}))},
1414
}))
1515
.mock('istanbul-reports', () => ({
16-
...jest.genMockFromModule('istanbul-reports'),
16+
...jest.createMockFromModule('istanbul-reports'),
1717
create: jest.fn(() => ({execute: jest.fn()})),
1818
}));
1919

packages/jest-runtime/src/__tests__/runtime_gen_mock_from_module.test.js renamed to packages/jest-runtime/src/__tests__/runtime_create_mock_from_module.test.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ describe('Runtime', () => {
1919
createRuntime = require('createRuntime');
2020
});
2121

22-
describe('genMockFromModule', () => {
22+
describe('createMockFromModule', () => {
2323
it('does not cause side effects in the rest of the module system when generating a mock', () =>
2424
createRuntime(__filename).then(runtime => {
2525
const testRequire = runtime.requireModule.bind(
@@ -33,7 +33,7 @@ describe('Runtime', () => {
3333
expect(origModuleStateValue).toBe('default');
3434

3535
// Generate a mock for a module with side effects
36-
const mock = module.jest.genMockFromModule('ModuleWithSideEffects');
36+
const mock = module.jest.createMockFromModule('ModuleWithSideEffects');
3737

3838
// Make sure we get a mock.
3939
expect(mock.fn()).toBe(undefined);
@@ -43,8 +43,8 @@ describe('Runtime', () => {
4343
it('resolves mapped modules correctly', () =>
4444
createRuntime(__filename, {moduleNameMapper}).then(runtime => {
4545
const root = runtime.requireModule(runtime.__mockRootPath);
46-
const mockModule = root.jest.genMockFromModule(
47-
'module/name/genMockFromModule',
46+
const mockModule = root.jest.createMockFromModule(
47+
'module/name/createMockFromModule',
4848
);
4949

5050
expect(mockModule.test.mock).toBeTruthy();
@@ -59,7 +59,7 @@ describe('Runtime', () => {
5959
);
6060

6161
const module = testRequire('RegularModule');
62-
const mockModule = module.jest.genMockFromModule('RegularModule');
62+
const mockModule = module.jest.createMockFromModule('RegularModule');
6363
const testObjectPrototype = Object.getPrototypeOf(module.object);
6464
const mockObjectPrototype = Object.getPrototypeOf(mockModule.object);
6565
expect(mockObjectPrototype).toBe(testObjectPrototype);

packages/jest-runtime/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1483,6 +1483,8 @@ class Runtime {
14831483
autoMockOn: enableAutomock,
14841484
clearAllMocks,
14851485
clearAllTimers: () => _getFakeTimers().clearAllTimers(),
1486+
createMockFromModule: (moduleName: string) =>
1487+
this._generateMock(from, moduleName),
14861488
deepUnmock,
14871489
disableAutomock,
14881490
doMock: mock,

packages/jest-snapshot/src/__tests__/inline_snapshots.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
*/
77

88
jest.mock('graceful-fs', () => ({
9-
...jest.genMockFromModule<typeof import('fs')>('fs'),
9+
...jest.createMockFromModule<typeof import('fs')>('fs'),
1010
existsSync: jest.fn().mockReturnValue(true),
1111
readdirSync: jest.fn().mockReturnValue([]),
1212
statSync: jest.fn(filePath => ({

packages/jest-snapshot/src/__tests__/utils.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
*/
77

88
jest.mock('graceful-fs', () => ({
9-
...jest.genMockFromModule<typeof import('fs')>('fs'),
9+
...jest.createMockFromModule<typeof import('fs')>('fs'),
1010
existsSync: jest.fn().mockReturnValue(true),
1111
}));
1212

packages/jest-source-map/src/__tests__/getCallsite.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import getCallsite from '../getCallsite';
1111

1212
// Node 10.5.x compatibility
1313
jest.mock('graceful-fs', () => ({
14-
...jest.genMockFromModule<typeof import('fs')>('fs'),
14+
...jest.createMockFromModule<typeof import('fs')>('fs'),
1515
ReadStream: jest.requireActual('fs').ReadStream,
1616
WriteStream: jest.requireActual('fs').WriteStream,
1717
}));

packages/jest-test-sequencer/src/__tests__/test_sequencer.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import * as fs from 'graceful-fs';
1010
import TestSequencer from '../index';
1111

1212
jest.mock('graceful-fs', () => ({
13-
...jest.genMockFromModule('fs'),
13+
...jest.createMockFromModule('fs'),
1414
existsSync: jest.fn(() => true),
1515
readFileSync: jest.fn(() => '{}'),
1616
}));

packages/jest-transform/src/__tests__/script_transformer.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ jest
1313
.mock('graceful-fs', () =>
1414
// Node 10.5.x compatibility
1515
({
16-
...jest.genMockFromModule('fs'),
16+
...jest.createMockFromModule('fs'),
1717
ReadStream: jest.requireActual('fs').ReadStream,
1818
WriteStream: jest.requireActual('fs').WriteStream,
1919
readFileSync: jest.fn((path, options) => {

0 commit comments

Comments
 (0)