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

React+TypeScript测试报错:未设置--jsx等问题求助

解决React+TypeScript组件测试的三类TS错误

错误1 & 2:TS6142/TS17004 未设置--jsx标志

这两个错误本质是TypeScript未正确识别JSX语法,需调整TS编译配置并确保Jest适配:

  1. 修改根目录tsconfig.json
    在compilerOptions中指定正确的JSX编译模式,React 17+推荐用react-jsx:

    {
      "compilerOptions": {
        // 其他配置保留
        "jsx": "react-jsx",
        "esModuleInterop": true,
        "module": "ESNext",
        "moduleResolution": "NodeNext"
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules"]
    }
    
  2. 为测试环境单独配置TS(可选但更稳妥)
    创建tsconfig.test.json继承主配置,适配Jest的CommonJS模块需求:

    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "jsx": "react-jsx",
        "module": "CommonJS"
      },
      "include": ["src/**/*.test.tsx", "src/**/*.test.ts", "setupTests.ts"]
    }
    

    然后在jest.config.ts中指定使用该测试配置:

    export default {
      // 现有配置保留
      preset: "ts-jest",
      transform: {
        '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.test.json' }]
      }
    }
    

错误3:TS2339 toBeInTheDocument不存在

该错误是因为未引入@testing-library/jest-dom的匹配器和类型定义:

  1. 安装依赖(未安装时执行)

    npm install --save-dev @testing-library/jest-dom
    
  2. 在setupTests.ts中导入匹配器
    确保setupTests.ts内容如下:

    import '@testing-library/jest-dom';
    
  3. 让TypeScript识别类型
    在tsconfig.json的compilerOptions中添加类型引用:

    {
      "compilerOptions": {
        // 其他配置保留
        "types": ["jest", "@testing-library/jest-dom"]
      }
    }
    

额外检查项

  • 测试文件导入组件时,去掉.tsx后缀:将import {Button} from "./Button.tsx";改为import {Button} from "./Button";,TypeScript会自动识别扩展名。
  • 重启IDE和测试服务,确保配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:35:04