Nest 官方测试能力基于 @nestjs/testing。
#1. 单元测试 —— 只测调度员
import { Test } from '@nestjs/testing';
import { FlightsService } from './flights.service';
describe('FlightsService', () => {
let service: FlightsService;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [FlightsService],
}).compile();
service = moduleRef.get(FlightsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});#2. 集成 / e2e —— 测整条服务链
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
describe('Flights E2E', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleRef.createNestApplication();
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
await app.init();
});
it('POST /flights should validate body', async () => {
await request(app.getHttpServer())
.post('/flights')
.send({ code: '' })
.expect(400);
});
afterAll(async () => {
await app.close();
});
});类比:
单测 = 单个调度岗位演练
e2e = 乘客从进门到登机整链路演练一个成熟 Nest 项目,不应该只会跑 npm run start:dev,还应该能稳定跑测试。