【问题标题】:How to use MemoryRouter in order to test useParams call如何使用 MemoryRouter 来测试 useParams 调用
【发布时间】:2020-12-27 06:50:28
【问题描述】:

我有一个名为 Component.ts 的假设 React 组件,其代码结构类似于:


import React, { FC } from 'react';
import { useParams } from 'react-router-dom';

export const Guide: FC<{}> = () => {

  const { serviceId } = useParams();

  return (
    <p>{serviceId}</p>
  )

}

为了测试这个组件的行为,我试图在我的Component.test.ts 文件中执行类似于以下内容的操作:


import React from 'react';
import { render } from '@testing-library/react';
import { Component } from './Component';
import { Route, MemoryRouter } from 'react-router-dom';


test('my Component test', async () => {

  const someServiceId = 'some-service-id';

  const { findByText } = render(
    <MemoryRouter initialEntries={[`guides/${someServiceId}`]}>
      <Route path='guides/:serviceId'> 
        <Guide />
      </Route>
    </MemoryRouter> 
  );
      
  expect(await findByText(someServiceId)).toBeInTheDocument();

});

当我使用 react-router-dom 的版本 5.2.2 时,我的测试正在运行,但自从我更新到 6.0.0-beta.0 后它就失败了。运行测试时,Jest 显示以下消息:

Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: "guides/some-service-id")

【问题讨论】:

    标签: reactjs typescript react-router-dom


    【解决方案1】:

    经过一番搜索,我找到了答案in the test suite

    6.0.0-beta.0 中的技巧是将&lt;Route /&gt; 包装在&lt;Routes /&gt; 中。另请注意,组件是从 react-router 而不是 react-router-dom 导入的:

    import {
      MemoryRouter,
      Routes,
      Route,
    } from 'react-router';
    
    test('my Component test', async () => {
      const someServiceId = 'some-service-id';
    
      const { findByText } = render(
        <MemoryRouter initialEntries={[`guides/${someServiceId}`]}>
          <Routes>
            <Route path='guides/:serviceId'> 
              <Guide />
            </Route>
          </Routes>
        </MemoryRouter> 
      );
          
      await waitFor(() => expect(findByText(someServiceId)).toBeInTheDocument());
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2020-06-05
      • 2021-10-05
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      相关资源
      最近更新 更多