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

When to Mock: Expensive Third-Party Libraries

Mock libraries like analytics, payment processors, or video players that can't run in test environments.

When to Mock: Expensive Third-Party Libraries

What you'll learn: When mocking is actually justified: libraries that can't or shouldn't run in test environments.

The Justified Exception

While we avoid mocking internal code, some third-party libraries should be mocked because they're genuinely incompatible with test environments. Analytics SDKs, payment processors, video players, and map renderers fall into this category—they're either expensive to initialize, require browser APIs unavailable in jsdom, or would trigger real-world side effects.

The Real-World Problem

Imagine testing a component that initializes a payment processor:

// Stripe.js actually loads external scripts and contacts servers
import { loadStripe } from '@stripe/stripe-js';

function CheckoutForm() {
  const [stripe, setStripe] = useState(null);
  
  useEffect(() => {
    loadStripe('pk_test_123').then(setStripe);
  }, []);
  
  // Component renders based on stripe state...
}

The problem: loadStripe tries to contact Stripe's servers, inject scripts, and initialize payment infrastructure—none of which work (or should happen) in a test runner.

When Mocking is Appropriate

Mock third-party libraries when they:

  • Contact external services (analytics, payment gateways)
  • Require browser APIs unavailable in test environments (Web Audio, WebGL)
  • Are prohibitively slow to initialize (large video libraries)
  • Have licensing/authentication requirements
vi.mock('@stripe/stripe-js', () => ({
  loadStripe: vi.fn(() => Promise.resolve({ /* mock Stripe instance */ }))
}));

Now you test the behavior your component exhibits when Stripe loads, not Stripe itself.

Key Takeaway: Mock third-party libraries that can't run in test environments or would trigger real external effects—but still test your component's behavior, not its implementation.