Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: override module.createRequire #9469

Merged
merged 13 commits into from
Feb 1, 2020
36 changes: 36 additions & 0 deletions packages/jest-runtime/src/__tests__/runtime_require_module.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@

'use strict';

import {builtinModules, createRequire} from 'module';
import path from 'path';
import {pathToFileURL} from 'url';
// eslint-disable-next-line import/default
import slash from 'slash';
import {onNodeVersions} from '@jest/test-utils';

let createRuntime;

Expand Down Expand Up @@ -347,4 +350,37 @@ describe('Runtime requireModule', () => {
);
expect(exports.isJSONModuleEncodedInUTF8WithBOM).toBe(true);
}));

onNodeVersions('>=12.12.0', () => {
it('overrides module.createRequire', () =>
createRuntime(__filename).then(runtime => {
const exports = runtime.requireModule(runtime.__mockRootPath, 'module');

expect(exports.createRequire).not.toBe(createRequire);

// createRequire with string
{
const customRequire = exports.createRequire(runtime.__mockRootPath);
expect(customRequire('./create_require_module').foo).toBe('foo');
}

// createRequire with URL
{
const customRequire = exports.createRequire(
pathToFileURL(runtime.__mockRootPath),
);
expect(customRequire('./create_require_module').foo).toBe('foo');
}

{
const customRequire = exports.createRequireFromPath(
runtime.__mockRootPath,
);
expect(customRequire('./create_require_module').foo).toBe('foo');
}

expect(exports.syncBuiltinESMExports).not.toThrow();
expect(exports.builtinModules).toEqual(builtinModules);
}));
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* 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.
*/

'use strict';

module.exports.foo = 'foo';
49 changes: 43 additions & 6 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
* LICENSE file in the root directory of this source tree.
*/

import {URL, fileURLToPath} from 'url';
import * as path from 'path';
import {Script, compileFunction} from 'vm';
import {fileURLToPath} from 'url';
import * as nativeModule from 'module';
import {Config} from '@jest/types';
import {
Jest,
Expand All @@ -17,13 +18,9 @@ import {
ModuleWrapper,
} from '@jest/environment';
import {SourceMapRegistry} from '@jest/source-map';
import jestMock = require('jest-mock');
import HasteMap = require('jest-haste-map');
import {formatStackTrace, separateMessageFromStack} from 'jest-message-util';
import Resolver = require('jest-resolve');
import {createDirectory, deepCyclicCopy} from 'jest-util';
import {escapePathForRegex} from 'jest-regex-util';
import Snapshot = require('jest-snapshot');
import {
ScriptTransformer,
ShouldInstrumentOptions,
Expand All @@ -35,11 +32,15 @@ import {
import {V8CoverageResult} from '@jest/test-result';
import {CoverageInstrumenter, V8Coverage} from 'collect-v8-coverage';
import * as fs from 'graceful-fs';
import stripBOM = require('strip-bom');
import {run as cliRun} from './cli';
import {options as cliOptions} from './cli/args';
import {findSiblingsWithFileExtension} from './helpers';
import {Context as JestContext} from './types';
import jestMock = require('jest-mock');
import HasteMap = require('jest-haste-map');
import Resolver = require('jest-resolve');
import Snapshot = require('jest-snapshot');
import stripBOM = require('strip-bom');

type HasteMapOptions = {
console?: Console;
Expand Down Expand Up @@ -887,6 +888,42 @@ class Runtime {
return this._environment.global.process;
}

if (moduleName === 'module') {
const createRequire = (modulePath: string | URL) => {
const filename =
typeof modulePath === 'string'
? modulePath
doniyor2109 marked this conversation as resolved.
Show resolved Hide resolved
: fileURLToPath(modulePath);

return this._createRequireImplementation({
doniyor2109 marked this conversation as resolved.
Show resolved Hide resolved
children: [],
exports: {},
filename,
id: filename,
loaded: false,
});
};

const overriddenModule = {...nativeModule};
doniyor2109 marked this conversation as resolved.
Show resolved Hide resolved

if ('createRequire' in nativeModule) {
Object.defineProperty(overriddenModule, 'createRequire', {
value: createRequire,
});
}
if ('createRequireFromPath' in nativeModule) {
Object.defineProperty(overriddenModule, 'createRequireFromPath', {
value: (filename: string) => createRequire(filename),
doniyor2109 marked this conversation as resolved.
Show resolved Hide resolved
});
}
if ('syncBuiltinESMExports' in nativeModule) {
Object.defineProperty(overriddenModule, 'syncBuiltinESMExports', {
value: () => {},
});
}
return overriddenModule;
}

return require(moduleName);
}

Expand Down