什么是 e2e 测试?NestJS 如何使用 Supertest 测试 HTTP 接口?
解读
面试官抛出这道题,通常想验证三件事:
- 你是否真的理解“端到端”在 Node 语境下的含义,而不是把 e2e 与单元测试、集成测试混为一谈;
- 你是否能在 NestJS 的 IoC 与模块化体系里,把应用“拎起来”跑在真实 HTTP 监听端口,并用 Supertest 完成黑盒调用;
- 你是否知道国内工程化落地时的常见坑(端口占用、数据库状态、JWT 鉴权、CI 并行化、测试数据隔离)。
回答时,先给出 e2e 的精准定义,再给出一条“能直接跑”的 NestJS + Supertest 最佳实践代码路径,最后主动把“数据回滚”“环境变量隔离”等工程痛点抛出来,会让面试官觉得你“干过真项目”。
知识点
- e2e(End-to-End)测试:把应用当作黑盒,从网络层发起请求,贯穿路由、守卫、拦截器、服务、数据库,验证整个链路是否符合预期。
- NestJS 测试哲学:
- 提供 Test.createTestingModule 复用 IoC 容器,但 e2e 需要 bootstrap 整个 NestApplication。
- 官方脚手架自带 test/jest-e2e.json,与单元测试隔离配置。
- Supertest:对 Express 实例做无端口监听(supertest( app.getHttpServer() ))或有端口监听(supertest.agent(url))的 HTTP 断言库;NestJS 底层适配器是 @nestjs/platform-express,因此天然兼容。
- 国内落地细节:
- CI 环境并行任务多,必须动态端口(0 端口)或 jest-worker-id 做端口隔离;
- 数据库用 test 库 + TypeORM synchronize + transaction rollback,避免脏数据;
- JWT 鉴权场景,用测试专用公钥/私钥对,避免调用线上 SSO;
- 文件上传接口,用内存中 Multer 存储,防止落地磁盘造成 side effect。
答案
e2e 测试是把整个后端当作黑盒,从 HTTP 层发起请求,验证“路由→守卫→拦截器→服务→数据库→响应”完整链路是否符合业务预期。
在 NestJS 中,使用 Supertest 的标准步骤如下(可直接落地到国内项目):
-
安装依赖
pnpm add -D supertest @types/supertest -
创建 test/app.e2e-spec.ts
import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import * as request from 'supertest'; import { AppModule } from '../src/app.module'; import { DataSource } from 'typeorm'; describe('AppController (e2e)', () => { let app: INestApplication; let dataSource: DataSource; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); // 获取数据库连接,用于事务回滚 dataSource = app.get<DataSource>(DataSource); }); afterAll(async () => { await app.close(); }); it('/POST /api/v1/login 应返回 201 与 JWT', async () => { const res = await request(app.getHttpServer()) .post('/api/v1/login') .send({ username: 'admin', password: '123456' }) .expect(201); expect(res.body).toHaveProperty('accessToken'); expect(res.body.accessToken).toMatch(/^eyJ/); }); it('/GET /api/v1/profile 应返回 401 当未带 Token', async () => { await request(app.getHttpServer()) .get('/api/v1/profile') .expect(401); }); it('/GET /api/v1/profile 应返回 200 与用户信息', async () => { // 先登录拿 Token const { body: { accessToken }, } = await request(app.getHttpServer()) .post('/api/v1/login') .send({ username: 'admin', password: '123456' }); const res = await request(app.getHttpServer()) .get('/api/v1/profile') .set('Authorization', `Bearer ${accessToken}`) .expect(200); expect(res.body.username).toBe('admin'); }); }); -
在 package.json 中配置独立脚本
"test:e2e": "dotenv -e .env.test -- jest --config ./test/jest-e2e.json --runInBand --forceExit"其中 .env.test 指向本地测试数据库,jest-e2e.json 指定 roots、testMatch、全局超时 30 s。
-
数据库隔离(国内团队常用方案)
- 在 beforeAll 中开启一个事务,在 afterAll 中回滚;
- 或者使用 typeorm-seeding 在每个 case 前重建 schema;
- CI 里用 GitHub Action services 或 GitLab docker-services 起临时 MySQL/Postgres,跑完即毁。
-
端口占用规避
若 CI 并行跑多 job,把 app.listen(0) 让系统随机端口,supertest.agent(url) 方式调用即可。
拓展思考
-
微服务场景:当后端拆成多 Nest 子服务,e2e 是否还要连真实消息队列(Kafka/RabbitMQ)?
国内大厂普遍采用“契约测试 + 消息桩”双轨制:e2e 只测本服务边界,跨服务用 Pact 做契约,避免把 MQ 拉进 CI 造成流水线过长。 -
GraphQL 的 e2e:Supertest 同样适用,只需把 .post('/graphql') 带 query 变量即可;若使用 Code First,建议把 schema 构建成 snapshot,在 e2e 里做回归比对,防止字段漂移。
-
性能与稳定性:
- 单测毫秒级,e2e 秒级,国内头部公司会把 e2e 拆到独立 Stage Pipeline,只在 MR 合并前跑全量;
- 用 jest 的 --shard 参数把用例水平切分,配合 k8s 动态 Pod,10 分钟跑完 2k 条 e2e 用例,是简历里很亮的一笔。
-
安全合规:
- 若接口涉及敏感数据脱敏,e2e 断言时不要硬编码真实身份证/手机号,用正则占位;
- 上线前必须通过“安全基线扫描”,Supertest 可集成 owasp-zap 做被动扫描,把报告输出到 GitLab Security Dashboard,满足国内金融客户合规要求。