TLNR:我试图在控制器规范中而不是在 e2e 规范中测试 DTO 验证,后者正是为此而设计的。McDoniel 的回答为我指明了正确的方向。
我开发了一个 NestJS 入口点,如下所示:
@Post()
async doStuff(@Body() dto: MyDto): Promise<string> {
// some code...
}
Run Code Online (Sandbox Code Playgroud)
我使用class-validator这样当我的 API 收到请求时,有效负载被解析并转换为 MyDto 对象,并执行作为 MyDto 类中的注释的验证。请注意,MyDto 有一个 MySubDto 类的嵌套对象数组。使用@ValidateNested 和@Type 注释,嵌套对象也可以正确验证。
这很好用。
现在我想为执行的验证编写测试。在我的 .spec 文件中,我写道:
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);
}
Run Code Online (Sandbox Code Playgroud)
这将失败,因为经过验证的 dto 对象不是 MyDto。我可以这样重写测试:
it('should FAIL on invalid DTO', …Run Code Online (Sandbox Code Playgroud)