所以这个有点难以开始工作。解决方案非常简单,但我花了一段时间才让它工作。问题是每当你在玩笑中使用任何模块时
它们都以以下方式加载
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){/*内部的模块代码*/
}});
如果你看看node_modules/jest-runtime/build/index.js:495:510
const dirname = (_path || _load_path()).default.dirname(filename);
localModule.children = [];
localModule.parent = mockParentModule;
localModule.paths = this._resolver.getModulePaths(dirname);
localModule.require = this._createRequireImplementation(filename, options);
const transformedFile = this._scriptTransformer.transform(
filename,
{
collectCoverage: this._coverageOptions.collectCoverage,
collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
isInternalModule,
mapCoverage: this._coverageOptions.mapCoverage },
this._cacheFS[filename]);
this._createRequireImplementation(filename, options); 给每个模块一个自定义的 require 对象。因此,您根本无法在任何地方获得本机 require 功能。一旦 jest 启动,从那时起加载的每个模块都将具有 jest 的自定义 require 函数。
当我们加载一个模块时,来自jest-runtime 的requireModule 方法被调用。以下是同一节的摘录
moduleRegistry[modulePath] = localModule;
if ((_path || _load_path()).default.extname(modulePath) === '.json') {
localModule.exports = this._environment.global.JSON.parse(
(0, (_stripBom || _load_stripBom()).default)((_gracefulFs || _load_gracefulFs()).default.readFileSync(modulePath, 'utf8')));
} else if ((_path || _load_path()).default.extname(modulePath) === '.node') {
// $FlowFixMe
localModule.exports = require(modulePath);
} else {
this._execModule(localModule, options);
}
如你所见,如果文件的扩展名是.node,它会直接加载模块,否则它会调用_execModule。这个函数与我之前发布的代码相同,用于代码转换
const isInternalModule = !!(options && options.isInternalModule);
const filename = localModule.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
const dirname = (_path || _load_path()).default.dirname(filename);
localModule.children = [];
localModule.parent = mockParentModule;
localModule.paths = this._resolver.getModulePaths(dirname);
localModule.require = this._createRequireImplementation(filename, options);
现在当我们要修改require函数进行测试时,我们需要_execModule直接导出我们的代码。所以代码应该类似于加载.node 模块
} else if ((_path || _load_path()).default.extname(modulePath) === '.mjs') {
// $FlowFixMe
require = require("@std/esm")(localModule);
localModule.exports = require(modulePath);
} else {
但这样做意味着修补代码,这是我们想要避免的。所以我们要做的是避免直接使用 jest 命令,并创建我们自己的 jestload.js 并运行它。加载jest的代码很简单
#!/usr/bin/env node
/**
* Copyright (c) 2014-present, Facebook, Inc. 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.
*/
cli = require('jest/bin/jest');
现在我们要在 cli 加载之前修改 _execModule。所以我们添加下面的代码
const jestRuntime = require("jest-runtime");
oldexecModule = jestRuntime.prototype._execModule;
jestRuntime.prototype._execModule = function (localModule, options) {
if (localModule.id.indexOf(".mjs") > 0) {
localModule.exports = require("@std/esm")(localModule)(localModule.id);
return localModule;
}
return oldexecModule.apply(this, [localModule, options]);
};
cli = require('jest/bin/jest');
现在是测试时间
//__test__/sum.test.js
sum = require('../sum.mjs').sum;
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('adds 2 + 3 to equal 5', () => {
expect(sum(3, 2)).toBe(5);
});
还有一个sum.mjs 文件
export function sum (x, y) { return x + y }
现在我们运行测试
解决方案可在以下 repo 中找到
https://github.com/tarunlalwani/jest-overriding-require-function-stackoverflow
您可以通过运行npm test 来克隆和测试解决方案。