I am rendering a component that uses Next.js router.
When rendering in jsdom using Jest/Testing Library via Testing Library's render
method, the router always returns null
.
For example, returning this component in Jest
const DashboardSidebar: FC<DashboardSidebarProps> = (props) => {
const { onMobileClose, openMobile } = props;
const router = useRouter();
const { user } = useAuth();
useEffect(() => {
if (openMobile && onMobileClose) {
onMobileClose();
}
}, [router.pathname]);
}
will give the error message
TypeError: Cannot read property 'pathname' of null
145 | onMobileClose();
146 | }
> 147 | }, [router.pathname]);
Same goes for router.isReady
. router is null
.
I am assuming that the rendering of the component in to jsdom will run the router, since the router is defined within the component.
I just have to make the router run so that components will render content, and I do not want to test its functionality; I am UI testing, so implementation details are unnecessary.
How does Nextjs router work under the hood, and why isn't it running, and how can I make the router run?