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でSupabaseとのやりとり部分をモック化してテストを実施する方法

Posted at

概要

Jestでプログラムのテストを実施する際に
Supabaseのデータを取得したり更新したりする関数をモック化した際の覚え書きです。

コード

テスト対象 supabaseのテーブルを更新する関数が想定の動きをするかテスト
export async function UpdateStudyRecord(row: Row) {
    const { id, title, time } = row;

    try {
        const { data, error } = await supabase
            .from("study-record")
            .update({ title, time })
            .eq("id", id);

        if (error) {
            console.error("データの編集中にエラーが発生しました:", error.message);
            return { data: null, error };
        }

        return { data, error };
    } catch (err) {
        console.error("予期しないエラーが発生しました:", err);
        return { data: null, error: err instanceof Error ? err : new Error(String(err)) };
    }
}

テストコード テスト対象の内部で実施しているsuoabaseのupdate処理をモック化
//モックの宣言
jest.mock("@/utils/supabase", () => ({
  supabase: {
    from: jest.fn(),
  },
}));
describe("supabaseMethod", () => {
  it("update成功時", async () => {
    (supabase.from as jest.Mock).mockReturnValue({
      //select以降のupdateの関数を記載
      update: jest.fn(() => ({
        eq: jest.fn().mockResolvedValue({ data: { id: "1" }, error: null }) , //成功時の戻り値を指定
      })),
    });
    const row: Row = { id: "1", title: "新しいタイトル", time: 1 };

    await expect(UpdateStudyRecord(row)).resolves.toEqual({
      data: { id: "1" },
      error: null,
    });
  });

  it("エラーが発生した場合", async () => {
    (supabase.from as jest.Mock).mockReturnValue({
      update: jest.fn(() => ({
        eq: jest.fn().mockResolvedValue({ data: null, error: new Error("更新に失敗") }),
      })),
    });

    const row: Row = { id: "1", title: "エラーテスト", time: 1 };

    await expect(UpdateStudyRecord(row)).resolves.toMatchObject({
      data: null,
      error: new Error("更新に失敗"),
    });
  });
});

insetやdeleteも中身を変更するだけ
insertなどで使いまわせるようにmockの宣言時はselectのみ記載

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?