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 避免多个测试文件共享数据库或环境变量时互相干扰。
// 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
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');
});
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
app.listen(3000) 会占用端口且留下句柄;直接传 app 给 Supertest,或只创建一个 server 并在 afterAll 关闭。EADDRINUSE;request(app) 使用临时端口,不需要写死 3000。--detectOpenHandles 定位,不要用 --forceExit 掩盖。request(app).get(...) 是 thenable,不 await 或不 return 时测试会提前结束,断言失败也不会归因到当前用例。express.json(),.send({ name: 'alice' }) 后 req.body 为空;把解析中间件放在路由之前。request(app) 每次是独立请求,登录后的 Cookie 不会带到下一个请求;用 request.agent(app) 保持会话。request(app),而不是先监听端口?request.agent(app) 和普通 request(app) 在 Cookie 上有什么区别?--detectOpenHandles 查找未关闭的数据库连接、定时器或监听端口,而不是直接 --forceExit。
小程序版
微信扫码,随时查命令