Skip to content

测试 API 端点

测试 HTTP 处理函数 and API 客户端使用 supertest, MSW, and contract 检查.

你将学到

  • 测试请求处理函数使用 supertest 针对真实服务器
  • Mocking network 响应使用 Mock Service 工作者 (MSW)
  • Asserting 状态 codes, 请求头, and JSON bodies
  • 验证错误响应 and 边缘情况

概念讲解

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 获取 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).获取("/用户/1").expect(200).expect("内容-类型", /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 获取 and XMLHttpRequest. You declare handlers like HTTP.获取("/API/用户/:id", () => HttpResponse.JSON(用户)) 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.

示例代码

              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 获取 call 内部 getUser and 返回 canned 响应. 测试验证客户端 parses JSON 正确地不使用 touching network.

动手试一试

常见错误

错误写法

Hitting 真实外部 API in 测试

正确做法

真实 APIs 是慢, 速率-有限, and 更改不使用 notice. Use MSW or supertest 到 keep 测试快, free, and deterministic.

错误写法

仅测试 happy path

正确做法

添加测试 for 400, 401, 404, 500, and malformed bodies. 错误 handling 是哪里用户获取 stuck, 所以它 需要大多数 coverage.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误