React+TypeScript测试报错:未设置--jsx等问题求助
解决React+TypeScript组件测试的三类TS错误
错误1 & 2:TS6142/TS17004 未设置--jsx标志
这两个错误本质是TypeScript未正确识别JSX语法,需调整TS编译配置并确保Jest适配:
修改根目录
tsconfig.json
在compilerOptions中指定正确的JSX编译模式,React 17+推荐用react-jsx:{ "compilerOptions": { // 其他配置保留 "jsx": "react-jsx", "esModuleInterop": true, "module": "ESNext", "moduleResolution": "NodeNext" }, "include": ["src/**/*"], "exclude": ["node_modules"] }为测试环境单独配置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的匹配器和类型定义:
安装依赖(未安装时执行)
npm install --save-dev @testing-library/jest-dom在setupTests.ts中导入匹配器
确保setupTests.ts内容如下:import '@testing-library/jest-dom';让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
相关产品推荐
相关产品推荐

