首页 > 解决方案 > 哪个导入与 FontAwesomeIcon、React 和 Jest 一起使用?

问题描述

我有一个 React 站点(使用 TypeScript 和 Webpack),它使用 FortAwesome 的react-fontawesome包来呈现图标。这个包是这样导入的:

import FontAwesomeIcon from '@fortawesome/react-fontawesome';

在使用 Enzyme 添加 Jest 测试时,任何使用包含引用的组件的测试都会FontAwesomeIcon失败,并出现以下情况:

Warning: React.createElement: type is invalid -- expected a string (for built-in
components) or a class/function (for composite components) but got: undefined. 
You likely forgot to export your component from the file it's defined in, or you might
have mixed up default and named imports.

将这些组件的导入更改为:

import * as FontAwesomeIcon from '@fortawesome/react-fontawesome';

修复了测试,但随后浏览到包含该组件的页面失败:

Warning: React.createElement: type is invalid -- expected a string (for built-in
components) or a class/function (for composite components) but got: object.

我预计这是 ES6、Babel 和月相之间的冲突,但经过几个小时的斗争,我已经没有想法了......

标签: javascriptreactjsfont-awesomejestjs

解决方案


正如预期的那样,这是标准的冲突,并且与 TypeScript 的关系比其他任何东西都多。解决方案是添加"allowSyntheticDefaultImports": truetsconfig.json文件中。希望这对后来的人有所帮助...


推荐阅读