Jest&react-router-dom:React.createElement:类型无效-预期为字符串(对于内置组件)……但是得到:未定义

问题描述 投票:0回答:1

我正在为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
  });
});

我完全一无所知。任何建议将不胜感激。

reactjs react-router jestjs enzyme react-router-dom
1个回答
0
投票

听起来好像您没有导入正确的文件(如果您的.(s)csstest.js文件与组件共享相同的名称并且位于同一根目录中,则webpack可能会导入错误的文件放入测试文件中-因此,我建议指定组件名称和扩展名:index.jsListItem.js)。否则,您可能忘记了导出ListItem组件。

© www.soinside.com 2019 - 2024. All rights reserved.