我有一个Header
组件,如下所示:
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-dom
的useLocation
挂钩。
我想为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
Package header
组件,但它仍然给我一个错误,如下所示:
useLocation() may be used only in the context of a <Router> component.
我做错了什么?
先谢了。
1条答案
按热度按时间kfgdxczn1#
渲染应如下所示