mock.module(specifier[, options])
稳定性: 1.0 - 早期开发
specifier<string> | <URL> 一个用于标识要模拟的模块的字符串。options<Object> 模拟模块的可选配置选项。支持以下属性:cache<boolean> 如果为false,每次调用require()或import()都会生成一个新的模拟模块。如果为true,后续调用将返回相同的模块模拟,并且该模拟模块会被插入到 CommonJS 缓存中。默认值: false。defaultExport<any> 一个可选值,用作模拟模块的默认导出。如果未提供此值,ESM 模拟将不包括默认导出。如果模拟的是 CommonJS 或内置模块,该设置将用作module.exports的值。如果未提供此值,CJS 和内置模拟将使用一个空对象作为module.exports的值。namedExports<Object> 一个可选对象,其键和值用于创建模拟模块的命名导出。如果模拟是 CommonJS 或内置模块,这些值会被复制到module.exports上。因此,如果一个模拟同时具有命名导出和非对象默认导出,当将其用作 CJS 或内置模块时,模拟将抛出异常。
- 返回:<MockModuleContext> 可用于操作模拟对象的对象。
此函数用于模拟 ECMAScript 模块、CommonJS 模块、JSON 模块和 Node.js 内置模块的导出。在模拟之前对原始模块的任何引用都不受影响。要启用模块模拟,必须使用 --experimental-test-module-mocks 命令行标志启动 Node.js。
【This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and
Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In
order to enable module mocking, Node.js must be started with the
--experimental-test-module-mocks command-line flag.】
以下示例演示了如何为模块创建模拟。
【The following example demonstrates how a mock is created for a module.】
test('mocks a builtin module in both module systems', async (t) => {
// Create a mock of 'node:readline' with a named export named 'fn', which
// does not exist in the original 'node:readline' module.
const mock = t.mock.module('node:readline', {
namedExports: { fn() { return 42; } },
});
let esmImpl = await import('node:readline');
let cjsImpl = require('node:readline');
// cursorTo() is an export of the original 'node:readline' module.
assert.strictEqual(esmImpl.cursorTo, undefined);
assert.strictEqual(cjsImpl.cursorTo, undefined);
assert.strictEqual(esmImpl.fn(), 42);
assert.strictEqual(cjsImpl.fn(), 42);
mock.restore();
// The mock is restored, so the original builtin module is returned.
esmImpl = await import('node:readline');
cjsImpl = require('node:readline');
assert.strictEqual(typeof esmImpl.cursorTo, 'function');
assert.strictEqual(typeof cjsImpl.cursorTo, 'function');
assert.strictEqual(esmImpl.fn, undefined);
assert.strictEqual(cjsImpl.fn, undefined);
});