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

React项目Jest测试报错:ReferenceError: require is not defined

React测试使用ES6导入时报错"ReferenceError: require is not defined"

问题详情

首次尝试为React应用编写测试,使用ES6导入语法时所有测试套件均报错:Test suite failed to run ReferenceError: require is not defined。希望保留ES6导入方案,相关代码与配置如下:

测试代码

import React from 'react';
import { render, screen } from '@testing-library/react';
import App from '../App';

test.todo('test');
describe('App', () => {
  it('should render application', () => {
    render(<App />);
    const todayButton = screen.getByText(/today/i);
    expect(todayButton).toBeInTheDocument();
  });
});

jest.config.js配置

module.exports = {
  testEnvironment: 'jest-environment-jsdom',
  extensionsToTreatAsEsm: ['.jsx'],
  transform: {
    '\.[j]sx?$': 'babel-jest',
    '\.css$': 'some-css-transformer',
  },
  moduleFileExtensions: ['jsx', 'js', 'json', 'node'],
};

package.json配置

{
  "name": "react-calendar",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "webpack serve --mode development --open",
    "build": "webpack --mode=production",
    "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.7.5",
    "@babel/core": "^7.7.5",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/preset-env": "^7.7.6",
    "@babel/preset-react": "^7.7.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.0.0",
    "babel-jest": "^29.5.0",
    "babel-loader": "^8.0.6",
    "cross-env": "^7.0.3",
    "jest": "^29.5.0",
    "jest-environment-jsdom": "^29.5.0"
  }
}

解决方案

问题源于Jest处理ES模块(ESM)与CommonJS的冲突,结合你的配置做以下调整:

  1. 将jest.config.js转为ESM格式
    由于package.json中设置了"type": "module",配置文件不能再用CommonJS的module.exports,需改为ES模块导出:
export default {
  testEnvironment: 'jest-environment-jsdom',
  extensionsToTreatAsEsm: ['.js', '.jsx'],
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest',
    '\\.css$': 'some-css-transformer',
  },
  moduleFileExtensions: ['jsx', 'js', 'json', 'node'],
  // 新增:确保Jest正确解析ESM导入的文件扩展名
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1'
  },
  // 新增:避免忽略需要转译的第三方ESM模块
  transformIgnorePatterns: [
    '/node_modules/(?!@testing-library/react)'
  ]
};
  1. 完善Babel配置
    创建或修改babel.config.json,确保不转换ES模块语法,让Jest自行处理:
{
  "presets": [
    ["@babel/preset-env", { "modules": false }],
    "@babel/preset-react"
  ],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}
  1. 更新测试脚本
    添加--no-cache避免缓存导致的配置不生效问题:
"scripts": {
  "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --no-cache"
}
  1. 明确文件扩展名
    ESM模式下导入文件必须指定完整扩展名,确保测试代码和项目文件的导入路径都包含.js或.jsx。

验证

执行npm test,测试套件应能正常运行,不再出现require is not defined报错。


内容的提问来源于stack exchange,提问作者Test Space

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:03:32