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 テスト時につまづいたエラーと解決方法

Posted at

はじめに

学習記録アプリを React + Supabase + Jest で開発していたときに、テスト実行中にいくつかのエラーで詰まりました。
ここでは実際に出たエラーを 「問題 → 原因 → 解決方法」 の形式で整理しています。

問題1: SyntaxError: Cannot use 'import.meta' outside a module

状況

src/utils/supabase.ts の中で

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;

と書いていたら、テスト実行時にエラーが出た。

原因

import.meta は ESM (モダン JavaScript) の書き方。

でも Jest は標準で import.meta を理解できないため、テストが止まってしまう。

解決方法

Node.js 標準の環境変数に書き換える

const supabaseUrl = process.env.VITE_SUPABASE_URL ?? "";
const supabaseAnonKey = process.env.VITE_SUPABASE_ANON_KEY ?? "";

テスト用に Supabase をモック化する
src/mocks/supabase.ts を作成:

export const supabase = {
  from: () => ({
    select: async () => ({ data: [], error: null }),
    insert: async () => ({ error: null }),
    delete: async () => ({ error: null }),
    update: async () => ({ error: null }),
  }),
};

これでテスト時には本物の Supabase ではなく「ダミーの supabase」が使われるようになる。

問題2: Cannot find module '../supabase' from 'src/tests/App.test.tsx'

状況

テストファイルに

jest.mock("../supabase");

と書いたら「モジュールが見つかりません」というエラーになった。

原因

実際のファイルは src/utils/supabase.ts にあるのに、テストでは ../supabase と書いていた。

import パスの指定ミス。

解決方法

アプリ本体の import を統一する
App.tsx では必ずこう書く:

import { supabase } from "./utils/supabase";

テストでも同じパスを使う

jest.mock("../utils/supabase");

これで 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?