1
1

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】モックを使ったテストが通らない(モックのクリア不足)

1
Posted at

はじめに

Vitestでモックを使ったテストが通りませんでした。

問題

テスト内容:モックが呼ばれないことを確認する

      it("ボタンを押しても遷移しない", async () => {
        const makeButton = await screen.findByRole("button", {
          name: "作成",
        });
        fireEvent.click(makeButton);
        await waitFor(() => {
          expect(mockedNavigator).not.toHaveBeenCalledWith("/trips");
        });
      });

上記のテストが通りませんでした。つまり、モックが呼ばれてしまっています。

解決方法

beforeEach(() => {
+  vi.clearAllMocks();
  render(
    <Provider>
      <MemoryRouter initialEntries={["/trips/new"]}>
        <Routes>
          <Route path="/trips/new" element={<NewTrips />} />
        </Routes>
      </MemoryRouter>
    </Provider>,
  );
});

beforeEachでモックをクリアする必要がありました。
というのも、一つ前のテストケースでは、"/trips"でモックが呼ばれることをテストしており、モックが呼び出された履歴が残ってしまっていました。

おわりに

本物の方の開発と違って、中身が見えないから色々想像しないといけなくて大変だ😵‍💫

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?