Chakra UI V3 中 Jest 测试遇到 emotionSfp 函数错误的解决方案
2025-05-03 23:52:13作者:裴麒琰
问题背景
在使用 Chakra UI V3 和 Jest 29 进行测试时,开发者可能会遇到一个 TypeError 错误,提示 emotionSfp is not a function
。这个错误源于 Chakra UI 内部对 @emotion/is-prop-valid
模块的导入方式与 Jest 环境下的模块解析机制不兼容。
问题分析
错误发生在 Chakra UI 的 factory.tsx 文件中,具体是在尝试导入 @emotion/is-prop-valid
模块时。在 Jest 测试环境下,该模块被导出为一个包含 default 属性的对象,而不是直接导出函数本身。
核心问题点:
- Chakra UI 期望
@emotion/is-prop-valid
直接导出一个函数 - 但在 Jest 环境中,该模块被包装成了一个 ES 模块,函数位于 default 属性下
- 这导致 Chakra UI 尝试调用
emotionSfp
时失败,因为它实际上是一个对象而非函数
解决方案
临时解决方案
对于需要快速解决问题的开发者,可以采用以下步骤:
- 首先添加
@emotion/is-prop-valid
作为开发依赖 - 配置 Jest 的
moduleNameMapper
来重定向该模块 - 创建模拟文件来替代真实的模块
具体实现:
- 在
jest.config.js
中添加配置:
moduleNameMapper: {
'@emotion/is-prop-valid': '<rootDir>/test/__mocks__/emotion.js',
},
setupFilesAfterEnv: ['<rootDir>/test/setup.js'],
- 创建模拟文件
__mocks__/emotion.js
:
const isPropValid = '';
export default isPropValid;
- 在
test/setup.js
中实现完整的模拟逻辑:
jest.mock(
'@emotion/is-prop-valid',
() => {
const reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/;
return function (prop) {
return (
reactPropsRegex.test(prop) ||
(prop.charCodeAt(0) === 111 &&
prop.charCodeAt(1) === 110 &&
prop.charCodeAt(2) < 91)
);
};
},
{ esModule: true },
);
长期解决方案
虽然上述临时方案可以解决问题,但更理想的长期解决方案是:
- 等待 Chakra UI 官方修复此问题,更新对
@emotion/is-prop-valid
的导入方式 - 或者在自己的项目中创建一个补丁,修改 Chakra UI 的导入逻辑
技术原理
这个问题的本质是 CommonJS 和 ES 模块系统之间的兼容性问题。在 Node.js 环境中,模块系统正在从 CommonJS 向 ES Modules 过渡,这导致了一些兼容性问题。
@emotion/is-prop-valid
作为一个被广泛使用的工具库,为了兼容不同环境,采用了同时支持两种模块系统的打包方式。但在 Jest 测试环境下,这种双重导出机制有时会导致模块解析出现偏差。
最佳实践建议
- 保持 Jest 和相关测试依赖的最新版本
- 对于 UI 组件库的测试,确保正确配置了所有必要的模拟
- 定期检查项目依赖的兼容性矩阵
- 考虑使用
jest-emotion
等专门为 CSS-in-JS 库设计的 Jest 插件
总结
Chakra UI V3 与 Jest 测试环境下的 emotionSfp
函数错误是一个典型的模块系统兼容性问题。通过合理的模拟配置可以解决这个问题,但开发者需要理解其背后的原理,以便在类似问题出现时能够快速定位和解决。随着 JavaScript 生态系统的演进,这类问题有望在未来版本的库中得到根本解决。
登录后查看全文
热门项目推荐
- QQwen3-Next-80B-A3B-InstructQwen3-Next-80B-A3B-Instruct 是一款支持超长上下文(最高 256K tokens)、具备高效推理与卓越性能的指令微调大模型00
- QQwen3-Next-80B-A3B-ThinkingQwen3-Next-80B-A3B-Thinking 在复杂推理和强化学习任务中超越 30B–32B 同类模型,并在多项基准测试中优于 Gemini-2.5-Flash-Thinking00
GitCode-文心大模型-智源研究院AI应用开发大赛
GitCode&文心大模型&智源研究院强强联合,发起的AI应用开发大赛;总奖池8W,单人最高可得价值3W奖励。快来参加吧~0266cinatra
c++20实现的跨平台、header only、跨平台的高性能http库。C++00AI内容魔方
AI内容专区,汇集全球AI开源项目,集结模块、可组合的内容,致力于分享、交流。02- HHunyuan-MT-7B腾讯混元翻译模型主要支持33种语言间的互译,包括中国五种少数民族语言。00
GOT-OCR-2.0-hf
阶跃星辰StepFun推出的GOT-OCR-2.0-hf是一款强大的多语言OCR开源模型,支持从普通文档到复杂场景的文字识别。它能精准处理表格、图表、数学公式、几何图形甚至乐谱等特殊内容,输出结果可通过第三方工具渲染成多种格式。模型支持1024×1024高分辨率输入,具备多页批量处理、动态分块识别和交互式区域选择等创新功能,用户可通过坐标或颜色指定识别区域。基于Apache 2.0协议开源,提供Hugging Face演示和完整代码,适用于学术研究到工业应用的广泛场景,为OCR领域带来突破性解决方案。00- HHowToCook程序员在家做饭方法指南。Programmer's guide about how to cook at home (Chinese only).Dockerfile06
- PpathwayPathway is an open framework for high-throughput and low-latency real-time data processing.Python00
热门内容推荐
1 freeCodeCamp音乐播放器项目中的函数调用问题解析2 freeCodeCamp论坛排行榜项目中的错误日志规范要求3 freeCodeCamp猫照片应用教程中的HTML注释测试问题分析4 freeCodeCamp JavaScript高阶函数中的对象引用陷阱解析5 freeCodeCamp全栈开发课程中React实验项目的分类修正6 freeCodeCamp课程视频测验中的Tab键导航问题解析7 freeCodeCamp全栈开发课程中React组件导出方式的衔接问题分析8 freeCodeCamp英语课程视频测验选项与提示不匹配问题分析9 freeCodeCamp课程页面空白问题的技术分析与解决方案10 freeCodeCamp博客页面工作坊中的断言方法优化建议
最新内容推荐
项目优选
收起

OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
143
1.91 K

deepin linux kernel
C
22
6

Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
8
0

React Native鸿蒙化仓库
C++
192
273

🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
927
551

旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
421
392

openGauss kernel ~ openGauss is an open source relational database management system
C++
145
189

为非计算机科班出身 (例如财经类高校金融学院) 同学量身定制,新手友好,让学生以亲身实践开源开发的方式,学会使用计算机自动化自己的科研/创新工作。案例以量化投资为主线,涉及 Bash、Python、SQL、BI、AI 等全技术栈,培养面向未来的数智化人才 (如数据工程师、数据分析师、数据科学家、数据决策者、量化投资人)。
Jupyter Notebook
75
64

本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
344
1.3 K

Elasticsearch
国内Top1 elasticsearch搜索引擎框架es ORM框架,索引全自动智能托管,如丝般顺滑,与Mybatis-plus一致的API,屏蔽语言差异,开发者只需要会MySQL语法即可完成对Es的相关操作,零额外学习成本.底层采用RestHighLevelClient,兼具低码,易用,易拓展等特性,支持es独有的高亮,权重,分词,Geo,嵌套,父子类型等功能...
Java
36
8