Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nestjs Optional DTO during the Unit test

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading