mock.module(specifier[, options])


稳定性: 1.0 - 早期开发

  • specifier <string> | <URL> 用于标识要模拟的模块的字符串。
  • options <Object> 模拟模块的可选配置选项。支持以下属性:
    • cache <boolean> 如果为 false,每次调用 require()import() 都会生成一个新的模拟模块。如果为 true,后续调用将返回相同的模块模拟,并且该模拟模块会被插入到 CommonJS 缓存中。默认值: false。
    • exports <Object> 可选的模拟导出。如果提供了 default 属性,则将其用作模拟模块的默认导出。所有其他自身可枚举属性将用作命名导出。此选项不能与 defaultExportnamedExports 一起使用。
      • 如果模拟的是 CommonJS 或内置模块,则 exports.default 用作 module.exports 的值。
      • 如果未为 CommonJS 或内置模拟提供 exports.defaultmodule.exports 默认为一个空对象。
      • 如果命名导出提供了非对象的默认导出,当作为 CommonJS 或内置模块使用时,mock 会抛出异常。
    • defaultExport <any> 用于作为模拟模块默认导出的可选值。如果未提供此值,ESM 模拟不会包含默认导出。如果模拟的是 CommonJS 或内置模块,则此设置用作 module.exports 的值。如果未提供此值,CJS 和内置模拟将使用空对象作为 module.exports 的值。**此选项不能与 options.exports 一起使用。**此选项已弃用,并将在以后的版本中移除。建议使用 options.exports.default
    • namedExports <Object> 一个可选对象,其键和值用于创建模拟模块的命名导出。如果模拟模块是 CommonJS 模块或内置模块,这些值会被复制到 module.exports 上。因此,如果一个模拟模块同时具有命名导出和非对象的默认导出,当作为 CJS 或内置模块使用时,模拟模块将抛出异常。**此选项不能与 options.exports 一起使用。**此选项已被弃用,并将在以后的版本中移除。建议使用 options.exports
  • 返回:<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.

注意模块自定义钩子 通过 同步 API 注册,用于解析提供给 mock.modulespecifier 的效果。通过 异步 API 注册的自定义钩子目前会被忽略(因为测试运行器的加载器是同步的,并且 node 不支持多链 / 跨链加载)。

以下示例演示了如何为模块创建模拟。

🌐 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 'foo', which
  // does not exist in the original 'node:readline' module.
  const mock = t.mock.module('node:readline', {
    exports: { foo: () => 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);
});