Course contentsShow
← React
Lesson 2134 of 2,39647. Testing Patterns and Best PracticesFree lesson

Environment Variables and Feature Flags

Mock configuration and feature toggles to test different code paths without changing implementation.

Environment Variables and Feature Flags

You'll learn how to test code paths that depend on runtime configuration without hardcoding or modifying implementation.

The Core Idea

Your app likely behaves differently based on environment variables (process.env.NODE_ENV) or feature flags (isFeatureEnabled('newCheckout')). You need to test both code paths—but you don't want to redeploy your app or change production code just to run tests.

The solution: mock the configuration layer so each test can simulate different environments or feature states. This lets you verify that your "new checkout" and "old checkout" branches both work, all in the same test suite.

Why This Matters

Configuration and feature flags are external dependencies from your component's perspective. Just like you mock API calls with MSW, you mock configuration to control which code paths execute. This isn't testing implementation details—it's testing actual user-facing behavior under different conditions.

The Pattern

Mock process.env or your feature flag module before rendering:

vi.stubEnv('VITE_NEW_CHECKOUT', 'true')
// or
vi.mock('./featureFlags', () => ({
  isEnabled: vi.fn(() => true)
}))

Then test that the component behaves correctly in that environment. Reset between tests to verify the opposite condition.

This approach ensures your conditional logic works without changing a single line of production code. You're not testing whether the flag exists—you're testing whether the user sees the right UI when the flag is on or off.

Key Takeaway: Mock environment variables and feature flags as external dependencies to test all conditional code paths in isolation, ensuring both configurations work correctly for users.