如何使用NestJS和类验证器手动测试输入验证 [英] How to manually test input validation with NestJS and class-validator

查看:393
本文介绍了如何使用NestJS和类验证器手动测试输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TLNR:我正在尝试在控制器规范中而不是在e2e规范中测试DTO验证,而e2e规范正是为此而设计的.麦道尼尔的回答为我指明了正确的方向.

TLNR: I was trying to test DTO validation in the controller spec instead of in e2e specs, which are precisely crafted for that. McDoniel's answer pointed me to the right direction.

我开发了一个NestJS入口点,如下所示:

I develop a NestJS entrypoint, looking like that:

@Post()
async doStuff(@Body() dto: MyDto): Promise<string> {
  // some code...
}

我使用class-validator,以便当我的API收到请求时,将有效负载解析并转换为MyDto对象,并执行作为MyDto类中的批注显示的验证.请注意,MyDto具有MySubDto类的嵌套对象数组.使用@ValidateNested和@Type批注,嵌套对象也可以正确验证.

I use class-validator so that when my API receives a request, the payload is parsed and turned into a MyDto object, and validations present as annotations in MyDto class are performed. Note that MyDto has an array of nested object of class MySubDto. With the @ValidateNested and @Type annotations, the nested objects are also validated correctly.

这很好用.

现在,我想为执行的验证编写测试.在我的.spec文件中,我写:

Now I want to write tests for the performed validations. In my .spec file, I write:

import { validate  } from 'class-validator';
// ...
it('should FAIL on invalid DTO', async () => {
  const dto = {
    //...
  };
  const errors = await validate( dto );
  expect(errors.length).not.toBe(0);
}

这失败,因为已验证的dto对象不是MyDto.我可以这样重写测试:

This fails because the validated dto object is not a MyDto. I can rewrite the test as such:

it('should FAIL on invalid DTO', async () => {
  const dto = new MyDto()
  dto.attribute1 = 1;
  dto.subDto = { 'name':'Vincent' };
  const errors = await validate( dto );
  expect(errors.length).not.toBe(0);
}

现在可以在MyDto对象上正确进行验证,但不能在嵌套的subDto对象上进行验证,这意味着我将不得不使用根据类实例化Dto的所有aaa对象,这将大大降低效率.另外,实例化类意味着如果我自愿省略某些必需的属性或指示错误的值,TypeScript将引发错误.

Validations are now properly made on the MyDto object, but not on my nested subDto object, which means I will have to instantiate aaaall objects of my Dto with according classes, which would be much inefficient. Also, instantiating classes means that TypeScript will raise errors if I voluntarily omits some required properties or indicate incorrect values.

所以问题是:

如何在测试中使用NestJs内置的请求主体解析器,以便可以编写想要用于dto的任何JSON,将其解析为 as MyDto对象,并使用class-validator进行验证验证功能?

How can I use NestJs built-in request body parser in my tests, so that I can write any JSON I want for dto, parse it as a MyDto object and validate it with class-validator validate function?

也欢迎使用任何其他更好的实践方法来进行验证!

Any alternate better-practice ways to tests validations are welcome too!

推荐答案

要使用验证管道测试输入验证,我认为达成此目标的最佳位置是在e2e测试中,而不是在单元测试中,只需确保您记得注册管道(如果通常使用app.useGlobalPipes()而不是使用依赖项注入)

To test input validation with the validation pipes, I think it is agreed that the best place to do this is in e2e tests rather than in unit tests, just make sure that you remember to register your pipes (if you normally use app.useGlobalPipes() instead of using dependency injection)

这篇关于如何使用NestJS和类验证器手动测试输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆