【问题标题】:In Jest test it says withRouter () is not a function在 Jest 测试中,它说 withRouter () 不是函数
【发布时间】:2019-07-31 16:07:43
【问题描述】:

所以我有一个 React 应用程序,并且我为我的组件编写了很多单元测试。我的 VideoNavbar 组件就是这样一个组件。我的测试运行得很完美,直到我决定用 withRouter() 包装组件的默认导出。现在我的 Jest 测试甚至无法开始运行,出现以下错误:

FAIL test/components/AppContent/VideoNavbar/VideoNavbar.Spec.js
  ● Test suite failed to run

    TypeError: (0 , _reactRouterDom.withRouter) is not a function

同样,测试本身根本没有改变。在我添加 withRouter() 之前,它运行良好。

为了让事情变得更奇怪,我还有一个用 withRouter() 包装的组件,它也有 Jest 测试,它不会出现这个错误。

最后,应用程序仍然可以完美运行。我可以启动整个过程,包括 VideoNavbar 组件在内的所有内容都可以正常工作。只有在 Jest 测试中才会发生这种情况。

有人对这可能是什么有任何想法吗?

编辑:这是我的组件的简化版本,以展示我如何导入和使用 withRouter()。我留下了一堆东西来专注于重要的部分。

import React, { useState } from 'react';
import { Link, withRouter } from 'react-router-dom';

const VideoNavbar = (props) => {
    const [ isOpen, setOpen ] = useState(false);
    const { isScanning, history, startFileScan } = props;
    const pathname = history.location.pathname;

    return (
        <JsxIsHere />
    );
};

export default withRouter(VideoNavbar);

【问题讨论】:

  • 你是怎么导入的?

标签: reactjs react-router jestjs


【解决方案1】:

好的,这是一个愚蠢的问题。我是这样导入 withRouter() 的:

import { withRouter } from 'react-router-dom';

这是基于我从 WebStorm 获得的自动完成导入。然而,真正的导入是:

import { withRouter } from 'react-router';

有了它,一切正常。

【讨论】:

  • 大声笑我自己没看到这个我觉得很傻。谢谢
猜你喜欢
  • 2020-02-28
  • 2018-06-19
  • 2020-01-05
  • 2019-10-01
  • 2019-11-28
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多