全书目录

第七篇:NestJS 完全指南 —— 国际机场总调度宇宙

第十七章:测试 —— 真机场开航前要演练,Nest 也一样

1 分钟 122 字 第 197 / 962 个阅读单元

Nest 官方测试能力基于 @nestjs/testing

#1. 单元测试 —— 只测调度员
ts
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 —— 测整条服务链
ts
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();
  });
});

类比:

text
单测 = 单个调度岗位演练
e2e = 乘客从进门到登机整链路演练

一个成熟 Nest 项目,不应该只会跑 npm run start:dev,还应该能稳定跑测试。