2
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?

Vitestでモックをテストケースごとに差し替えるようにする

2
Last updated at Posted at 2026-11-07

はじめに

  • vitestでapiレスポンスが取れている時、取れていない時のモックを差し替えたい

追記) この記事の内容でモックが差し替えできるようにはなるが、残ってしまい毎回内容を書かないといけないことについては以下に記載

問題

  • もともと以下のようにモックしていて、ファイル全体が同じ内容でモックされていた。ファイルを変えればこれでもいいのだろうけど
vi.mock("./hooks/useGetLearnRecords",()=>{
    return {
        useGetLearnRecords: vi.fn().mockReturnValue({
            isLoading: false,
            records: [
                {id: "d22a72a4-265a-49e8-8fd4-143569833cd3", title:"Reactの学習", time:1},
                {id: "3e7a74fd-79ee-401d-8ec0-2c91265ca119", title: "AWSの学習", time: 3}
            ],
            reGetRecords
        })
    }
})

解決

  • 以下のように切り出した
const { useGetLearnRecords } = vi.hoisted(() => {
  return {
    useGetLearnRecords: vi.fn().mockReturnValue({
      isLoading: false,
      records: [
        {
          id: "d22a72a4-265a-49e8-8fd4-143569833cd3",
          title: "Reactの学習",
          time: 1,
        },
        {
          id: "3e7a74fd-79ee-401d-8ec0-2c91265ca119",
          title: "AWSの学習",
          time: 3,
        },
      ],
      reGetRecords,
    }),
  };
});

vi.mock("./hooks/useGetLearnRecords", () => ({
  useGetLearnRecords,
}));
  • 呼び出し側でこのように差し替えられる
test("読み込み中画面が表示される", async () => {
  useGetLearnRecords.mockReturnValue({
    isLoading: true,
    records: [],
    reGetRecords: vi.fn(),
  });
  render(<App />);

  expect(screen.getByText("読み込み中")).not.toBeNull();
});

終わりに

解決した手順と参考記事

  1. 以下の記事の内容を一気に全部を試そうとしてうまくいかない
  2. 1つのプロパティ(isLoadingだけ)を試して変数に切り出せそうだと確認
  3. returnやmockReturnedValueなど含めて同じ形で切り出す
  4. IDEの補完でuseGetLearnRecordsの後にuseGetLearnRecordsがあったりしたので、{}でラップする必要がありそうだと気づく

2
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
2
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?