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?

More than 1 year has passed since last update.

【vite×Jest】テスト実行時にTypeError:* is not a functionというエラー

Last updated at Posted at 2024-09-06

はじめに

jestのエラーでハマりましたので解決法を共有します。

問題

タイトルの通り、「TypeError: setIsLoadingOverlay is not a function」というエラーが出てテストが通らない。

問題のコード

Settings.test.tsx(中略)
describe("登録テスト", () => {
  test("[正常系]登録処理が正常に動作すること", async () => {
    // 実行
    render(<Settings />);

    // 入力
    const token = "test-api-key";
    const apiInput = screen.getByTestId("qiita-api-input");
    await userEvent.type(apiInput, token);
    // 登録
    const registButton = screen.getByTestId("regist-button");
    fireEvent.click(registButton);

    // 検証
    await waitFor(async () => {
      expect(DB.registQiitaAPIKey).toHaveBeenCalledTimes(1);
      expect(DB.registQiitaAPIKey).not.toHaveBeenCalledWith(token);
    });
    expect(apiInput).toHaveValue("");
  });

テスト対象コード(+の箇所でエラー)

Settings.tsx(中略)
  // 登録
  const registQiitaAPIKey: SubmitHandler<{ token: string }> = useCallback(
    async ({ token }) => {
+      setIsLoadingOverlay(true);
      setIsRegistering(true);
      await DB.registQiitaAPIKey(Util.encrypt(token));
      displayMessage({ title: "登録が正常に完了しました。", status: "success" });
      setIsRegistering(false);
      setIsLoadingOverlay(false);
      reset({ token: "" });
    },
    [setIsLoadingOverlay, displayMessage, reset]
  );

解決方法

setIsLoadingOverlayはContextで定義した関数であるため、テスト時にrender関数でProviderをラップしないと読み込まない。

解決時のコード

Settings.test.tsx(中略)
describe("登録テスト", () => {
  test("[正常系]登録処理が正常に動作すること", async () => {
    // 実行
+    render(<Settings />, { wrapper: LoadingProvider });
    // 入力
    const token = "test-api-key";
    const apiInput = screen.getByTestId("qiita-api-input");
    await userEvent.type(apiInput, token);
    // 登録
    const registButton = screen.getByTestId("regist-button");
    fireEvent.click(registButton);

    // 検証
    await waitFor(async () => {
      expect(DB.registQiitaAPIKey).toHaveBeenCalledTimes(1);
      expect(DB.registQiitaAPIKey).not.toHaveBeenCalledWith(token);
    });
    expect(apiInput).toHaveValue("");
  });

render関数の第二引数にはテストしたいコンポーネントをラップするためのコンポーネントを指定できるようです。

おわりに

テストコードをもっとサクサク実装できるようになりたいです。。

参考

JISOUのメンバー募集中🔥

プログラミングコーチングJISOUではメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
気になる方はぜひHPからライン登録お願いします!👇

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?