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
- Remove
import.meta.env
fromsupabase.ts
and standardize toprocess.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);
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”;
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”,
},
};
Summary
Tests exist in a separate world from production: What works in production (like
import.meta.env
) may not work in testsKeep “writing style” consistent: Stick with CJS (
require
/module.exports
) for Jest-related code for stabilityStop communication with external services in tests: Replace them with mocks and focus tests solely on verifying behavior
Top comments (0)