【问题标题】:unit test not using url path with parameter when using reach router with react-testing-library使用带有 react-testing-library 的到达路由器时,单元测试不使用带参数的 url 路径
【发布时间】:2020-10-22 01:46:14
【问题描述】:

我正在尝试为 react 组件创建一个单元测试,其中组件的 props 检查部分 url 路径以确定操作过程,并在路径的末尾接收参数或值。

使用https://testing-library.com/docs/example-reach-router 中给出的示例,我创建了自己的单元测试,但是当我运行测试时,我的组件抱怨 uri 值不存在。另外,当我将 console.log(props) 添加到我的组件并再次运行测试时,props 是未定义的。

我尝试了一种使用 LocationProvider 包装组件的变体,如 https://reach.tech/router/api/LocationProvider 所示添加历史记录

相关代码sn-p为-

function renderWithRouter(
  ui,
  { route = '/', history = createHistory(createMemorySource(route)) } = {}
) {
  return {
    ...render(

      <LocationProvider history={history}>{ui}</LocationProvider>
    )
    ,
    history,
  }
}

describe('View Order Test', () => {

  describe('Order', () => {

    it('Renders the Order View for a specific Order', async () => {

      const { queryByText } =
        renderWithRouter(

          <State initialState={initialState} reducer={reducer}>
            <ViewOrder />
          </State>
          , { route: '/order/orderView/1234', }
        )
      expect(queryByText('OrderID: 1234'))
    }
    )
  })

似乎没有任何效果。有没有办法将道具传递给一个单元中的 uri (@reach/router) 组件?正如我所说,我的单位是上面给出的那些的副本

【问题讨论】:

  • 很难按原样提供帮助,您能在代码盒中重现吗?
  • 将整个代码放在那里会太多,但我可以向您保证,我基本上复制了链接中的内容
  • 你不需要放所有代码,只是一个最小的可复现的例子
  • 添加相关代码片段

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


【解决方案1】:

通过添加 Reach Router 并将其包裹在组件周围来解决。

【讨论】:

    【解决方案2】:

    我在使用带有reach-router 的url 参数测试组件时遇到了类似的问题。

    路由文件示例:

    import { Router } from "@reach/router";
    import Item from "pages/Item";
    
    const Routes = () => (
      <Router>
        <Item path="/item/:id" />
      </Router>
    );
    ...
    

    在我的测试代码中,我在渲染函数中这样做了:

    import {
      Router,
      createHistory,
      createMemorySource,
      LocationProvider,
    } from "@reach/router";
    import { render } from "@testing-library/react";
    
    export function renderWithRouter(
      ui,
      { route = "/", history = createHistory(createMemorySource(route)) } = {}
    ) {
      return {
        ...render(
          <LocationProvider history={history}>
            <Router>{ui}</Router>
          </LocationProvider>
        ),
        history,
      };
    }
    

    和测试用例:

    test("renders the component", async () => {
      renderWithRouter(<Item path="/item/:id" />, { route: "/item/1" });
      ...
    });
    

    通过这种方式,我能够获取url参数并且所有测试都运行良好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-14
      • 2019-09-02
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2021-07-05
      • 2021-05-27
      相关资源
      最近更新 更多