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

React-scripts忽略.tsx后缀测试文件,如何配置使其识别运行?

解决React Scripts无法运行.tsx测试文件的问题

核心问题说明

react-scripts 会忽略自定义的 jest.config.js 文件,因此你之前添加的配置不会生效。同时,.test.ts 后缀不支持JSX语法,导致组件测试报错,必须使用 .test.tsx 后缀并让Jest正确识别它。

具体解决步骤

  1. 移除自定义jest.config.js,改用package.json配置
    在项目根目录的 package.json 中添加Jest配置(取代单独的配置文件):

    "jest": {
      "testMatch": [
        "**/__tests__/**/*.ts?(x)",
        "**/?(*.)+(spec|test).ts?(x)"
      ],
      "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "jsx",
        "json",
        "node"
      ],
      "testEnvironment": "jsdom"
    }
    
  2. 安装必要的类型依赖
    确保TypeScript相关的类型包已安装,否则TSX语法会无法被正确解析:

    npm install --save-dev @types/jest @types/react @types/react-dom
    

    若使用Yarn:

    yarn add --dev @types/jest @types/react @types/react-dom
    
  3. 检查tsconfig.json配置
    确保 tsconfig.json 中启用了JSX解析支持:

    • React 17+ 版本,设置 compilerOptions.jsx 为 "react-jsx"
    • React 16及以下版本,设置为 "react"
      同时确保测试文件被包含在编译范围内:
    "include": ["src/**/*", "src/**/*.test.tsx"]
    
  4. 升级react-scripts到最新版本
    旧版本的 react-scripts 对TSX测试的支持不完善,升级到最新版可解决多数兼容性问题:

    npm install react-scripts@latest
    

    若使用Yarn:

    yarn upgrade react-scripts@latest
    

验证

完成上述配置后,重新运行测试命令:

npm test

此时 .test.tsx 后缀的测试文件应该能被正常识别并运行,且组件测试的JSX语法报错也会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:17:37