react-testing-library 和 Location/Path 上的问题 header

Issue on react-testing-library and Location/Path in header

我有一个如下所示的 header 组件,我正在尝试为其编写测试。我收到错误 inserts text in h2 >>> TypeError: Cannot read property 'location' of undefined

header.js

import { useLocation } from 'react-router-dom'

const Header = ({ title }) => {
const location = useLocation();  <<<< Error Occurs here

 return (
    <header className='header'>
       <h2 data-testid='h2HeaderTag'>{title}</h2>
       {location.pathname === '/'}
    </header>
 )}

Header.test.js :

it("inserts text in h2", () => {
   const { getByTestId, getByText } = render(<Header title="title" />);

   expect(getByTestId("h2HeaderTag")).toHaveTextContent("title");
   expect(getByText("title")).toHaveClass("fancy-h2");
});

您似乎没有将正在测试的组件渲染到路由器中以使其具有路由上下文和定义的位置。您可以提供一个自定义包装器来包装被测试的提供路由上下文的组件。参见 Wrapper API

  1. 创建 RouterWrapper 测试实用程序

    import { MemoryRouter } from 'react-router-dom';
    
    export const RouterWrapper = ({ children }) => (
      <MemoryRouter>{children}</MemoryRouter>
    );
    
  2. 在测试中导入并使用 RouterWrapper

    import { RouterWrapper } from '../path/to/test/utils';
    
    it("inserts text in h2", () => {
      const { getByTestId, getByText } = render(
        <Header title="title" />,
        { wrapper: RouterWrapper }
      );
    
      expect(getByTestId("h2HeaderTag")).toHaveTextContent("title");
      expect(getByText("title")).toHaveClass("fancy-h2");
    });