diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e9c4c1ef83f..29fca69044f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ### Features +* `[jest-runtime]` Prevent modules from marking themselves as thier own parent + ([#5235](https://github.com/facebook/jest/issues/5235)) * `[expect]` Add support for async matchers ([#5836](https://github.com/facebook/jest/pull/5919)) * `[expect]` Suggest toContainEqual diff --git a/packages/jest-runtime/src/__tests__/runtime_require_mock.test.js b/packages/jest-runtime/src/__tests__/runtime_require_mock.test.js index 38dab7d03279..f86118ed963c 100644 --- a/packages/jest-runtime/src/__tests__/runtime_require_mock.test.js +++ b/packages/jest-runtime/src/__tests__/runtime_require_mock.test.js @@ -173,10 +173,10 @@ describe('Runtime', () => { expect(exports.isManualMockModule).toBe(true); }); }); + it('provides `require.main` in mock', () => createRuntime(__filename).then(runtime => { - runtime._moduleRegistry[__filename] = module; - runtime.setMock(__filename, 'export_main', () => require.main, { + runtime.setMock(__filename, 'export_main', () => module, { virtual: true, }); const mainModule = runtime.requireMock(__filename, 'export_main'); diff --git a/packages/jest-runtime/src/index.js b/packages/jest-runtime/src/index.js index 8c5619bab736..d179cdfbb81b 100644 --- a/packages/jest-runtime/src/index.js +++ b/packages/jest-runtime/src/index.js @@ -327,7 +327,9 @@ class Runtime { // $FlowFixMe localModule.exports = require(modulePath); } else { - this._execModule(localModule, options, moduleRegistry, from); + // Only include the fromPath if a moduleName is given. Else treat as root. + const fromPath = moduleName ? from : null; + this._execModule(localModule, options, moduleRegistry, fromPath); } localModule.loaded = true; @@ -392,7 +394,10 @@ class Runtime { id: modulePath, loaded: false, }; - this._execModule(localModule, undefined, this._mockRegistry, from); + + // Only include the fromPath if a moduleName is given. Else treat as root. + const fromPath = moduleName ? from : null; + this._execModule(localModule, undefined, this._mockRegistry, fromPath); this._mockRegistry[moduleID] = localModule.exports; localModule.loaded = true; } else { @@ -493,7 +498,7 @@ class Runtime { localModule: Module, options: ?InternalModuleOptions, moduleRegistry: ModuleRegistry, - from: Path, + from: ?Path, ) { // If the environment was disposed, prevent this module from being executed. if (!this._environment.global) { @@ -517,7 +522,8 @@ class Runtime { ({ enumerable: true, get() { - return moduleRegistry[from] || null; + const key = from || ''; + return moduleRegistry[key] || null; }, }: Object), );