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

使用svgr渲染SVG时React.createElement类型无效测试报错求助

解决单元测试中SVGR渲染SVG的"React.createElement: type is invalid"报错

这个问题核心是单元测试环境(比如Jest)没有配置SVGR来将SVG转换为React组件,导致你导入的SVG不是合法的React元素类型,传入Icon组件后触发报错。以下是具体解决方案:

1. 配置Jest处理SVG为React组件

方案一:使用@svgr/jest转换器

安装依赖:

npm install --save-dev @svgr/jest

在jest.config.js中添加SVG的转换规则:

module.exports = {
  // 保留你已有的其他配置
  transform: {
    '^.+\\.jsx?$': 'babel-jest', // 原有JS/JSX处理
    '^.+\\.svg$': '@svgr/jest', // 添加SVG转换
  },
};

方案二:使用babel-plugin-inline-react-svg

安装依赖:

npm install --save-dev babel-plugin-inline-react-svg

在你的Babel配置文件(.babelrc或babel.config.js)中添加插件:

{
  "presets": ["@babel/preset-react", "@babel/preset-env"], // 保留你已有的presets
  "plugins": ["inline-react-svg"]
}

如果用TypeScript,还需要在src/types/svg.d.ts(或其他类型声明文件)中添加类型定义,避免TS报错:

declare module '*.svg' {
  import React from 'react';
  const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
  export default ReactComponent;
}

2. 确保Icon组件的参数类型正确

检查你的Icon组件是否正确接收React组件类型的props:

// Icon.jsx
import React from 'react';

export default function Icon({ svgImage: SvgComponent }) {
  // 确认SvgComponent是合法的React组件类型
  if (!SvgComponent || typeof SvgComponent !== 'function') {
    return null; // 或者抛出明确错误,方便调试
  }
  return <SvgComponent />;
}

如果用TypeScript,更要严格定义props类型:

import React from 'react';

type IconProps = {
  svgImage: React.ElementType;
};

export default function Icon({ svgImage: SvgComponent }: IconProps) {
  return <SvgComponent />;
}

3. 验证测试文件的导入方式

确保测试文件中正确导入SVG组件并传入Icon:

// Icon.test.jsx
import React from 'react';
import { render } from '@testing-library/react';
import Icon from './Icon';
import HomeIcon from './icons/home.svg'; // 注意是默认导入

test('renders icon correctly', () => {
  const { getByRole } = render(<Icon svgImage={HomeIcon} />);
  expect(getByRole('img')).toBeInTheDocument();
});

4. 排查环境冲突

  • 确认Storybook的SVGR配置和测试环境的配置参数一致(比如是否开启了SVGO优化),避免导出的组件结构不一致
  • 检查测试文件中是否有其他覆盖SVG导入的配置(比如mock文件),如果有需要移除或调整

内容的提问来源于stack exchange,提问作者Kavallier

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:30:44