reactjs - Jest and react-router-dom : React. createElement : type is invalid -- expected a string (for built-in components) . .. 但得到:undefined

标签 reactjs react-router jestjs enzyme react-router-dom

我正在为具有 Link 的组件编写测试来自 react-router-dom .

组件本身可以正常工作,不会出现任何错误或警告。

但是,当组件使用 shallow 渲染时来自 enzyme , 它在控制台中显示以下错误消息。

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.

据我研究,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
  });
});

我完全没有头绪。 任何建议将不胜感激。

最佳答案

我今天也遇到了这个问题,这是我见过的唯一一个遇到同样事情的人。在用头撞墙一个小时后,我终于弄明白了——事实上,这也可能是你问题的原因。你问这个问题已经 2 年了,所以你可能不再需要答案了,但对于任何 future 偶然发现这篇文章的开发者......

该组件在实践中正确导入,但由于您的模拟,在您的测试中没有正确导入,特别是这部分:

jest.mock('react-router-dom', () => ({
  useHistory: jest.fn()
}));

这用只包含属性 useHistory 的对象替换了所有 react-router-dom 导入,因此从中导入 Link 给出你一个未定义的。它很容易修复:

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: jest.fn()
}));

关于reactjs - Jest and react-router-dom : React. createElement : type is invalid -- expected a string (for built-in components) . .. 但得到:undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59598902/

相关文章:

javascript - 为什么 useState 不在单元测试(Jest、Enzyme)中重新渲染组件?

reactjs - 如何使用 Jest 在 React Native 中正确测试我的 Realm.io 实现?

facebook - 脚本标签在通用 react 应用程序(FB插件)中运行两次

javascript - ReactJS 表单字段的值未更新,并记录为日期字段

javascript - TypeError : this. props.AddNewHero 不是一个函数

reactjs - React-Router v4 onEnter 替换

javascript - 使用 javascript 从 Firebase 检索数据

javascript - 如何在 React 组件中传递 iframe

javascript - React-Redux - NavMenu 上的唯一键警告

javascript - 使用 Jest 按顺序运行 Puppeteer 测试