Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 30 ยท Projects

Project: Test an API Client

Build and test a small fetch-based API client: success paths, HTTP errors, network failures, retries with backoff and fake timers, with runnable stand-ins.

Almost every real application talks to an HTTP API, and almost every API call can fail in several ways: the server answers with an error, the network drops, or the answer is slow. A good API client hides those details, and a good test suite proves it does. In this project you will design a small client with retries, then write the tests for it in the order you would write them in a real codebase.

The tools are the ones from the Mocking chapter: a fake fetch (Mock Functions with jest.fn), injected dependencies (Mocking Modules) and fake timers (Mocking Timers, Dates and HTTP). The real Jest code in this lesson is read-only because Jest cannot run on this site. The runnable examples use Node's assert and mock.timers as honest stand-ins, and each one says so.

What the client must do

Return JSON A 200 response gives back the parsed body.
Fail fast on 4xx The caller made a mistake, retrying will not help.
Retry 5xx Server trouble is often temporary.
Back off Wait 100 ms, then 200 ms, then 400 ms.

Every one of these becomes at least one test.

1 / 2

The design

Hard-wiring fetch and setTimeout into the client would make it hard to test. Instead the constructor accepts them as options and falls back to the real ones:

JavaScript
// api-client.js
export class ApiError extends Error {
  constructor(status, message) {
    super(message);
    this.name = "ApiError";
    this.status = status;
  }
}

export class ApiClient {
  constructor({
    baseUrl,
    fetchImpl = globalThis.fetch,
    sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
    retries = 2,
    backoffMs = 100,
  }) {
    Object.assign(this, { baseUrl, fetchImpl, sleep, retries, backoffMs });
  }

  async getJson(path) {
    for (let attempt = 0; ; attempt++) {
      let response;
      try {
        response = await this.fetchImpl(this.baseUrl + path);
      } catch (cause) {
        if (attempt >= this.retries) {
          throw new ApiError(0, `network error: ${cause.message}`);
        }
      }
      if (response) {
        if (response.ok) return response.json();
        if (response.status < 500 || attempt >= this.retries) {
          throw new ApiError(response.status, `HTTP ${response.status}`);
        }
      }
      await this.sleep(this.backoffMs * 2 ** attempt);
    }
  }
}

Read the loop once: a thrown network error and a 5xx answer both lead to a sleep and another attempt, a 4xx answer ends at once, and running out of retries throws an ApiError. The status 0 marks "no response at all".

The test plan

Write the plan as a list of test names before any code. It doubles as a specification:

  1. returns the parsed body on success
  2. requests baseUrl + path
  3. does not retry a 4xx response
  4. retries a 5xx and succeeds on the second try
  5. waits 100 ms, then 200 ms between attempts
  6. gives up after retries extra attempts with the last status
  7. retries a network error
  8. reports a network error once retries are used up

A scripted fake fetch

The key helper is a fake fetch that plays back a script: each call consumes the next step, which is either a response or an error. In Jest you would build it from jest.fn():

JavaScript
function scriptedFetch(...steps) {
  const fetchMock = jest.fn();
  for (const step of steps) {
    if (step instanceof Error) fetchMock.mockRejectedValueOnce(step);
    else fetchMock.mockResolvedValueOnce(step);
  }
  return fetchMock;
}

const reply = (status, body = {}) => ({
  ok: status >= 200 && status < 300,
  status,
  json: async () => body,
});

The stand-in below does the same with a plain function that records its calls. It is NOT Jest, but the tests read almost identically.

Node.js Stand-in: the whole suite with a scripted fetch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that no test waits for real time: the injected sleep only records the delay it was asked for. That makes backoff behavior a plain assertion on an array ([100, 200]) instead of a stopwatch.

Fake timers instead of an injected sleep

Injecting sleep is the simplest design. But you will often test code that calls setTimeout directly. Then you use fake timers, and the one thing to remember is that promises and timers interleave, so you must let pending promise callbacks run before you advance the clock.

In Jest 29.5 and later (check your version) the async variant does that for you:

JavaScript
test("waits before the second attempt", async () => {
  jest.useFakeTimers();
  const fetchImpl = scriptedFetch(reply(503), reply(200, { ok: true }));
  const client = new ApiClient({ baseUrl: "https://api.test", fetchImpl });

  const pending = client.getJson("/x");
  await jest.advanceTimersByTimeAsync(100);

  await expect(pending).resolves.toEqual({ ok: true });
  expect(fetchImpl).toHaveBeenCalledTimes(2);
  jest.useRealTimers();
});

The runnable stand-in below uses Node's mock.timers, which has the same purpose. It does not wait 100 real milliseconds: it moves a fake clock.

Node.js Stand-in: fast-forwarding the backoff with mock.timers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second request only happens once the fake clock reaches exactly 100 ms. That boundary check is the whole point: it proves the client waited the right amount, without the test taking any time.

Prefer an injected sleep for your own code and fake timers for code you cannot change. Both are fast, but injection keeps the test free of timer subtleties.

What to cover next

The client is far from finished, and each extra feature is another small test cycle:

  • postJson with a request body: assert the fetch options (method, headers, body), for example with expect(fetchImpl).toHaveBeenCalledWith(url, expect.objectContaining({ method: "POST" })).
  • A timeout for a hanging request.
  • Jitter on the backoff delay, tested by also injecting a random function.
  • Parsing failures: a 200 response whose body is not JSON.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the client accept fetchImpl and sleep as constructor options?

    Dependency injection lets a test pass a scripted fetch and a recording sleep, with no network and no real waiting.
  2. 2. A request returns HTTP 404. What should the client do?

    A 4xx status means the request itself is wrong, so retrying would only repeat the mistake.
  3. 3. In the fake-timer test, what must happen before the clock is advanced?

    The setTimeout call happens after an awaited fetch. Until that promise step runs, there is no timer to advance, which is why the async advance helpers exist.
  4. 4. Which assertion best proves the backoff doubles?

    Recording the requested delays and comparing the exact array checks both the count and the doubling.

Summary

  • Make time and network injectable (or fakeable) so tests are fast and deterministic.
  • Write the test plan as names first: success, 4xx, 5xx retry, backoff, giving up, network errors.
  • A scripted fake fetch that consumes one step per call keeps each test short.
  • With real setTimeout code, use fake timers and let promises settle before advancing the clock.
  • Assert on delays and call counts, never on real elapsed time.

Next, test code where many listeners react to one action in Project: Test an Event System.