系统学习 测试与质量四阶段学习路径:从单元与接口测试,到端到端、性能、契约和 CI 门禁

用 Supertest 在 Node.js 中直接测试 Express 应用,覆盖状态码、JSON、Cookie 与 CI 集成

适用场景

Node.js 项目使用 Express、Koa 或类似框架,想在不启动固定端口的情况下做 HTTP 层集成测试。Supertest 可以直接接收应用实例,自动创建临时服务器,适合接口回归、鉴权流程和中间件行为验证,常与 Jest 或 Mocha 搭配。

核心概念 / 语法

安装与基本调用

npm install --save-dev supertest jest express

测试中引入应用实例,而不是 URL:

const request = require('supertest');
const app = require('./app');

const res = await request(app).get('/health').expect(200);

request(app) 会在后台监听一个临时端口,请求结束后关闭,不需要自己调用 app.listen。expect(200) 断言状态码,expect('Content-Type', /json/) 断言响应头;响应体用 Jest 的 expect(res.body) 或 Mocha 的断言库检查。

.send() 发送 JSON 或表单对象,.set() 设置 Header,.attach() 上传文件,.query() 添加查询参数。发送 JSON 时应用必须启用 express.json(),否则 req.body 可能是 undefined。

普通请求之间不共享 Cookie;需要登录态时用 request.agent(app) 创建代理,后续请求会自动保存并携带 Set-Cookie 设置的 Cookie。

测试文件应导出 app,不要在模块顶层 listen。如果确实需要监听端口,在 afterAll 中关闭 server,否则 Jest 会因为句柄未释放而挂住。Jest 配置 testEnvironment: "node",CI 中用 --runInBand 避免多个测试文件共享数据库或环境变量时互相干扰。

常用示例

1. 应用与基础断言

// app.js
const express = require('express');
const app = express();
app.use(express.json());

app.get('/health', (req, res) => res.json({ status: 'ok' }));
app.post('/users', (req, res) => {
  if (!req.body.name) return res.status(400).json({ error: 'name required' });
  return res.status(201).json({ id: 1, name: req.body.name });
});
app.post('/login', (req, res) => {
  if (req.body.password !== 'test-password') return res.status(401).json({ error: 'denied' });
  return res.cookie('session', 'demo').json({ ok: true });
});
app.get('/me', (req, res) => {
  if (!req.headers.cookie?.includes('session=demo')) {
    return res.status(401).json({ error: 'unauthorized' });
  }
  return res.json({ user: 'alice' });
});
module.exports = app;
// app.test.js
const request = require('supertest');
const app = require('./app');

test('GET /health 返回 200', async () => {
  const res = await request(app).get('/health').expect(200);
  expect(res.headers['content-type']).toMatch(/json/);
  expect(res.body).toEqual({ status: 'ok' });
});
npx jest --runInBand

2. 参数化与登录态(接上文)

test.each([
  [{ name: 'alice' }, 201],
  [{}, 400],
])('POST /users %j 返回 %i', async (body, status) => {
  await request(app).post('/users').send(body).expect(status);
});

test('agent 保留登录 cookie', async () => {
  const agent = request.agent(app);
  await agent.post('/login').send({ password: 'test-password' }).expect(200);
  const res = await agent.get('/me').expect(200);
  expect(res.body.user).toBe('alice');
});

3. CI 中运行

name: tests
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx jest --ci --runInBand --detectOpenHandles

易错点

相关条目

参考链接

读完自测

  1. 为什么推荐把 Express app 直接传给 request(app),而不是先监听端口?
  2. request.agent(app) 和普通 request(app) 在 Cookie 上有什么区别?
  3. Jest 测试跑完不退出,第一步应该检查什么?
答案
  1. Supertest 会临时监听并在请求后关闭,避免端口冲突和未关闭的 server 句柄。
  2. agent 会保存并自动携带 Cookie,普通 request 每次都是独立请求。
  3. 用 --detectOpenHandles 查找未关闭的数据库连接、定时器或监听端口,而不是直接 --forceExit。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令