React Jest测试报错:无法找到@emotion/styled模块求助
问题原因及解决方案
报错Cannot find module '@emotion/styled' from 'node_modules/@mui/styled-engine/node/index.js'的核心原因主要有两个:
1. 缺少Emotion相关依赖
MUI v5默认依赖Emotion作为样式引擎,但你的项目可能未安装必要的Emotion核心包。
解决方法:
安装@emotion/react和@emotion/styled:
npm install @emotion/react @emotion/styled --save # 或使用yarn yarn add @emotion/react @emotion/styled
2. Jest未转译MUI/Emotion相关包
Jest默认不转译node_modules中的代码,但@mui和@emotion的部分包使用了未编译的ES模块,导致测试时无法识别。你的transformIgnorePatterns仅包含@autofiy相关包,未覆盖MUI和Emotion。
解决方法:
修改jest.config.js中的transformIgnorePatterns,添加@mui、@emotion到例外列表:
transformIgnorePatterns: [ "/node_modules/(?![@autofiy/autofiyable|@autofiy/property|@mui|@emotion]).+\\.js$", "/node_modules/(?![@autofiy/autofiyable|@autofiy/property|@mui|@emotion]).+\\.ts$", "/node_modules/(?![@autofiy/autofiyable|@autofiy/property|@mui|@emotion]).+\\.tsx$", ],
同时,你的transform配置存在babel-jest和ts-jest处理同类型文件的冲突,建议统一使用ts-jest(已配置preset: "ts-jest"),修改transform为:
transform: { "^.+\\.(ts|tsx)?$": "ts-jest", },
验证修复
重新运行测试脚本:
npm run test
内容的提问来源于stack exchange,提问作者taaniel
相关产品推荐
相关产品推荐

