【发布时间】:2020-04-23 05:13:28
【问题描述】:
我正在为具有来自react-router-dom 的Link 的组件编写测试。
组件本身可以正常工作,不会出现任何错误或警告。
但是,当组件使用来自enzyme 的shallow 呈现时,它会在控制台中显示以下错误消息。
警告:React.createElement:类型无效 - 应为字符串(用于内置组件)或类/函数(用于复合组件)但得到:未定义。
您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。
据我研究,apparently 当您错误地导入 React 模块(或组件)时会发生此错误。
例如
import Link from 'react-router-dom'; // Wrong!
import { Link } from 'react-router-dom'; // Correct!
但是,就我而言,Link 已正确导入,但仍会显示上述警告消息。
这是组件的 sn-p。
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
});
});
我完全不知道。 任何建议将不胜感激。
【问题讨论】:
-
我遇到了同样的问题!你找到解决方案了吗?
标签: reactjs react-router jestjs enzyme react-router-dom