Introduction
When writing tests with Jest, I encountered errors such as "environment variables cannot be read" and "loading spinner cannot be found." This article summarizes the situation and how to resolve it.
1. import.meta.env not working error
Situation
Developing a learning record app using React, Vite, and Supabase
Trying to mock the Supabase client with Jest
Copying the production code (utils/supabase.ts) and creating mocks/utils/supabase.ts
The following was written in it:
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL as string;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY as string;
However, Jest does not understand Vite's import.meta.env.
Problem
import.meta.env is only valid in the Vite build environment.
It is not supported in Jest (Node.js environment + ts-jest), so TypeScript is not supported. A compilation error occurred.
Solution
Use process.env for test-only mocks.
Additionally, create .env.test and load it when Jest runs.
// src/mocks/utils/supabase.ts
const supabaseUrl = process.env.VITE_SUPABASE_URL || "http://localhost:54321";
const supabaseAnonKey = process.env.VITE_SUPABASE_ANON_KEY || "mock-anon-key";
2. Loading spinner test failed.
Situation
- When mocking an asynchronous process, execution was too fast, making it impossible to test the instantaneous state of the UI.
const spinner = await screen.findByRole("status");
expect(spinner).toBeInTheDocument();
findByRole("status") waits for the specified element to appear in the DOM.
However, the Superbase mock returned the data immediately.
As a result, setLoading(false) was executed immediately, causing the spinner to disappear.
Problem
The spinner is indeed displayed during initial rendering.
However, because it immediately disappears while waiting for findByRole, it is treated as "not found" in the test.
Solution
To get it through, change it to getByRole("status") and check whether it exists on initial display.
test("Loading spinner is displayed", () => {
renderWithProviders(<App />);
expect(screen.getByRole("status")).toBeInTheDocument();
});
If you want to fully test "displayed while loading, then disappeared after data is retrieved," add a setTimeout to the mock to delay execution and check with findByRole.
Summary
Error 1. Using import.meta.env with a Supabase mock → Jest cannot use this and results in an error.
Solution: Switch to process.env.Error 2. Spinner test failed → The mock immediately resolved and disappeared.
Solution: Use getByRole to simply pass the test. Add a delay to the mock to verify operation.
Top comments (0)