Eliminating Flaky Tests: Managing Global Environment State in Vitest
Testing code that interacts with environment variables is a common source of frustration. In the ibime-connect project, we recently encountered flaky behavior in our integration tests—specifically those validating rate-limiting logic—where global state changes weren't being cleaned up correctly, leaking configurations across test suites.
The Problem: State Leakage
When tests mutate process.env directly, they create a "global state leak." Even if you attempt to manually revert the variable at the end of a test, a failure or early exit often skips that cleanup logic. This causes the modified environment variable to persist, unexpectedly impacting subsequent tests and causing intermittent, hard-to-reproduce failures.
In our case, setting NODE_ENV to production for a specific test case accidentally leaked into other tests, triggering production-only code paths where they didn't belong.
A Robust Solution with Vitest
Instead of manual manipulation, Vitest provides built-in utilities designed to manage environment isolation safely. By utilizing vi.stubEnv, we can safely mock variables, and by pairing it with vi.unstubAllEnvs, we ensure a clean slate after every test execution.
The Pattern
import { vi, describe, it, expect, afterEach } from 'vitest';
describe('Rate Limiter', () => {
afterEach(() => {
// Automatically resets all stubbed env variables
vi.unstubAllEnvs();
});
it('triggers rate limit in production mode', () => {
vi.stubEnv('NODE_ENV', 'production');
const status = checkRateLimit();
expect(status).toBe(429);
});
});
The Takeaway
Never rely on manual cleanup for global state. By leveraging Vitest's vi.unstubAllEnvs in an afterEach hook, you guarantee that environmental mutations are scoped strictly to the test that needs them. Treat environment variables as transient state—isolate them, use them, and let the framework clean up after you.
Generated with Gitvlg.com