5
2

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.

JestでSupabaseのAPIモック化:実践的なコードと解説

5
Posted at

JestでSupabaseをモック化で詰まったので記事にしました。

やりたいこと

Supabaseからデータを取得するメソッドをモック化してSupabase本体に依存しないテストを書きたい。

実際のコード
以下はsupabaseClientを初期化して返すメソッドです。

import { Database } from "../database.types"

export const useSupabaseClient = () => {

  const supabaseClient = createClient<Database>(
    process.env.VITE_SUPABASE_URL!,
    process.env.VITE_SUPABASE_KEY!
  )

  return { supabaseClient }
}

以下はtestファイルです。先ほどのsupabaseClientが呼ばれた時に、select時の挙動を返します。

jest.mock("../hooks/useSupabaseClient.ts", () => {
  return {
    useSupabaseClient: () => ({
      supabaseClient: {
        from: jest.fn().mockReturnValue({
          select: jest.fn().mockResolvedValue({
            data: [
              {
                id: "1",
                name: "test1",
              }
            ]
          })
        })
      }
    })
  }
})

解説

まずテストファイルのuseSupabaseClientが、実装のsupabaseClientのメソッドをモックします。
useSupabaseClient: () => ({

useSupabaseClientはsupabaseClientを返すので、supabaseClientのオブジェクトを定義します。
このオブジェクトはSupabaseに関連するメソッドを持つオブジェクトです。
なのでfrom.select("table")とSupabaseへリクエストを送るときの挙動はこのオブジェクトの中に定義します。

from: jest.fn().mockReturnValue({
  select: jest.fn().mockResolvedValue({

from.select...とメソッドチェーンで実装するので、モックでは上記のようにfromメソッドの中にselectメソッドを定義します。

Supabaseのモックは以上です。

最後に

from.select...とメソッドチェーンで実装するので、fromメソッドの中にselectメソッドがあると考えるところの理解が足らず、今回は本モックの実装で時間がかかってしまいました。

あとselectはselectnのみで他のメソッドに切り出した方がもっと簡単でシンプルかと思いました。
本テストと実装に伸びしろがありますが、勉強になったので残しておきます。

以上です。
最後までご拝読ありがとうございました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?