React 17 + Jest测试报错:Unexpected token 'export' 求解决方案
问题:Jest执行单元测试时出现Unexpected token 'export'错误
环境
React 17、Jest 29.7.0、Babel 7.24.0
错误信息
执行yarn test(带--coverage参数)时触发如下错误:
Error: Test suite failed to run Jest encountered an unexpected token..... Details: <root dir>/node_modules/cheerio/dist/browser/index.js:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { contains, merge } from './static.js'; ^^^^^^ SyntaxError: Unexpected token 'export' 3 | import { configure } from 'enzyme'; 4 | > 5 | global.ResizeObserver = jest.fn().mockImplementation(() => ({ | ^ 6 | observe: jest.fn(), 7 | unobserve: jest.fn(), 8 | disconnect: jest.fn(), at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14) at Object.<anonymous> (node_modules/enzyme/build/Utils.js:93:16) at Object.<anonymous> (node_modules/enzyme/build/ReactWrapper.js:33:14) at Object.<anonymous> (node_modules/enzyme/build/index.js:3:21) at Object.<anonymous> (node_modules/@wojtekmaj/enzyme-adapter-react-17/build/ReactSeventeenAdapter.js:11:15) at Object.<anonymous> (node_modules/@wojtekmaj/enzyme-adapter-react-17/build/index.js:3:18) at Object.<anonymous> (test/setup.js:5:50)
现有配置
Jest.config.js
module.exports = { testEnvironment: 'jsdom', setupFiles: ["./test/setup.js"], testURL: "http://localhost/", moduleNameMapper: { "^.+\\.(less|css)$": "babel-jest", }, transformIgnorePatterns: [ "/node_modules/?!(cheerio|jest-runtime|enzyme|@wojtekmaj)" ], testTimeout: 30000, };
setup.js
import 'raf/polyfill'; import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; import { configure } from 'enzyme'; global.ResizeObserver = jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), })) global.CSS = { escape: (str) => str, }; configure({ adapter: new Adapter(), });
尝试调整transformIgnorePatterns的正则表达式但无效,寻求正确配置或解决方法。
解决方法
1. 修正transformIgnorePatterns正则表达式
原正则匹配范围存在问题,导致Jest无法正确识别需要转译的模块。将配置修改为:
transformIgnorePatterns: [ 'node_modules/(?!(cheerio|enzyme|@wojtekmaj/enzyme-adapter-react-17)/)' ]
说明:明确指定需要转译的包(包括cheerio、enzyme以及对应的适配器),确保Jest对这些包的ES模块代码进行转译。
2. 验证Babel配置正确性
确保项目根目录的babel.config.js(或.babelrc)包含测试环境所需的预设:
module.exports = { presets: [ ['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-react' ] };
该配置会将ES模块语法转译为Jest兼容的CommonJS格式。
3. 升级兼容依赖版本
检查enzyme和@wojtekmaj/enzyme-adapter-react-17的版本是否适配Jest 29,执行以下命令更新到最新兼容版本:
yarn upgrade @wojtekmaj/enzyme-adapter-react-17 enzyme
4. 调整setup.js的导入方式(备选)
若上述方法无效,尝试将setup.js中的import替换为require,避免转译问题:
require('raf/polyfill'); const Adapter = require('@wojtekmaj/enzyme-adapter-react-17'); const { configure } = require('enzyme'); global.ResizeObserver = jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), })) global.CSS = { escape: (str) => str, }; configure({ adapter: new Adapter(), });
内容的提问来源于stack exchange,提问作者Mellacheruvu Janakirama Sarma
相关产品推荐
相关产品推荐

