【问题标题】:How to test withRouter() and uselocation() wrapped component in React using jest?如何使用 jest 在 React 中测试 withRouter() 和 uselocation() 包装的组件?
【发布时间】:2022-01-29 23:33:33
【问题描述】:

我遇到了错误。请告诉如何编写测试用例来测试包装在 withRouter 中的组件和使用 useLocation() 的组件 ● 测试套件无法运行

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

【问题讨论】:

    标签: reactjs jestjs react-router react-testing-library


    【解决方案1】:

    出现此错误是因为路由组件树未附加到渲染方法。

    我建议创建一个 TestUtils,它从 react-testing-library 和路由器层次结构中抽象出渲染:

    这或多或少:

    export const renderWithRouter = (
      children,
      {
        path = '/',
        initialRoute = '/',
        history = createMemoryHistory({ initialEntries: [initialRoute] })
      } = {}
    ) => {
      return {
        ...render(
          <Router history={history}>
            <Route path={path}>{children}</Route>
          </Router>
        ),
        history
      };
    };
    

    用法:

    路由中没有参数:

    const wrapper = renderWithRouter(<Component />);
    

    在路由中有参数:

    const wrapper = renderWithRouter(<Component />, { path: '/route/:id', initialRoute: '/route/1' });
    

    其中 :id 将被 1 替换

    【讨论】:

    • 我们需要在测试文件中导入withRouter吗?
    • 不...只是使用renderWithRouter而不是从测试库渲染
    • 当我尝试做 expect(wrapper).tomatchsnapshot(); 时仍然出错错误是 TypeError: (0 , _reactRouterDom.withRouter) 不是函数 21 | 22 | > 23 |导出默认 withRouter(ScrollToTop);
    • 你能展示你的 app.js、index.js 和你的测试文件/工具吗?
    猜你喜欢
    • 2018-03-14
    • 1970-01-01
    • 2017-10-27
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多