Skip to content

Commit 651eb37

Browse files
authored
fix: properly return mocks when using jest.isolatedModules (#11882)
1 parent f4188de commit 651eb37

File tree

3 files changed

+63
-4
lines changed

3 files changed

+63
-4
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
### Fixes
66

7+
- `[jest-runtime]` Fix regression when using `jest.isolateModules` and mocks ([#11882](https://github.com/facebook/jest/pull/11882))
8+
79
### Chore & Maintenance
810

911
### Performance

e2e/__tests__/isolateModules.test.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
import {tmpdir} from 'os';
9+
import * as path from 'path';
10+
import {cleanup, createEmptyPackage, writeFiles} from '../Utils';
11+
import runJest from '../runJest';
12+
13+
const DIR = path.resolve(tmpdir(), 'isolate-modules.test');
14+
15+
beforeEach(() => {
16+
cleanup(DIR);
17+
createEmptyPackage(DIR);
18+
});
19+
20+
afterAll(() => cleanup(DIR));
21+
22+
test('works with mocks', () => {
23+
writeFiles(DIR, {
24+
'config.js': `
25+
module.exports.getBoolean = function getBoolean(variableName) {
26+
return false;
27+
}
28+
`,
29+
'read.js': `
30+
const {getBoolean} = require('./config');
31+
32+
const value = getBoolean('foo');
33+
console.log("was " + value);
34+
`,
35+
'test.js': `
36+
jest.mock('./config');
37+
const config = require('./config');
38+
39+
test('dummy test', () => {
40+
const configGetMock = config.getBoolean.mockImplementation(() => {
41+
return true;
42+
});
43+
44+
jest.isolateModules(() => {
45+
require("./read");
46+
});
47+
48+
expect(configGetMock).toBeCalledTimes(1);
49+
})
50+
`,
51+
});
52+
const {exitCode} = runJest(DIR);
53+
54+
expect(exitCode).toBe(0);
55+
});

packages/jest-runtime/src/index.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -861,12 +861,14 @@ export default class Runtime {
861861
{conditions: this.cjsConditions},
862862
);
863863

864-
const mockRegistry = this._isolatedMockRegistry || this._mockRegistry;
865-
866-
if (mockRegistry.get(moduleID)) {
867-
return mockRegistry.get(moduleID);
864+
if (this._isolatedMockRegistry?.has(moduleID)) {
865+
return this._isolatedMockRegistry.get(moduleID);
866+
} else if (this._mockRegistry.has(moduleID)) {
867+
return this._mockRegistry.get(moduleID);
868868
}
869869

870+
const mockRegistry = this._isolatedMockRegistry || this._mockRegistry;
871+
870872
if (this._mockFactories.has(moduleID)) {
871873
// has check above makes this ok
872874
const module = this._mockFactories.get(moduleID)!();

0 commit comments

Comments
 (0)