Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Validation pipe is throwing the expect error for improperly shaped request on NestJS

I'm using NestJS 7.0.2 and have globally enabled validation pipes via app.useGlobalPipes(new ValidationPipe());.

I'd like to be able to have a unit test that verifies that errors are being thrown if the improperly shaped object is provided, however the test as written still passes. I've seen that one solution is to do this testing in e2e via this post, but I'm wondering if there is anything I'm missing that would allow me to do this in unit testing.

I have a very simple controller with a very simple DTO.

Controller

async myApi(@Body() myInput: myDto): Promise<myDto | any> {
  return {};
}

DTO

export class myDto {
  @IsNotEmpty()
  a: string;

  @IsNotEmpty()
  b: string | Array<string>
}

Spec file

  describe('generate', () => {
    it('should require the proper type', async () => {
      const result = await controller.generate(<myDto>{});
      // TODO: I expect a validation error to occur here so I can test against it.
      expect(result).toEqual({})
    })
  })

It also fails if I do not coerce the type of myDto and just do a ts-ignore on a generic object.

like image 776
zmanc Avatar asked Oct 12 '25 09:10

zmanc


1 Answers

Just test your DTO with ValidationPipe:

it('validate DTO', async() => {
    let target: ValidationPipe = new ValidationPipe({ transform: true, whitelist: true });
    const metadata: ArgumentMetadata = {
        type: 'body',
        metatype: myDto,
        data: ''
    };
    await target.transform(<myDto>{}, metadata)
        .catch(err => {
            expect(err.getResponse().message).toEqual(["your validation error"])
        })
});

You can find here complete test examples for ValidationPipe in Nestjs code repository

like image 166
leotesta Avatar answered Oct 15 '25 00:10

leotesta