1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jest × React Router v6: useNavigate をモックしてテストする定番パターン

Posted at

はじめに

React Router v6 の useNavigate を使うと、ボタンやリンクから簡単にページ遷移できます。
ですが、テスト環境では本物の遷移を起こさずに「navigate が呼ばれたか」だけ確認したいことがよくあります。

そのために使うのが モック(偽物関数) です。
この記事では、実務やQiita/Zennでも定番となっている「useNavigate をモックするお作法」を紹介します。

書き方の流れ

1.偽の navigate 関数を作る

const mockedNavigator = jest.fn();

2.react-router-dom をモック化して、useNavigate だけ差し替える

jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"), // 他の機能は本物
  useNavigate: () => mockedNavigator,        // navigate だけ偽物
}));

3.テストで使う

fireEvent.click(screen.getByRole("button", { name: /戻る/ }));
expect(mockedNavigator).toHaveBeenCalledWith("/");

これは何を保証しているのか?

本物のページ遷移は起きない。

「navigate('/') が呼ばれた」ことだけを確認できる。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?