Introduction
React Router v6's useNavigate function allows you to easily navigate between pages using buttons and links.
However, in a test environment, you often want to simply check whether "navigate" was called without actually performing the transition.
To achieve this, you need a mock (fake function).
In this article, we'll introduce the "useNavigate mocking technique," a standard practice in practice and on Qiita/Zenn.
Writing Steps
- Create a fake navigate function
const mockedNavigator = jest.fn();
- Mock react-router-dom and replace only useNavigate
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"), // Other functions are real
useNavigate: () => mockedNavigator, // Only navigate is fake
}));
- Use in testing
fireEvent.click(screen.getByRole("button", { name: /back/ }));
expect(mockedNavigator).toHaveBeenCalledWith("/");
What does this guarantee?
No real page transitions will occur.
All you can confirm is that "navigate('/') was called."
Top comments (0)