Testing code that calls a third-party API
How you fake external HTTP without real network calls.
Intercept at the HTTP boundary (nock) or run a local mock server; cover success, errors, timeouts, and assert request shape.
WHAT THIS TESTS: Whether you can choose the right interception point so your tests exercise as much real code as possible while staying offline and deterministic, and whether you test failure modes, not just the happy path.
A GOOD ANSWER COVERS: Two broad techniques. First, intercept at the HTTP transport boundary using a library like nock, which patches the http/https layer and matches outgoing requests, letting you script responses, status codes, delays, and bodies. This keeps your real client (axios/fetch), serialization, auth headers, retry, and error-mapping code under test. Second, run a standalone local mock server (WireMock, Mockoon, or an Express stub) the service points at via a configurable base URL; this is closer to a real network round trip and is reusable across languages, but adds process management. The weaker option is mocking your own client wrapper module with jest.mock; it is the simplest but bypasses the actual request construction and HTTP handling, so bugs in headers or serialization slip through. Whatever you pick, test 2xx success, 4xx validation errors, 5xx and timeouts, and assert the outgoing request matches the contract (idempotency keys for payments, for example).
COMMON WRONG ANSWERS: Mocking the highest-level wrapper and claiming the integration is tested; making real calls to a third-party sandbox in CI (slow, flaky, rate-limited, requires secrets); only testing the success path and ignoring timeouts and error codes.
LIKELY FOLLOW-UPS: How do you test retry and backoff logic deterministically? How do you keep mocks honest against contract drift (contract tests, recorded fixtures)? Why are idempotency keys critical for payment retries?
ONE CONCRETE EXAMPLE: For a Stripe charge service, use nock to intercept POST to the charges endpoint: assert one test returns a successful charge, another returns a card_declined 402, and a third delays past the timeout so you verify the retry and surfaced error.
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.