我正在为Link
中具有react-router-dom
的组件编写测试。
组件本身可以正常工作,而不会发出任何错误或警告。
但是,当使用shallow
中的enzyme
渲染组件时,它将在控制台中显示以下错误消息。
警告:React.createElement:类型无效-预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。
您可能忘记了从定义文件中导出组件,或者您可能混淆了默认导入和命名导入。
据我研究,apparently当您错误地导入React模块(或组件)时,会发生此错误。
例如
import Link from 'react-router-dom'; // Wrong!
import { Link } from 'react-router-dom'; // Correct!
但是,在我的情况下,Link
已正确导入,但仍会显示上面的警告消息。
这是该组件的摘要。
import React from 'react';
import { Link, useHistory } from 'react-router-dom';
// other modules here
const ListItem = (props) => {
const history = useHistory();
const queryParameter = _.get(history, 'location.search', '');
const pathName = `/blah/${props.id}${queryParameter}`;
return (
<li>
<Link to={pathName}>
<div>blah blah...</div>
</Link>
</li>
);
};
((当我注释掉<Link>
时,警告消息将从控制台中消失。因此,使用useHistory()
应该与警告无关)
jest.mock('react-router-dom', () => ({
useHistory: jest.fn()
}));
describe('ListItem', () => {
const baseProps = { /* initial props here*/ };
it("renders the name", () => {
const wrapper = shallow(<ListItem {...baseProps} />);
// the line above shows the warning message in the console
});
});
我完全一无所知。任何建议将不胜感激。
听起来好像您没有导入正确的文件(如果您的.(s)css
或test.js
文件与组件共享相同的名称并且位于同一根目录中,则webpack可能会导入错误的文件放入测试文件中-因此,我建议指定组件名称和扩展名:index.js
或ListItem.js
)。否则,您可能忘记了导出ListItem
组件。