You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 11:55:33