React项目Jest测试报错:无法解析JSX文件,求解决方案
环境配置信息
package.json中的devDependencies
"devDependencies": { "@babel/core": "^7.20.5", "@babel/preset-env": "^7.19.4", "@babel/preset-react": "^7.18.6", "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "babel-jest": "^29.3.1", "babel-plugin-transform-class-properties": "^6.24.1", "jest": "^27.5.1", "jest-dom": "^4.0.0", "react-test-renderer": "^18.2.0" }
babel.config.js配置
module.exports = { presets: [ ["@babel/preset-env"], ["@babel/preset-react"] ], };
报错信息
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, refer to Jest官方文档相关章节配置。
• If you are trying to use TypeScript, refer to Jest官方文档相关章节配置。
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.You'll find more details and examples of these config options in Jest官方文档。
可行解决方案
1. 修复Jest与babel-jest版本不匹配问题
当前jest版本为27.5.1,babel-jest为29.3.1,版本差异过大导致兼容冲突。统一两者版本:
- 卸载现有版本:
npm uninstall jest babel-jest
- 安装同版本的jest和babel-jest(推荐27.x系列,适配现有babel版本):
npm install --save-dev jest@27.5.1 babel-jest@27.5.1
2. 添加Jest配置文件
在项目根目录创建jest.config.js,配置核心参数:
module.exports = { testEnvironment: "jsdom", transform: { "^.+\\.(js|jsx)$": "babel-jest", }, transformIgnorePatterns: [ "/node_modules/(?!(需要转译的依赖包名)/)", ], moduleNameMapper: { "\\.(css|less|scss|sass)$": "identity-obj-proxy", }, setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"], };
说明:
testEnvironment: "jsdom":适配React的DOM运行环境,React 18+必须配置transform:指定用babel-jest转译所有js/jsx文件transformIgnorePatterns:若第三方依赖使用未转译的ES语法,将其从忽略列表排除(替换需要转译的依赖包名为实际包名,如react-router-dom)moduleNameMapper:Mock样式文件,避免Jest解析css等非JS资源报错setupFilesAfterEnv:自动引入@testing-library/jest-dom的断言方法,无需在测试文件中手动导入
3. 优化Babel配置(可选)
若项目使用类组件的class properties语法,更新babel.config.js:
module.exports = { presets: [ ["@babel/preset-env", { targets: { node: "current" } }], ["@babel/preset-react", { runtime: "automatic" }] ], plugins: ["babel-plugin-transform-class-properties"] };
添加targets: { node: "current" }让Babel针对当前Node版本转译;runtime: "automatic"可免去测试文件中手动导入React的步骤。
4. 清理缓存并重新测试
执行命令清理Jest缓存,避免旧缓存干扰:
npx jest --clearCache
然后重新运行测试:
npx jest
内容的提问来源于stack exchange,提问作者ax3l Garcia

