我有如下标头组件:
import { useLocation } from "react-router-dom";
const Header = () => {
let route = useLocation().pathname;
return route === "/user" ? <ComponentA /> : <ComponentB />;
}
您将如何模拟此 useLocation() 以获取用户路径?
我不能简单地在我的测试文件中调用标题组件,因为我收到错误:
类型错误:无法读取 useLocation 处未定义的属性“位置”
describe("<Header/>", () => {
it("call the header component", () => {
const wrapper = shallow(<Header />);
expect(wrapper.find(ComponentA)).toHaveLength(1);
});
});
我尝试过看起来类似于链接如何使用新的反应路由器钩子测试组件? https://stackoverflow.com/questions/58117890/how-to-test-components-using-new-react-router-hooks但它不起作用。
我试过如下:
const wrapper = shallow(
<Provider store={store}>
<MemoryRouter initialEntries={['/abc']}>
<Switch>
<AppRouter />
</Switch>
</MemoryRouter>
</Provider>,
);
jestExpect(wrapper.find(AppRouter)
.dive()
.find(Route)
.filter({path: '/abc'})
.renderProp('render', { history: mockedHistory})
.find(ContainerABC)
).toHaveLength(1);
从链接使用浅层渲染测试react-router https://stackoverflow.com/questions/58887090/testing-react-router-with-shallow-rendering?rq=1但它不起作用。
请告诉我。
提前致谢。