You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试NestJS中main.ts的端口监听功能

如何测试NestJS中main.ts的端口监听功能

嘿,我懂你想测试main.ts里端口监听逻辑的困惑,其实用Jest配合mock就能轻松搞定,下面给你两种常见的测试思路,按需选就行:

一、单元测试(Mock方式,不启动真实服务)

首先得稍微调整下你的main.ts,把bootstrap函数导出,方便测试代码调用它,最好还把创建好的app返回:

import { NestFactory } from '@nestjs/core';
import { RunnerModule } from './runner.module';

// 导出bootstrap函数,同时返回app实例
export async function bootstrap() {
  const app = await NestFactory.create(RunnerModule);
  await app.listen(3000);
  return app;
}

bootstrap();

接下来创建对应的测试文件main.spec.ts,我们用Jest来mock掉NestFactory,不用真的启动服务器,只验证逻辑是否正确:

import { NestFactory } from '@nestjs/core';
import { bootstrap } from './main';
import { RunnerModule } from './runner.module';

// 直接mock整个@nestjs/core模块里的NestFactory
jest.mock('@nestjs/core', () => ({
  NestFactory: {
    // 让create方法返回一个带mock listen的假app
    create: jest.fn().mockResolvedValue({
      listen: jest.fn().mockResolvedValue(true),
    }),
  },
}));

describe('main.ts 端口监听逻辑', () => {
  it('应该正确调用listen方法并传入3000端口', async () => {
    const app = await bootstrap();

    // 验证NestFactory是否用正确的模块创建了实例
    expect(NestFactory.create).toHaveBeenCalledWith(RunnerModule);
    // 核心断言:listen方法确实传入了3000
    expect(app.listen).toHaveBeenCalledWith(3000);
  });
});

这种方式的好处是测试速度快,不会占用真实端口,纯验证代码逻辑是否符合预期。

二、集成测试(启动真实服务验证)

如果你想确认服务真的能在3000端口正常响应请求,可以写个集成测试,用supertest这类工具来验证:

import * as request from 'supertest';
import { bootstrap } from './main';

describe('main.ts 端口监听集成测试', () => {
  let app: any;

  // 测试前启动服务
  beforeAll(async () => {
    app = await bootstrap();
  });

  // 测试结束后关闭服务,释放端口
  afterAll(async () => {
    await app.close();
  });

  it('应该能在3000端口接收到请求', async () => {
    // 这里可以请求你实际的接口,比如健康检查接口,或者根路径
    const response = await request('http://localhost:3000').get('/');
    // 根据你的实际接口返回做断言,比如状态码200
    expect(response.status).toBe(200);
  });
});

这种方式更贴近真实场景,但测试速度会慢一点,而且要注意测试结束后关闭服务避免端口占用。

备注:内容来源于stack exchange,提问作者c9 m8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 07:58:07