While working with Jest and React-Testing-Library, you might encounter the following error:
useNavigate() may be used only in the context of a <Router> component
There are two reasons for the above error:
- The React component you trying to render, is being rendered without wrapping it with any React-router component wrapper such as: BrowserRouter, HistoryRouter or MemoryRouter.
- React-Router-Dom hooks aren’t mocked.
Solution
1- Wrap your component with React-Router component (based on your usage, it can be one of (BrowserRouter, HistoryRouter or MemoryRouter), as the following:
describe("App", () => {
it("renders correctly", async () => {
render(
<BrowserRouter>
<App />
</BrowserRouter>
);
});
});
2- Mock React-Router hooks as the following:
const mockedUsedNavigate = jest.fn();
jest.mock("react-router-dom", () => ({
...(jest.requireActual("react-router-dom") as any),
useNavigate: () => mockedUsedNavigate
}));
describe("App", () => {
it("renders", async () => {
render(
<BrowserRouter>
<App />
</BrowserRouter>
);
// expect(mockedUsedNavigate).toHaveBeenCalledWith('/post-1');
});
});
More details about How to mock React-Router-Dom hooks in Jest can be found on this link.
Photo from Unsplash.