Testing API Clients
Testing API Clients — why it matters
An API client test should verify URL construction, headers, status handling, payload parsing, and error paths. Inject fetch as a dependency or intercept requests with an appropriate testing tool. Avoid making ordinary unit tests depend on live third-party servers.
What you’ll learn
- Explain testing api clients and the problem it solves.
- Identify the relevant compile-time checks and runtime responsibilities.
- Run the example, predict its output, and try a realistic modification.
Understand the mechanism
The injected fake controls the response without external network access. The client still checks the HTTP success flag and validates the untrusted JSON shape before returning title.
A fetch mock that always returns valid JSON leaves failure and malformed-payload behavior untested.
Follow the concept flow
Run the primary TypeScript example
Save as testing-api-clients.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.
TypeScript source
type FetchLike = (url: string) => Promise<{ ok: boolean; json(): Promise<unknown> }>;
async function loadTitle(fetcher: FetchLike): Promise<string> {
const response = await fetcher("https://example.test/items/1");
if (!response.ok) throw new Error("HTTP error");
const body = await response.json();
if (typeof body !== "object" || body === null || !("title" in body) || typeof body.title !== "string") throw new Error("Bad response");
return body.title;
}
const fakeFetch: FetchLike = async () => ({ ok: true, json: async () => ({ title: "Read" }) });
loadTitle(fakeFetch).then(console.log).catch(console.error);Verified output
ReadCompile: npx tsc --strict --target es2022 --module commonjs testing-api-clients.ts; run: node testing-api-clients.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.
The example demonstrates the code-level behavior; the related configuration or test commands are shown separately when needed.
Trace the result
The injected fake controls the response without external network access. The client still checks the HTTP success flag and validates the untrusted JSON shape before returning title.
Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.
Common mistake and correction
A fetch mock that always returns valid JSON leaves failure and malformed-payload behavior untested.
Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.
Practice the concept
Add fake responses for 404 and malformed JSON; assert that the client rejects in both cases.
Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.
Check your understanding
What to remember
An API client test should verify URL construction, headers, status handling, payload parsing, and error paths.
Run the primary example, then complete the practice task or environment-specific lab.
Reaching the recap and completing the quizzes are separate milestones.