我有一个简单的 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/