Skip to content

Commit

Permalink
fix: require.main undefined with createRequire() (#10610)
Browse files Browse the repository at this point in the history
  • Loading branch information
flozender committed Oct 10, 2020
1 parent c80911a commit acd7c83
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 21 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,7 @@

### Fixes

- `[jest-runner, jest-runtime]` fix: `require.main` undefined with `createRequire()` ([#10610](https://github.com/facebook/jest/pull/10610))
- `[jest-validate]` Show suggestion only when unrecognized cli param is longer than 1 character ([#10604](https://github.com/facebook/jest/pull/10604))
- `[jest-validate]` Validate `testURL` as CLI option ([#10595](https://github.com/facebook/jest/pull/10595))

Expand Down
22 changes: 22 additions & 0 deletions e2e/__tests__/requireMainAfterCreateRequire.test.ts
@@ -0,0 +1,22 @@
/**
* 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 * as path from 'path';
import {onNodeVersions} from '@jest/test-utils';
import runJest from '../runJest';

onNodeVersions('>=12.2.0', () => {
test('`require.main` not undefined after createRequire', () => {
const {stdout} = runJest('require-main-after-create-require');

expect(stdout).toBe(
path.join(
__dirname,
'../require-main-after-create-require/__tests__/parent.test.js',
),
);
});
});
14 changes: 14 additions & 0 deletions e2e/require-main-after-create-require/__tests__/parent.test.js
@@ -0,0 +1,14 @@
/**
* 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.
*/
const Module = require('module');
const path = require('path');

test('require child from parent', () => {
// createRequire with a different file
const newRequire = Module.createRequire(path.resolve('./empty.js'));
expect(() => newRequire('./child')).not.toThrow();
});
8 changes: 8 additions & 0 deletions e2e/require-main-after-create-require/child.js
@@ -0,0 +1,8 @@
/**
* 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.
*/
// Will throw if require.main is null
process.stdout.write(require.main.filename);
6 changes: 6 additions & 0 deletions e2e/require-main-after-create-require/empty.js
@@ -0,0 +1,6 @@
/**
* 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.
*/
6 changes: 6 additions & 0 deletions e2e/require-main-after-create-require/package.json
@@ -0,0 +1,6 @@
{
"jest": {
"testEnvironment": "node"
}
}

25 changes: 16 additions & 9 deletions packages/jest-runner/src/runTest.ts
Expand Up @@ -151,15 +151,22 @@ async function runTestInternal(
const cacheFS = {[path]: testSource};
setGlobal(environment.global, 'console', testConsole);

const runtime = new Runtime(config, environment, resolver, cacheFS, {
changedFiles: context?.changedFiles,
collectCoverage: globalConfig.collectCoverage,
collectCoverageFrom: globalConfig.collectCoverageFrom,
collectCoverageOnlyFrom: globalConfig.collectCoverageOnlyFrom,
coverageProvider: globalConfig.coverageProvider,
sourcesRelatedToTestsInChangedFiles:
context?.sourcesRelatedToTestsInChangedFiles,
});
const runtime = new Runtime(
config,
environment,
resolver,
cacheFS,
{
changedFiles: context?.changedFiles,
collectCoverage: globalConfig.collectCoverage,
collectCoverageFrom: globalConfig.collectCoverageFrom,
collectCoverageOnlyFrom: globalConfig.collectCoverageOnlyFrom,
coverageProvider: globalConfig.coverageProvider,
sourcesRelatedToTestsInChangedFiles:
context?.sourcesRelatedToTestsInChangedFiles,
},
path,
);

const start = Date.now();

Expand Down
3 changes: 3 additions & 0 deletions packages/jest-runtime/src/__mocks__/createRuntime.js
Expand Up @@ -47,6 +47,9 @@ module.exports = async function createRuntime(filename, config) {
config,
environment,
Runtime.createResolver(config, hasteMap.moduleMap),
undefined,
undefined,
filename,
);

for (const path of config.setupFiles) {
Expand Down
9 changes: 8 additions & 1 deletion packages/jest-runtime/src/cli/index.ts
Expand Up @@ -84,7 +84,14 @@ export async function run(
setGlobal(environment.global, 'jestProjectConfig', config);
setGlobal(environment.global, 'jestGlobalConfig', globalConfig);

const runtime = new Runtime(config, environment, hasteMap.resolver);
const runtime = new Runtime(
config,
environment,
hasteMap.resolver,
undefined,
undefined,
filePath,
);

for (const path of config.setupFiles) {
// TODO: remove ? in Jest 26
Expand Down
16 changes: 5 additions & 11 deletions packages/jest-runtime/src/index.ts
Expand Up @@ -162,6 +162,7 @@ class Runtime {
private _isolatedModuleRegistry: ModuleRegistry | null;
private _moduleRegistry: ModuleRegistry;
private _esmoduleRegistry: Map<string, Promise<VMModule>>;
private _testPath: Config.Path | undefined;
private _resolver: Resolver;
private _shouldAutoMock: boolean;
private _shouldMockModuleCache: BooleanMap;
Expand All @@ -184,6 +185,8 @@ class Runtime {
resolver: Resolver,
cacheFS: Record<string, string> = {},
coverageOptions?: ShouldInstrumentOptions,
// TODO: Make mandatory in Jest 27
testPath?: Config.Path,
) {
this._cacheFS = new Map(Object.entries(cacheFS));
this._config = config;
Expand All @@ -208,6 +211,7 @@ class Runtime {
this._isolatedMockRegistry = null;
this._moduleRegistry = new Map();
this._esmoduleRegistry = new Map();
this._testPath = testPath;
this._resolver = resolver;
this._scriptTransformer = new ScriptTransformer(config);
this._shouldAutoMock = config.automock;
Expand Down Expand Up @@ -1365,17 +1369,7 @@ class Runtime {

Object.defineProperty(moduleRequire, 'main', {
enumerable: true,
get() {
let mainModule = from.parent;
while (
mainModule &&
mainModule.parent &&
mainModule.id !== mainModule.parent.id
) {
mainModule = mainModule.parent;
}
return mainModule;
},
value: this._testPath ? this._moduleRegistry.get(this._testPath) : null,
});
return moduleRequire;
}
Expand Down

0 comments on commit acd7c83

Please sign in to comment.