testing - Nestjs 单元测试期间可选的 DTO

标签 testing nestjs

我有一个简单的 Controller :

@Patch('/:userId')
  public async updateUser(    
    @Param('userId') userId: string,
    @Body() userUpdate: UpdateUserDto): Promise<any> {  
    await this.usersService.update(userId, userUpdate);
}

UpdateUserDto 是:

import { IsEmail,IsString, IsOptional, MaxLength, IsNotEmpty} from "class-validator";

export class UpdateUserDto{
    
    @IsEmail()
    @IsOptional()
    email:string;
     
    @IsString()
    @IsOptional()
    password:string;

    @IsString()
    @MaxLength(30)
    @IsNotEmpty()
    @IsOptional()
    name: string;
  
    @IsString()
    @MaxLength(40)
    @IsNotEmpty()
    @IsOptional()
    username: string;    
}

创建部分更新时,所有字段都是可选的。

如果我使用所有字段,我的单元测试中不会出现任何错误

it('test', async () => {
    const users = await controller.updateUser('10',{name: "testname",username:"fakeUser",email:"email",password:"S"});
  });

但是如果我使用它的一部分,我会收到错误,例如:

it('test', async () => {
    const users = await controller.updateUser('10',{name: "testname",email:"email",password:"S"});

Argument of type '{ name: string; email: string; password: string; }' is not assignable to parameter of type 'UpdateUserDto'. Property 'username' is missing in type '{ name: string; email: string; password: string; }' but required in type 'UpdateUserDto'. });

最佳答案

如果password是可选的(即可以是未定义),则告诉TS它是:password?: string

关于testing - Nestjs 单元测试期间可选的 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71341335/

相关文章:

java - 如何跨具有不同依赖项的模块重复一组测试?

python - 应该如何构建 python 源代码分发以便测试可以运行?

android - Catch Android 随机崩溃技巧

javascript - 如何模拟正在测试的服务调用的函数的实现?

jestjs - 找不到 Nestjs 测试模块

express - NestJS - 默认(通配符)路由?

oracle - 重置 oracle 数据库以进行测试的最快方法

angular - 单元测试 Angular 2 服务主题

Nx 上的 Nestjs REPL

nestjs - Nest 无法解析 AuthService (?) 的依赖关系。请确保索引 [0] 处的参数在 AuthModule 上下文中可用