Chakra UI V3 中 Jest 测试遇到 emotionSfp 函数错误的解决方案
2025-05-03 04:16:37作者:裴麒琰
问题背景
在使用 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 生态系统的演进,这类问题有望在未来版本的库中得到根本解决。
登录后查看全文
热门项目推荐
AutoGLM-Phone-9BAutoGLM-Phone-9B是基于AutoGLM构建的移动智能助手框架,依托多模态感知理解手机屏幕并执行自动化操作。Jinja00
Kimi-K2-ThinkingKimi K2 Thinking 是最新、性能最强的开源思维模型。从 Kimi K2 开始,我们将其打造为能够逐步推理并动态调用工具的思维智能体。通过显著提升多步推理深度,并在 200–300 次连续调用中保持稳定的工具使用能力,它在 Humanity's Last Exam (HLE)、BrowseComp 等基准测试中树立了新的技术标杆。同时,K2 Thinking 是原生 INT4 量化模型,具备 256k 上下文窗口,实现了推理延迟和 GPU 内存占用的无损降低。Python00
GLM-4.6V-FP8GLM-4.6V-FP8是GLM-V系列开源模型,支持128K上下文窗口,融合原生多模态函数调用能力,实现从视觉感知到执行的闭环。具备文档理解、图文生成、前端重构等功能,适用于云集群与本地部署,在同类参数规模中视觉理解性能领先。Jinja00
HunyuanOCRHunyuanOCR 是基于混元原生多模态架构打造的领先端到端 OCR 专家级视觉语言模型。它采用仅 10 亿参数的轻量化设计,在业界多项基准测试中取得了当前最佳性能。该模型不仅精通复杂多语言文档解析,还在文本检测与识别、开放域信息抽取、视频字幕提取及图片翻译等实际应用场景中表现卓越。00
GLM-ASR-Nano-2512GLM-ASR-Nano-2512 是一款稳健的开源语音识别模型,参数规模为 15 亿。该模型专为应对真实场景的复杂性而设计,在保持紧凑体量的同时,多项基准测试表现优于 OpenAI Whisper V3。Python00
GLM-TTSGLM-TTS 是一款基于大语言模型的高质量文本转语音(TTS)合成系统,支持零样本语音克隆和流式推理。该系统采用两阶段架构,结合了用于语音 token 生成的大语言模型(LLM)和用于波形合成的流匹配(Flow Matching)模型。 通过引入多奖励强化学习框架,GLM-TTS 显著提升了合成语音的表现力,相比传统 TTS 系统实现了更自然的情感控制。Python00
Spark-Formalizer-X1-7BSpark-Formalizer 是由科大讯飞团队开发的专用大型语言模型,专注于数学自动形式化任务。该模型擅长将自然语言数学问题转化为精确的 Lean4 形式化语句,在形式化语句生成方面达到了业界领先水平。Python00
最新内容推荐
STM32到GD32项目移植完全指南:从兼容性到实战技巧 JDK 8u381 Windows x64 安装包:企业级Java开发环境的完美选择 开源电子设计自动化利器:KiCad EDA全方位使用指南 Python案例资源下载 - 从入门到精通的完整项目代码合集 Python开发者的macOS终极指南:VSCode安装配置全攻略 网页设计期末大作业资源包 - 一站式解决方案助力高效完成项目 昆仑通态MCGS与台达VFD-M变频器通讯程序详解:工业自动化控制完美解决方案 STDF-View解析查看软件:半导体测试数据分析的终极工具指南 MQTT 3.1.1协议中文版文档:物联网开发者的必备技术指南 Jetson TX2开发板官方资源完全指南:从入门到精通
项目优选
收起
deepin linux kernel
C
24
9
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
9
1
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
64
19
暂无简介
Dart
671
155
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
660
309
Ascend Extension for PyTorch
Python
220
236
仓颉编译器源码及 cjdb 调试工具。
C++
134
867
喝着茶写代码!最易用的自托管一站式代码托管平台,包含Git托管,代码审查,团队协作,软件包和CI/CD。
Go
23
0
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
392
3.84 K
React Native鸿蒙化仓库
JavaScript
259
322