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

React TypeScript项目中jest.config.ts配合react-scripts test报错求助

解决React TypeScript项目中Jest配置的三类错误

1. 无效testPattern错误

问题根源:react-scripts test 不支持直接通过 -- --config 传递自定义配置文件,命令行参数被误解析为测试文件匹配模式。

解决方案:

  • 修改package.json中的test脚本,通过环境变量指定配置文件:
"scripts": {
  "test": "JEST_CONFIG=jest.config.ts react-scripts test"
}
  • 确保TypeScript配置文件能被正确解析,在package.json中补充基础jest配置:
"jest": {
  "preset": "ts-jest",
  "globals": {
    "ts-jest": {
      "tsconfig": "tsconfig.json"
    }
  }
}

2. Axios模块import语法错误

问题根源:Axios v1.x默认使用ES模块语法,Jest默认以CommonJS模式运行,且react-scripts默认的transform配置会忽略node_modules下的文件,导致Axios的import语句无法被转译。

解决方案:

  • 调整jest.config.ts中的transformIgnorePatterns,确保Axios被包含在转译范围内,同时继承react-scripts的默认配置避免冲突:
import { Config } from "jest";

const config: Config = {
  transformIgnorePatterns: [
    "/node_modules/(?!axios|@horat1us/detect-ad-block)/", // 加入需要转译的ES模块依赖
  ],
  verbose: true,
  preset: "react-scripts/jest",
};

export default config;
  • 或者直接mock Axios规避转译问题,在src/setupTests.ts中添加:
jest.mock('axios', () => ({
  default: jest.fn(() => Promise.resolve({ data: {} })),
  AxiosResponse: jest.fn(),
}));

3. --isolatedModules编译失败错误

问题根源:TypeScript的--isolatedModules选项要求所有文件必须是ES模块(包含import/export语句),classes.test.ts无任何导入导出,被识别为全局脚本。

解决方案:

  • 在classes.test.ts末尾添加空导出语句,将其转为模块:
describe("function: contains", (): void => {
  // 测试代码
});

export {};
  • 或者添加必要的测试库导入:
import '@testing-library/jest-dom';

describe("function: contains", (): void => {
  // 测试代码
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:13:14