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

Viewed 4539

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.

2 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

To test custom ValidationPipe:

    let target = new ValidationDob();
    const metadata: ArgumentMetadata = {
      type: 'query',
      metatype: GetAgeDto,
      data: '',
    };

  it('should throw error when dob is invalid', async () => {
    try {
      await target.transform(<GetAgeDto>{ dob: 'null' }, metadata);
      expect(true).toBe(false);
    } catch (err) {
      expect(err.getResponse().message).toEqual('Invalid dob timestamp');
    }
  });
Related