我有如下所示的标头组件:
import { useLocation } from "react-router-dom";
const Header = () => {
let route = useLocation().pathname;
return route === "/user" ? <ComponentA /> : <ComponentB />;
}
您将如何模拟此useLocation()以获取用户路径?
我无法在测试文件中像下面那样简单地调用Header组件,因为出现错误:
TypeError:无法读取useLocation处未定义的属性'location'
describe("<Header/>", () => {
it("call the header component", () => {
const wrapper = shallow(<Header />);
expect(wrapper.find(ComponentA)).toHaveLength(1);
});
});
我尝试过看起来类似于链接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);
从链接Testing react-router with Shallow rendering开始,但是没有用。
请让我知道。
提前感谢。
您是否尝试过:
describe("<Header/>", () => {
it("call the header component", () => {
const wrapper = shallow(<MemoryRouter initialEntries={['/abc']}><Header /></MemoryRouter>);
expect(wrapper.find(Header).dive().find(ComponentA)).toHaveLength(1);
});
});
当使用浅色时,仅会渲染第一个lvl,因此您需要使用潜水来渲染另一个组件。
我发现我可以使用以下模式来模拟类似useLocation的React Router钩子:
import React from "react"
import ExampleComponent from "./ExampleComponent"
import { shallow } from "enzyme"
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"),
useLocation: () => ({
pathname: "localhost:3000/example/path"
})
}));
describe("<ExampleComponent />", () => {
it("should render ExampleComponent", () => {
shallow(<ExampleComponent/>);
});
});
如果在ExampleComponent中调用useLocation,则上述模式应允许您在酶/笑话测试中浅化呈现组件,而不会出现错误。希望能有所帮助!