Home > other >  Nestjs Optional DTO during the Unit test
Nestjs Optional DTO during the Unit test

Time:03-04

I have a simple controller:

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

The UpdateUserDto is:

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;    
}

all fields are optional to create partial updates.

I don't have any error in my unit test if I use all fields

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

but I get an error if I use part of it, like:

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'. });

CodePudding user response:

if password is optional (ie., can be undefined), then tell to TS it is: password?: string

  • Related