Skip to content

Commit

Permalink
fix: properly return mocks when using jest.isolatedModules (#11882)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Sep 17, 2021
1 parent f4188de commit 651eb37
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Fixes

- `[jest-runtime]` Fix regression when using `jest.isolateModules` and mocks ([#11882](https://github.com/facebook/jest/pull/11882))

### Chore & Maintenance

### Performance
Expand Down
55 changes: 55 additions & 0 deletions e2e/__tests__/isolateModules.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {tmpdir} from 'os';
import * as path from 'path';
import {cleanup, createEmptyPackage, writeFiles} from '../Utils';
import runJest from '../runJest';

const DIR = path.resolve(tmpdir(), 'isolate-modules.test');

beforeEach(() => {
cleanup(DIR);
createEmptyPackage(DIR);
});

afterAll(() => cleanup(DIR));

test('works with mocks', () => {
writeFiles(DIR, {
'config.js': `
module.exports.getBoolean = function getBoolean(variableName) {
return false;
}
`,
'read.js': `
const {getBoolean} = require('./config');
const value = getBoolean('foo');
console.log("was " + value);
`,
'test.js': `
jest.mock('./config');
const config = require('./config');
test('dummy test', () => {
const configGetMock = config.getBoolean.mockImplementation(() => {
return true;
});
jest.isolateModules(() => {
require("./read");
});
expect(configGetMock).toBeCalledTimes(1);
})
`,
});
const {exitCode} = runJest(DIR);

expect(exitCode).toBe(0);
});
10 changes: 6 additions & 4 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -861,12 +861,14 @@ export default class Runtime {
{conditions: this.cjsConditions},
);

const mockRegistry = this._isolatedMockRegistry || this._mockRegistry;

if (mockRegistry.get(moduleID)) {
return mockRegistry.get(moduleID);
if (this._isolatedMockRegistry?.has(moduleID)) {
return this._isolatedMockRegistry.get(moduleID);
} else if (this._mockRegistry.has(moduleID)) {
return this._mockRegistry.get(moduleID);
}

const mockRegistry = this._isolatedMockRegistry || this._mockRegistry;

if (this._mockFactories.has(moduleID)) {
// has check above makes this ok
const module = this._mockFactories.get(moduleID)!();
Expand Down

0 comments on commit 651eb37

Please sign in to comment.