当钩子有一些导航逻辑时,我在用renderHook
实用程序测试钩子时遇到了一些问题.我不能在测试中模拟导航.
例如,让我们以这个示例挂钩为例
export const useNavBar = () => {
const location = useLocation();
const isExpandable = useMemo(() => {
const aPath = matchPath({path: "/a-rute"}, location.pathName);
const anotherPath = matchPath({path: "/another-rute"}, location.pathName);
return !aPath && !anotherPath
}, [location.pathname]);
return { isExpandable }
}
目前我想try 一下,当用户导航到不可扩展的路由时,它会发生变化.然而,在测试中,它似乎忽略了window.history.pushState
.
it("changes expandable accessing an invalid route", () => {
const { result } = renderHook(useNavBar, { wrapper: BrowserRouter });
expect(result.current.isExpandable).toBeTruthy();
window.history.pushState({}, '', '/a-route');
expect(result.current.isExpandable).toBeFalsy();
}
调用window.history.pushState
不会触发重新呈现,因此不会更新值.手动调用rerender
也没有效果,因为useLocation
不会注意到更改.
那么,如何使用renderHook
更新位置呢?