Next.js中用emotion/styled+Jest测试组件遇意外Token错误
解决Jest测试@emotion/styled组件时的"Unexpected Token"报错
问题场景
测试使用@emotion/styled编写的NavBar组件时,Jest抛出"Jest encountered an unexpected token"错误,组件核心代码如下:
import styled from "@emotion/styled"; const StyledNavBar = styled.div` position: fixed; top: 0; width: calc(100% + 1rem); `; const NavBar = (props) => {};
当前依赖版本与环境:
{"dependencies": {"@emotion-icons/material": "^3.14.0","@emotion-icons/material-outlined": "^3.14.0","@emotion-icons/material-rounded": "^3.14.0","@emotion/react": "^11.9.3","@emotion/styled": "^11.9.3","@next/bundle-analyzer": "^13.4.19","@next/env": "^13.5.6","jest-emotion": "^11.0.0","next": "13.4.12","react": "18.2.0","react-dom": "18.2.0"},"devDependencies": {"@emotion/jest": "^11.11.0","@testing-library/jest-dom": "^6.2.0","@testing-library/react": "^14.1.2","jest": "^29.7.0","jest-environment-jsdom": "^29.7.0","jest-styled-components": "^7.2.0"}}
Node版本为v20.9.0,此前调整过Jest配置但未解决问题。
可行解决方案
1. 用Babel转译Emotion语法
Jest默认无法解析styled.div后的模板字符串样式,需通过babel-jest配合Emotion的Babel插件处理:
首先安装必要依赖:
npm install --save-dev @babel/preset-env @babel/preset-react @emotion/babel-plugin babel-jest
然后在项目根目录创建或修改babel.config.js:
module.exports = { presets: [ '@babel/preset-env', ['@babel/preset-react', { runtime: 'automatic' }] ], plugins: ['@emotion/babel-plugin'] };
2. 修正Jest配置
修改jest.config.js(或jest.config.mjs),确保以下配置项正确:
module.exports = { testEnvironment: 'jest-environment-jsdom', transform: { '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest' }, moduleNameMapper: { '^@emotion/react$': require.resolve('@emotion/react'), '^@emotion/styled$': require.resolve('@emotion/styled') }, setupFilesAfterEnv: [ '@testing-library/jest-dom', '@emotion/jest' ] };
transform指定用babel-jest处理JS/JSX文件,保证Emotion语法被转译moduleNameMapper避免Jest解析Emotion包时出现路径冲突setupFilesAfterEnv加载测试所需的辅助库,@emotion/jest用于样式断言
3. 适配Next.js 13配置
由于使用Next.js 13,需注意兼容性:
- 若使用App Router,可将测试文件放在
app目录外,或在Jest配置中添加testPathIgnorePatterns: ['<rootDir>/app/'] - 若启用Next.js的SWC编译器,需在
next.config.js中禁用SWC的Jest集成,改用Babel处理:
module.exports = { experimental: { swcPlugins: [['@emotion/swc-plugin', {}]] }, jest: { transform: {} // 禁用Next.js默认SWC转译,改用babel-jest } };
4. 清理缓存并重新测试
执行命令清理Jest缓存,避免旧配置干扰:
npx jest --clearCache
随后重新运行测试:
npm test
验证要点
- 确保
@emotion/babel-plugin与@emotion/react、@emotion/styled版本均为11.x系列,避免版本不匹配 - 测试文件扩展名需为
.jsx或.tsx,确保被transform规则覆盖 - 使用TypeScript时,需添加
@babel/preset-typescript到Babel预设,并在Jest配置中处理.ts/.tsx文件
内容的提问来源于stack exchange,提问作者kevin parra
相关产品推荐
相关产品推荐

