in packages/jest-runtime/src/index.ts [1400:1513]
private _execModule(
localModule: InitialModule,
options: InternalModuleOptions | undefined,
moduleRegistry: ModuleRegistry,
from: string | null,
) {
if (this.isTornDown) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
// If the environment was disposed, prevent this module from being executed.
if (!this._environment.global) {
return;
}
const module = localModule as Module;
const filename = module.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
module.children = [];
Object.defineProperty(module, 'parent', {
enumerable: true,
get() {
const key = from || '';
return moduleRegistry.get(key) || null;
},
});
module.paths = this._resolver.getModulePaths(module.path);
Object.defineProperty(module, 'require', {
value: this._createRequireImplementation(module, options),
});
const transformedCode = this.transformFile(filename, options);
let compiledFunction: ModuleWrapper | null = null;
const script = this.createScriptFromCode(transformedCode, filename);
let runScript: RunScriptEvalResult | null = null;
const vmContext = this._environment.getVmContext();
if (vmContext) {
runScript = script.runInContext(vmContext, {filename});
}
if (runScript !== null) {
compiledFunction = runScript[EVAL_RESULT_VARIABLE];
}
if (compiledFunction === null) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
const jestObject = this._createJestObjectFor(filename);
this.jestObjectCaches.set(filename, jestObject);
const lastArgs: [Jest | undefined, ...Array<Global.Global>] = [
this._config.injectGlobals ? jestObject : undefined, // jest object
...this._config.sandboxInjectedGlobals.map<Global.Global>(
globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}
throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
},
),
];
if (!this._mainModule && filename === this._testPath) {
this._mainModule = module;
}
Object.defineProperty(module, 'main', {
enumerable: true,
value: this._mainModule,
});
try {
compiledFunction.call(
module.exports,
module, // module object
module.exports, // module exports
module.require, // require implementation
module.path, // __dirname
module.filename, // __filename
// @ts-expect-error
...lastArgs.filter(notEmpty),
);
} catch (error: any) {
this.handleExecutionError(error, module);
}
this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
this._currentlyExecutingModulePath = lastExecutingModulePath;
}