Jest解析React组件中HTML标签失败,如何配置Babel/Jest解决?
Ah, that classic "Unexpected token" error when Jest hits JSX—let’s get this sorted out. The issue here is that Jest isn’t properly using Babel to transpile your JSX syntax into plain JavaScript that Node can understand, even though you’ve got the right presets installed. Here’s how to fix it step by step:
1. Update Your Babel Configuration
First, make sure your .babelrc targets the Node environment (since Jest runs in Node) and includes all necessary presets/plugins:
{ "presets": [ ["@babel/preset-env", { "targets": { "node": "current" } }], "@babel/preset-react" ], "plugins": [ "@babel/plugin-proposal-class-properties", "@babel/plugin-syntax-dynamic-import" ] }
The @babel/preset-env with node: current ensures Babel generates code compatible with your current Node version, which Jest relies on. The @babel/preset-react takes care of converting JSX to React.createElement calls that Node can parse.
2. Add Transform Rules to Jest Configuration
Tell Jest explicitly to use babel-jest for processing .js and .jsx files. Update the jest section in your package.json:
"jest": { "verbose": true, "collectCoverage": true, "roots": ["<rootDir>/resources/js/"], "testRegex": "tests/.*.test.js$", "moduleDirectories": ["resources/js/", "node_modules"], "moduleNameMapper": { "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "__mocks__/fileMock.js", "\\.(css|scss)$": "__mocks__/styleMock.js" }, "transform": { "^.+\\.(js|jsx)$": "babel-jest" } }
This transform rule ensures any JS/JSX file gets passed through Babel before Jest runs it—this is the key step that was likely missing, causing Jest to choke on JSX tags like <div>.
3. Clear Jest’s Cache
Jest caches transpiled files, so even after updating configs, old cached code might still cause issues. Run this command to clear the cache:
npx jest --clearCache
4. Double-Check Paths and File Extensions
Make sure your BlogEditor import path is correct relative to your test file. Since your roots point to <rootDir>/resources/js/, confirm that ../../containers/BlogEditor/BlogEditor resolves to the actual component file (and that the component uses .js or .jsx as its extension—Jest should handle both, but it’s worth verifying).
5. Reinstall Dependencies (If Needed)
If you’re still seeing issues, there might be a version conflict or corrupted install. Delete your node_modules folder and lock file (package-lock.json or yarn.lock), then re-install:
rm -rf node_modules package-lock.json npm install
After following these steps, re-run your tests—Jest should now properly transpile your JSX and stop throwing that unexpected token error.
内容的提问来源于stack exchange,提问作者Anadi Misra

