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

使用react-router-dom时Jest测试出现模块版本冲突错误求助

解决React Router与Jest的CommonJS/ES模块冲突问题

错误场景

运行Jest测试时出现模块加载冲突错误:

FAIL client/__test__/index.test.tsx
  ● Test suite failed to run

    You are loading the CommonJS build of React Router on a page that is already running the ES modules build, so things won't work right.

      3 | import Error404 from './components/Error/404';
      4 | import Error500 from './components/Error/500';
    > 5 | import { Switch } from 'react-router-dom';
        | ^
      6 |
      7 | import ErrorBoundary from './components/Error/ErrorBoundary';

问题原因

测试环境中同时加载了react-router-dom的CommonJS和ES模块版本,导致模块系统冲突。Jest默认忽略node_modules目录的代码转换,而react-router-dom的ES模块代码在未被转换的情况下,会和项目中已启用的ESM配置产生冲突。

解决方案

1. 修正Jest的转换忽略规则

更新jest.config.js中的transformIgnorePatterns,确保react-router-dom及其依赖的ES模块包被ts-jest转换:

module.exports = {
  roots: ['<rootDir>/client/__test__'],
  transform: {
    '^.+\\.(ts)x?$': ['ts-jest', {
      useESM: true,
      tsconfig: './client/tsconfig.test.json',
      diagnostics: false,
    }]
  },
  testRegex: '(client/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  // 关键:让这些包不被忽略转换
  transformIgnorePatterns: ['node_modules/(?!react-router-dom|@remix-run/react|@remix-run/router)']
};

注:如果使用react-router-dom v5,只需保留react-router-dom|react-router即可。

2. 统一TS-Jest的ESM配置

移除globals中的重复ts-jest配置,将所有ts-jest选项集中到transform字段内,避免配置不一致导致的ESM模式冲突。

3. 确保测试TS配置支持ESM

检查client/tsconfig.test.json(如果不存在则创建),添加ESM相关配置:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "module": "ESNext",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "NodeNext"
  }
}

4. PNPM用户额外配置

如果使用pnpm,在package.json中添加overrides确保加载正确的模块入口:

"pnpm": {
  "overrides": {
    "react-router-dom": {
      "main": "./dist/react-router-dom.development.js",
      "module": "./dist/react-router-dom.development.js"
    }
  }
}

验证

重新运行Jest测试,确认模块冲突错误消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:05:13