【问题标题】:Unable to test a component with useLocation hook无法使用 useLocation 挂钩测试组件
【发布时间】:2023-01-19 17:53:36
【问题描述】:

我有一个 Headercomponent 如下:

const Header = () => {
    const data = useDataContext().header;

    return <div data-testid="header" className="w-full h-[80px] bg-white">
        <div className="h-1 bg-green-400 w-full"/>
        <div className="flex items-center w-full h-[80px] shadow-sm">
            <div className="flex items-center flex-1 h-full">
                <Navigation applications={data.apps}/>
            </div>
            <div className="flex items-center pl-4 h-full">
                <Account />
            </div>
        </div>
    </div>

}

Navigation组件如下:

import React, {useState} from 'react';
import {App} from "../../../../interfaces/interfaces";
import {map, find, filter} from "lodash";
import NavigationItem from "./NavigationItem";
import { useLocation, useNavigate } from 'react-router-dom';

interface NavigationProps {
    applications: App[]
}

const Navigation:React.FC<NavigationProps> = ({applications}: NavigationProps) => {
    const [expanded, setExpanded] = useState<boolean>(false)
    const location = useLocation();
    const navigate = useNavigate();

    const activeApplication = find(applications, application => application.url === location.pathname);
    const inactiveApplications = filter(applications, application => application.url !== location.pathname)

    return (
        <div className="flex h-full">
            <div className="z-[2]">
                <NavigationItem application={activeApplication}
                                handleClick={() => setExpanded(expanded => !expanded)}
                                expanded={expanded}
                />
            </div>

            <div className={`flex transform transition transition-transform ${expanded ? 'translate-x-0' : '-translate-x-full'}`}>
                {map(inactiveApplications, application => {
                    return <NavigationItem application={application}
                                           handleClick={() => {
                                               setExpanded(false);
                                               navigate(application.url);
                                           }}
                    />
                })}
            </div>
        </div>
    );
};

export default Navigation;

因此Navigation组件使用来自react-router-domuseLocation钩子。

我想为 Header 组件和 header.test.tsx 编写一些测试如下:

import Header from "./Header";
import {MemoryRouter} from "react-router-dom";

import {describe, it} from "@jest/globals";
import {render, screen} from "@testing-library/react";

describe("<Header/>", () => {
    it("renders the header component with Home link", () => {
        render(<MemoryRouter initialEntries={["/home"]}>
            <Header/>
        </MemoryRouter>);
        const textElement = screen.getByText(/Home/i);
        expect(textElement).toBeInTheDocument();

        const headerElement = screen.getByTestId("header");
        expect(headerElement).toBeInTheDocument()

        // expect(screen.getByRole('link')).toHaveAttribute('href', 'https://www.test.com');
    });
});

因此,我用 MemoryRouter 包装了 header 组件,但它仍然给我一个错误,如下所示:

useLocation() may be used only in the context of a <Router> component.

我做错了什么?

提前致谢。

【问题讨论】:

  • 你试过 ...jest.requireActual('react-router-dom'),

标签: reactjs typescript jestjs react-router-dom


【解决方案1】:

你的渲染应该是这样的

render(
<MemoryRouter initialEntries={["/home"]}>
  <Routes>
     <Route path="/home" element={<Header/>} />
  </Routes>
</MemoryRouter>
)

【讨论】:

  • 同样的错误。
猜你喜欢
  • 2020-08-13
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多