DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

Jest React Router v6: A standard pattern for mocking and testing useNavigate

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

  1. Create a fake navigate function
const mockedNavigator = jest.fn();
Enter fullscreen mode Exit fullscreen mode
  1. 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
}));
Enter fullscreen mode Exit fullscreen mode
  1. Use in testing
fireEvent.click(screen.getByRole("button", { name: /back/ }));
expect(mockedNavigator).toHaveBeenCalledWith("/");
Enter fullscreen mode Exit fullscreen mode

What does this guarantee?

No real page transitions will occur.

All you can confirm is that "navigate('/') was called."

Top comments (0)