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】エラー「Cannot read properties of undefined」の原因と解決法

Posted at

はじめに

開発中は動いていたSupabaseクライアントが、Jestを実行した瞬間に Cannot read properties of undefined で落ちて困ったため、問題点と解決法をまとめます。

問題と原因

Viteで書いたクライアントは import.meta.env に依存しています。
しかし、Jest(Node環境)では import.meta が存在しません。
そのため、Supabase初期化時に環境変数の取得に失敗していました。

解決法

環境によって process.envimport.meta.env を切り替える関数を作成します。

import { createClient } from "@supabase/supabase-js";

export function createSupabaseClient() {
  const isNode = typeof process !== "undefined" && process.release?.name === "node";
  const supabaseUrl = isNode
    ? process.env.VITE_SUPABASE_URL
    : import.meta.env.VITE_SUPABASE_URL;
  const supabaseAnonKey = isNode
    ? process.env.VITE_SUPABASE_ANON_KEY
    : import.meta.env.VITE_SUPABASE_ANON_KEY;

  return createClient(supabaseUrl, supabaseAnonKey);
}

そして、呼び出し側で以下のように使用します。

import { createSupabaseClient } from "./supabaseClient";
export const supabase = createSupabaseClient();

最後に

ViteとJestでは環境変数の扱いが異なることを知らなかったため、今回知ることができよかったです。
同じようなエラーで困っている方の参考になったら幸いです。

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?