API Mocking and Stubbing for Development and Testing
API mocking and stubbing replaces real external API calls with simulated responses in development and testing environments. This enables front-end development to proceed without a working backend, allows testing of error and edge-case scenarios, and prevents test suites from depending on external service availability.
Why Mock APIs
- Front-end development: Build and test UI components against realistic API responses before the backend is built
- Testing edge cases: Simulate error responses, timeouts, rate limit errors, and unusual data that is difficult to reproduce with real APIs
- Test isolation: Unit and integration tests should not depend on external services — mocking ensures tests are reliable, fast, and reproducible
- Cost control: Avoid API charges in test environments — many APIs charge per call
- Offline development: Develop and test without internet access to external services
Mocking Approaches
- Mock service workers (MSW): Intercepts HTTP requests at the browser/Node level and returns configured mock responses. Excellent for front-end testing with realistic network behaviour.
- WireMock: Standalone mock server with powerful request matching and response templating. Good for complex integration testing.
- Nock (Node.js): HTTP request interceptor for Node.js test environments
- Mirage JS: In-browser mock server for front-end development
Consumer-Driven Contract Testing
Contract testing formalises the agreement between API consumer and provider — the consumer defines the contract (what it expects), and the provider verifies it can fulfil that contract. Pact is the leading tool for consumer-driven contract testing.