You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jest.mock方法时出现ReferenceError错误求助

解决Jest ES模块环境下jest.mock()报ReferenceError: require is not defined的问题

问题原因

你的项目在package.json中设置了"type": "module",启用了ES模块规范,但默认的jest.mock()是为CommonJS模块设计的,它生成的Mock代码会依赖require函数——而ES模块环境中并没有这个函数,因此抛出该错误。

解决方案

1. 配置Jest支持ES模块

创建jest.config.mjs文件(因为项目是ES模块,所以用.mjs后缀),添加以下配置:

export default {
  transform: {}, // 禁用默认的CommonJS转换,保留ES模块格式
  moduleFileExtensions: ['js', 'mjs'], // 支持ES模块文件后缀
  testEnvironment: 'node',
};

2. 使用ES模块兼容的Mock API

替换原来的jest.mock(),改用Jest提供的jest.unstable_mockModule()(Jest 28+版本支持),这是专门为ES模块设计的Mock方法。同时注意模块导入必须在Mock之后进行,且要配合async/await:

修改后的测试文件代码:

import {jest, describe, test, expect} from '@jest/globals';

// 异步Mock ES模块
await jest.unstable_mockModule('../math.js', () => ({
  add: jest.fn(),
  subtract: jest.fn(),
}));

// 在Mock完成后导入目标模块
const mathlib = await import('../mathlib');
const math = await import('../math');

describe('math', () => {
  test('adds numbers', () => {
    mathlib.doAdd(1, 2);
    expect(math.add).toHaveBeenCalledWith(1, 2);
  });
});

3. 保留必要的Node.js实验标志

你的package.json中的测试脚本已经添加了--experimental-vm-modules,这个标志是Node.js运行ES模块测试必须的,无需修改:

"scripts": {
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}

验证运行

直接执行npm test,此时Jest会正确Mock ES模块,不再抛出require is not defined的错误。

内容的提问来源于stack exchange,提问作者Rakesh K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:55:19