Testing Network Calls and API Clients
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Replace the network with a controllable double.
- Assert on the request that was sent and the data that was returned.
- Test timeout, error and retry paths without a real server.
Overview
#Never call the real network in a unit test
A test that hits a real server is slow, flaky and dependent on state you do not control. It also fails when the network is down, which has nothing to do with your code. Replace the network boundary with a double and test the client logic against it.
Inject the fetch function
The cleanest approach is dependency injection: the API client accepts a fetch function rather than reading the global. The test passes a fake that records the request and returns a canned response.
function createClient(fetchImpl) {
return {
async getUser(id) {
const response = await fetchImpl('/api/users/' + id);
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.json();
},
};
}
Assert both directions
A network test has two contracts: the request the client sends and the data it returns. Assert that the URL and method are correct, and assert that the parsed result matches. A test that only checks the return value misses a client that calls the wrong endpoint but happens to parse the response.
Test the failure paths
The interesting API behavior is in the failures. Return a 404 and assert the client throws a typed error. Return a 500 and assert it does not silently return undefined. Simulate a timeout and assert the client aborts and surfaces a timeout error. Simulate a malformed JSON body and assert the client handles the parse error instead of crashing with an unhelpful message.
Response objects are not plain data
A real Response has ok, status, headers and async json() and text() methods. A fake must model these, or the client code will call response.json() on a plain object and crash. Build the smallest fake that satisfies the interface the client actually uses.
Where the boundary sits
Decide once where the network boundary is and double it there. If some tests use a request-interception layer and others inject a fake fetch, you have two boundaries and inconsistent tests. Pick one and apply it consistently.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
The fake response below has `ok: false` and status 404. What does `getUser` do?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst fakeFetch = async () => ({ ok: false, status: 404, json: async () => ({}) }); const client = createClient(fakeFetch); client.getUser(1).then(() => console.log('resolved')).catch((e) => console.log(e.message));Exercise 2Explain
Explain why a test should assert on the request URL as well as the response.
Reveal the reference answer
reference.javascriptThe client has two responsibilities: send the right request and return the right data. A test that only checks the response can pass even if the client calls the wrong endpoint, as long as the fake returns a plausible body. Asserting the URL and method proves the client addressed the correct resource, which is half of its contract.The answer should treat request and response as two separate contracts the client must satisfy.
Exercise 3Implement
Implement `createClient(fetchImpl)` whose `getUser(id)` calls `fetchImpl('/api/users/' + id)`, throws `HTTP <status>` when `!response.ok`, and otherwise returns `response.json()`. With a fake returning `{ ok: true, json: async () => ({ id: 7 }) }`, `console.log((await client.getUser(7)).id)` should print `7`.
starter.javascriptfunction createClient(fetchImpl) { // your code here }Reveal the reference answer
reference.javascriptfunction createClient(fetchImpl) { return { async getUser(id) { const response = await fetchImpl('/api/users/' + id); if (!response.ok) throw new Error('HTTP ' + response.status); return response.json(); }, }; }Authored expected output: 7
The client awaits the injected fetch, checks the ok flag, and delegates parsing to response.json(). Injecting fetchImpl is what makes the client testable without a server.
Exercise 4Debug
This test fake is a plain object, so `response.json()` is not a function and the client crashes. Fix the fake to model a real Response.
starter.javascriptconst fakeFetch = async () => ({ ok: true, body: { id: 1 } }); const client = createClient(fakeFetch); client.getUser(1).then((u) => console.log(u.id));Reveal the reference answer
reference.javascriptconst fakeFetch = async () => ({ ok: true, status: 200, json: async () => ({ id: 1 }), }); const client = createClient(fakeFetch); client.getUser(1).then((u) => console.log(u.id));Authored expected output: 1
The client calls response.json(), which the plain object does not have. The fake must provide async json() returning the body, plus ok and status, to satisfy the interface the client uses.
Exercise 5Test
Write tests that prove the client sends the correct URL and throws on a 500 response.
starter.javascriptfunction createClient(fetchImpl) { return { async getUser(id) { const response = await fetchImpl('/api/users/' + id); if (!response.ok) throw new Error('HTTP ' + response.status); return response.json(); }, }; }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } async function test() { const calls = []; const okFetch = async (url) => { calls.push(url); return { ok: true, status: 200, json: async () => ({ id: 7 }) }; }; const client = createClient(okFetch); const user = await client.getUser(7); assertEqual(calls[0], '/api/users/7', 'request url'); assertEqual(user.id, 7, 'parsed body'); const failFetch = async () => ({ ok: false, status: 500, json: async () => ({}) }); let message = ''; try { await createClient(failFetch).getUser(1); } catch (error) { message = error.message; } assertEqual(message, 'HTTP 500', 'throws on 500'); console.log('client verified'); } test();Authored expected output: client verified
The first two assertions cover the request contract and the success path. The third covers the failure path and proves the client surfaces the status instead of returning bad data.
Exercise 6Interview
In an interview, explain how you would test a client that retries failed requests.
Reveal the reference answer
reference.javascriptI inject the fetch function and a deterministic delay so no real time passes. I make the first two calls reject and the third resolve, then assert the client resolved and that fetch was called exactly three times. I add a case where every call rejects and assert the client throws after the configured attempt count, proving it does not retry forever. I also assert the delay between attempts uses the injected scheduler rather than a real timer.The answer should combine dependency injection, call counting, both success and exhaustion paths, and control of time.
Common misconceptions
#- Hitting a real API in tests is more realistic and therefore better.
- Only the success path needs a test because the server handles errors.
- A fake response can be a plain object with a `json` property.
Follow-up practice
#- testing-integration
- testing-contracts
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.