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

Vite React项目运行Jest测试时遇JSX标志错误求助

解决Vite React项目Jest测试中"Cannot use JSX unless the '--jsx' flag is provided"错误

以下是几个可行的解决方法,按优先级尝试:

1. 为测试环境单独创建TS配置文件

主tsconfig.json中的composite、isolatedModules、module: ESNext等配置是为Vite打包优化的,和Jest的CommonJS模块环境不兼容。创建tsconfig.test.json:

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

然后修改jest.config.mjs中ts-jest的配置指向这个文件:

export default {
  // ...其他配置
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.test.json', // 替换为测试用TS配置
    },
  },
};

2. 直接在Jest配置中强制指定JSX选项

如果不想单独创建配置文件,可在jest.config.mjs的ts-jest全局配置中直接指定jsx选项,强制覆盖TSConfig的设置:

export default {
  // ...其他配置
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.json',
      jsx: 'react-jsx' // 直接设置JSX模式
    },
  },
};

3. 确认依赖安装完整

确保已安装所有必要的测试依赖:

npm install --save-dev ts-jest @types/jest @types/react @types/react-dom jest-environment-jsdom

4. 检查测试文件扩展名

如果测试文件中使用了JSX语法,必须使用.tsx作为文件后缀,不能用.ts,否则TypeScript不会识别并处理JSX代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:02:05