所以我有一个 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);
最佳答案
好吧,这是一个愚蠢的问题。我是这样导入 withRouter() 的:
import { withRouter } from 'react-router-dom';
这是基于我从 WebStorm 获得的自动完成导入。然而,真正的导入是:
import { withRouter } from 'react-router';
有了这个,一切正常。
关于reactjs - 在 Jest 测试中,它说 withRouter () 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55083305/