Handling External Services in E2E Tests
You'll learn when to stub, mock, or use real external services in end-to-end tests, and how to prevent third-party failures from breaking your test suite.
The External Service Dilemma
When your application depends on external APIs (payment processors, email services, weather APIs), you face a choice: test against the real service, or use a test substitute? Each approach has tradeoffs.
Real services give you confidence that integrations actually work, but they're slow, cost money, and can fail unpredictably—bringing down your entire test suite when a third-party has an outage.
Stubbed or mocked services run fast and reliably, but don't catch real integration issues like authentication changes or API deprecations.
When to Use Each Approach
Use real services for:
- Critical payment flows (at least in staging)
- One or two "smoke tests" that verify actual connectivity
- Services you control or that offer reliable test environments
Use stubs/mocks for:
- Most E2E tests where the service behavior is well-understood
- Expensive operations (SMS sending, third-party API calls)
- Testing error scenarios (network timeouts, rate limits)
Building Resilience
Even when using real services, protect your tests:
- Isolate external calls to specific test scenarios you can skip independently
- Implement timeouts so slow services don't hang your suite
- Add retry logic for transient failures
- Use test accounts or sandboxes provided by the service
- Cache responses when appropriate to reduce actual calls
Think of it like testing a car: you test the radio works, but you don't need to verify that the actual radio station broadcasts correctly—that's their responsibility.
Key Takeaway: Default to stubbing external services in most E2E tests for speed and reliability, but maintain a smaller set of tests against real services to catch genuine integration issues—and always design tests to gracefully handle third-party failures.