Introduction
When writing tests with Jest, I encountered the error "environment variables cannot be read." This article summarizes the situation and how to resolve it.
1. Loading Spinner Test Failed
Situation
- When mocking an asynchronous process, execution was too fast, making it impossible to test the UI's momentary state.
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 does indeed appear in the initial rendering.
However, because it immediately disappears while waiting for findByRole, it is treated as "not found" in the test.
Solution
To get it to work, change it to getByRole("status") and check whether it exists at initial display.
test("Loading spinner is displayed", () => {
renderWithProviders(<App />);
expect(screen.getByRole("status")).toBeInTheDocument();
});
If you want to fully test "displaying while loading and disappearing after data is retrieved," add a setTimeout to the mock to delay execution and check with findByRole.
Summary
Spinner test failed → The mock immediately resolved and disappeared.
Solution: Use getByRole to simply pass. Add a delay to the mock to verify operation.
Top comments (0)