使用@mui/icons-material测试React组件时,如何解决‘Element type is invalid’错误?
解决React组件测试中"Element type is invalid"错误
错误原因
测试环境中,传递给LabelIconButton的PowerSettingsNew图标组件未被正确解析为有效的React组件,或者Mock的LabelIconButton组件处理props的方式存在问题,导致React无法识别组件类型,抛出"Element type is invalid"错误。
解决方案
1. 正确Mock MUI图标组件
在测试文件中添加对PowerSettingsNew图标的Mock,确保它是一个可渲染的React组件:
// 单个图标Mock jest.mock('@mui/icons-material/PowerSettingsNew', () => { return () => <span>MockPowerIcon</span>; }); // 或批量Mock整个图标模块 jest.mock('@mui/icons-material', () => ({ PowerSettingsNew: () => <span>MockPowerIcon</span>, }));
2. 优化LabelIconButton的Mock实现
如果Mock的组件需要处理传入的icon props,改用标准的React组件函数形式Mock,避免潜在的渲染问题:
jest.mock('../LabelIconButton', () => { const MockLabelIconButton = ({ title, icon: Icon }) => { return ( <div> {Icon && <Icon />} <span>{title}</span> </div> ); }; return MockLabelIconButton; });
3. 调整断言逻辑匹配实际调用参数
React调用组件时,第二个参数可能包含内部上下文属性(如key、ref),不一定是空对象。使用expect.objectContaining和expect.anything()进行模糊匹配:
it('appelle le composant LabelIconButton avec les bonnes props', () => { render(<LabelIconButtonDisconnection/>); expect(LabelIconButton).toHaveBeenCalledWith( expect.objectContaining({ title: 'déconnexion', icon: PowerSettingsNew, }), expect.anything() ); });
总结
优先结合方案1和方案3解决问题:先Mock图标确保它是有效的可渲染组件,再调整断言逻辑匹配React组件的实际调用参数,即可解决"Element type is invalid"错误。
内容的提问来源于stack exchange,提问作者Malaury Boudon
相关产品推荐
相关产品推荐

