DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

Errors I Encountered During Jest Testing and Their Solutions

Introduction

While developing a study log app using React + Supabase + Jest, I encountered several errors during test execution.
Here, I've organized the actual errors encountered in the format “Problem → Cause → Solution”.

Problem 1: SyntaxError: Cannot use ‘import.meta’ outside a module

Situation

In src/utils/supabase.ts, the line

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;

caused an error during test execution.

Cause

import.meta is an ESM (modern JavaScript) syntax.

However, Jest doesn't understand import.meta by default, causing tests to halt.

Solution

Rewrite to Node.js standard environment variables

const supabaseUrl = process.env.VITE_SUPABASE_URL ?? “”;
const supabaseAnonKey = process.env.VITE_SUPABASE_ANON_KEY ?? “”;
Enter fullscreen mode Exit fullscreen mode

Mock Supabase for testing
Create 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 }),
  }),
};
Enter fullscreen mode Exit fullscreen mode

This ensures the “dummy supabase” is used instead of the real Supabase during tests.

Issue 2: Cannot find module ‘../supabase’ from ‘src/tests/App.test.tsx’

Situation

When writing

jest.mock(“../supabase”);
Enter fullscreen mode Exit fullscreen mode

resulted in a “module not found” error.

Cause

The actual file is located at src/utils/supabase.ts, but the test specified ../supabase.

Incorrect import path specification.

Solution

Unify the import path throughout the main app
Always write it like this in App.tsx:

import { supabase } from “./utils/supabase”;
Enter fullscreen mode Exit fullscreen mode

Use the same path in tests

jest.mock(“../utils/supabase”);
Enter fullscreen mode Exit fullscreen mode

This allows Jest to correctly find the mock file.

Conclusion

It cost me a bit of time.

Top comments (0)