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
Posted at

はじめに

以下の後に次のテストを書いてうまくいかなかった

問題

  • 「学習履歴が表示される」でモックが残ってうまくいかない
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();
});

test("学習履歴が表示される", async () => {
  render(<App />);

  expect(screen.getByText("Reactの学習")).not.toBeNull();
  expect(screen.getByText("AWSの学習")).not.toBeNull();
});

解決

  • デフォルト値をbeforeEachで入れるようにした
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,
}));

+ const records = [
+   {
+     id: "d22a72a4-265a-49e8-8fd4-143569833cd3",
+     title: "Reactの学習",
+     time: 1,
+   },
+   {
+     id: "3e7a74fd-79ee-401d-8ec0-2c91265ca119",
+     title: "AWSの学習",
+     time: 3,
+   },
+ ];

+ beforeEach(() => {
+   useGetLearnRecords.mockReturnValue({
+     isLoading: false,
+     records,
+     reGetRecords,
+   });
+ });

test("読み込み中画面が表示される", async () => {
  useGetLearnRecords.mockReturnValue({
    isLoading: true,
    records: [],
    reGetRecords: vi.fn(),
  });
  render(<App />);

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

test("学習履歴が表示される", async () => {
  render(<App />);

  expect(screen.getByText("Reactの学習")).not.toBeNull();
  expect(screen.getByText("AWSの学習")).not.toBeNull();
});

終わりに

  • mockReturnValueOnce使っても、開発環境だと2回呼ばれるために2回書かないといけないということもありうまくいかなかった
  • そもそもデフォルト値という設計自体がよくないのか?一応意図通り動いているがベストではなさそう
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?