Skip to content

Testing API Endpoints

Test HTTP handlers and API clients with supertest, MSW, and contract checks.

What you'll learn

  • Testing request handlers with supertest against a real server
  • Mocking network responses with Mock Service Worker (MSW)
  • Asserting status codes, headers, and JSON bodies
  • Validating error responses and edge cases

Concept

Two Layers of API Tests

API testing happens at two layers. At the handler layer, you mount your Express/Fastify app and drive it with supertest, which injects HTTP requests without opening a network port — fast and isolated. At the client layer, your front-end code calls fetch or axios, and you intercept those calls with Mock Service Worker (MSW) so the test never hits a real server. Both layers matter: handler tests verify your server logic, client tests verify your front-end's handling of the contract.

supertest

supertest(app).get("/users/1").expect(200).expect("Content-Type", /json/) fires a request against your app instance and chains assertions on the response. Because the app is already in memory, there is no port binding and no network — the test runs in milliseconds. Pair it with a test database that resets between tests so each request starts from known data.

MSW

MSW runs a service worker in the test environment that intercepts fetch and XMLHttpRequest. You declare handlers like http.get("/api/users/:id", () => HttpResponse.json(user)) and the worker returns the canned response. MSW can also simulate errors, delays, and edge-case responses (404, 500, malformed JSON) so you can test your client's error handling thoroughly without a real backend.

Assert the Contract

Assert not just the status code but the response body shape, content type, and relevant headers. Use toEqual for the full body when it is small, or toMatchObject / expect.objectContaining for partial checks. Always test the error paths: missing fields return 400, unauthorized returns 401, unknown resource returns 404. These paths are where users get stuck, so they deserve explicit tests.

In Practice

A thorough API test suite covers the happy path, every error status, validation failures, and edge cases like empty payloads and oversized inputs. With supertest, mount the app once and chain assertions; with MSW, declare handlers for each scenario (success, 404, 500, malformed JSON) and swap them per test to exercise the client's error handling. Assert on the response body with toMatchObject when you care about specific fields but not the whole payload — this survives additive changes to the API. For pagination and filtering, parameterize the tests over different query strings. Always assert the content type header so a JSON endpoint that accidentally returns HTML is caught. These tests are your contract: when the API changes, the failing test tells the client team exactly what broke.

Example

              import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";
import { getUser } from "./apiClient";

const server = setupServer(
  http.get("https://api.example.com/users/:id", ({ params }) =>
    HttpResponse.json({ id: Number(params.id), name: "Ada" })
  )
);
beforeAll(() => server.listen());
afterAll(() => server.close());

describe("getUser", () => {
  it("returns the user from the API", async () => {
    const user = await getUser(1);
    expect(user).toEqual({ id: 1, name: "Ada" });
  });
});
            

MSW intercepts the fetch call inside getUser and returns a canned response. The test verifies the client parses the JSON correctly without touching the network.

Try it

Common mistakes

The mistake

Hitting a real external API in tests

The fix

Real APIs are slow, rate-limited, and change without notice. Use MSW or supertest to keep tests fast, free, and deterministic.

The mistake

Only testing the happy path

The fix

Add tests for 400, 401, 404, 500, and malformed bodies. Error handling is where users get stuck, so it needs the most coverage.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors