Prompt
How do I stub third-party API calls in my tests?
Latest observation
To stub third-party API calls in tests, the usual goal is to replace the real network call with a predictable fake so your tests are fast, reliable, and don’t depend on an external service.
Common approaches
1) Mock the HTTP client used by your code
If your code uses something like fetch, axios, requests, httpx, etc., stub at that layer.
Example idea:
- Your function calls
fetch("https://api.example.com/user") - In tests, replace
fetchwith a stub that returns a fixed response
This is usually the simplest and most maintainable approach.
2) Use a library designed for HTTP mocking
Depending on your language/framework, there are tools like:
- JavaScript/TypeScript: MSW, nock, jest mocks
- Python: responses, respx, unittest.mock
- Ruby: WebMock, VCR
- Java: WireMock, Mockito
- Go: httptest, gock
These libraries intercept outgoing HTTP requests and return mocked responses.
3) Dependency injection
Instead of calling the API directly inside your business logic, pass in a client object or function.
Example pattern:
- Production: pass the real API client
- Test: pass a fake client returning known data
This makes tests easier to isolate and often avoids heavy mocking.
4) Record/replay with cassettes
Tools like VCR record real API responses once, then replay them in tests later.
Useful when:
- You want realistic responses
- The API is stable
- You don’t want to handcraft every mock
Downsides:
- Can get brittle if API responses change
- May accidentally capture sensitive data unless sanitized
Best practices
- Stub at the network boundary, not deep inside business logic.
- Return realistic responses that match what your code expects.
- Cover error cases too: timeouts, 500s, invalid JSON, rate limits.
- Don’t hit real external services in unit tests if you can avoid it.
- Keep integration tests separate if you do want to test the real API.
Tiny examples
JavaScript with Jest
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ name: "Alice" })
})
);
Python with unittest.mock
from unittest.mock import patch, Mock
@patch("my_module.requests.get")
def test_user(mock_get):
mock_get.return_value = Mock(status_code=200, json=lambda: {"name": "Alice"})
If you tell me your language/framework and which third-party API library you’re using, I can show you the exact way to stub it.