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

如何测试使用@Query装饰器和Validation Pipes的Nestjs路由

问题原因

你本地运行服务时,已经在启动入口(通常是main.ts)里全局注册了ValidationPipe,但测试环境创建测试应用实例时没有挂载这个管道,所以class-validator的校验逻辑完全没有生效,自然不会返回400错误。

解决方法

1. 给测试用的Nest应用全局注册ValidationPipe

修改测试代码里的beforeAll逻辑,在nestApp = app.createNestApplication()之后、await nestApp.init()之前添加管道注册代码,配置要和你实际项目里的管道配置保持一致:

import { ValidationPipe } from '@nestjs/common';

// 原有beforeAll代码
beforeAll(async () => {
  app = await Test.createTestingModule({
    controllers: [AppController],
    providers: [AppService],
    imports: [HttpModule],
  }).compile();
  appService = app.get<AppService>(AppService);
  nestApp = app.createNestApplication();
  // 新增:全局注册ValidationPipe
  nestApp.useGlobalPipes(new ValidationPipe({
    // 如果你实际使用时开了whitelist、transform等配置,这里也要对应加上
    whitelist: true,
    transform: true,
  }));
  await nestApp.init();
  return;
});

2. 补全缺失参数的测试用例

修改Incorrect query分组下的两个测试用例:

describe('Incorrect query', () => {
  test("Returns an error if 'q' query parameter is missing.", async () => {
    const response = await supertest(nestApp.getHttpServer())
      .get('/news?pageNumber=1');
    expect(response.statusCode).toBe(400);
    expect(response.body).toStrictEqual({
      statusCode: 400,
      message: ["q should not be empty"],
      error: "Bad Request"
    });
  });

  test("Returns an error if 'pageNumber' query parameter is missing.", async () => {
    const response = await supertest(nestApp.getHttpServer())
      .get('/news?q=test');
    expect(response.statusCode).toBe(400);
    expect(response.body).toStrictEqual({
      statusCode: 400,
      message: ["pageNumber should not be empty"],
      error: "Bad Request"
    });
  });
});

修改完成后重新运行测试就能复现和生产环境一致的校验错误了。

内容的提问来源于stack exchange,提问作者doublethink13

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:15:04