DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

[For Beginners] Quickly Fix Jest Crashing with import.meta in Vite+React+TypeScript (Supabase Compatible)

Introduction

When testing a Vite + TypeScript app with Jest, I encountered the following errors:

  • TS1343: ‘import.meta’ can only be used with specific module configurations

  • SyntaxError: Cannot use import statement outside a module

  • Additionally, accessing Supabase during tests resulted in logs like ENOTFOUND

Causes

  • The issue stemmed from two causes:
    • src/utils/supabase.ts was written assuming import.meta.env could be used, despite Jest (and Node) not supporting it.
    • Jest configuration was mixed between ESM and CJS modes. (Jest failed to interpret the file format, triggering a chain of errors.)

Solution

  1. Remove import.meta.env from supabase.ts and standardize to process.env
// src/utils/supabase.ts
import { createClient } from “@supabase/supabase-js”;

const supabaseUrl = process.env.VITE_SUPABASE_URL || “”;
const supabaseAnonKey = process.env.VITE_SUPABASE_ANON_KEY || “”;

export const supabase = createClient(supabaseUrl, supabaseAnonKey);

Enter fullscreen mode Exit fullscreen mode

2. Write setup in JS (using require)

// jest.setup.js
require(“@testing-library/jest-dom”);

// Dummy values for testing (use .env.test + dotenv for production)
process.env.VITE_SUPABASE_URL = “https://dummy.supabase.co”;
process.env.VITE_SUPABASE_ANON_KEY = “dummy-anon-key”;
Enter fullscreen mode Exit fullscreen mode

3. Fix Jest configuration in CommonJS

// jest.config.cjs
/** @type {import(‘ts-jest’).JestConfigWithTsJest} */
module.exports = {
  preset: “ts-jest”,
  testEnvironment: “jsdom”,
  setupFilesAfterEnv: [“<rootDir>/jest.setup.js”],
  transform: {
    “^.+\\.(ts|tsx)$”: [“ts-jest”, { tsconfig: “tsconfig.json” }],
  },
  moduleNameMapper: {
    “\\.(css|less|scss)$”: “identity-obj-proxy”,
  },
};
Enter fullscreen mode Exit fullscreen mode

Summary

  • Tests exist in a separate world from production: What works in production (like import.meta.env) may not work in tests

  • Keep “writing style” consistent: Stick with CJS (require / module.exports) for Jest-related code for stability

  • Stop communication with external services in tests: Replace them with mocks and focus tests solely on verifying behavior

Top comments (0)