Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs - How to unit test a DTO?

I am asking you for help. I have created a DTO that looks like it (this is a smaller version) :

export class OfImportDto {

    @IsString({
        message: "should be a valid product code"
    })
    productCode: string;

    @IsString({
        message: "Enter the proper product description"
    })
    productDescription: string;

    @IsDateString({
        message: "should be a valid date format, for example : 2017-06-07T14:34:08+04:00"
    })
    manufacturingDate : Date

    @IsInt({
        message: "should be a valid planned quantity number"
    })
    @IsPositive()
    plannedQuantity: number;

the thing is that i am asking to test that, with a unit test and not a E2E test. And I Don't know how to do that. For instance, I would like to unit test 1/ if my product code is well a string, a string should be created, if not, throw my exception 2/ if my product description is well a string, a string should be created, if not, throw my exception ... and so on.

So, can I made a spec.ts file to test that? If yes, how? If not, is it better to test it within the service.spec.ts? If so, how?

Thank you very much, any help would be very helpful :)

like image 819
JimmyB Avatar asked Mar 25 '20 15:03

JimmyB


1 Answers

It would be possible to create a OfImportDTO.spec.ts file (or whatever your original file is called), but the thing is, there isn't any logic here to test. The closest thing you could do is create an instance of a Validator from class-validator and then instantiate an instance of the OfImportDto and then check that the class passes validation. If you add logic to it (e.g. getters and setters with specific functions) then it could make sense for unit testing, but otherwise, this is basically an interface being called a class so it exists at runtime for class-validator

like image 60
Jay McDoniel Avatar answered Sep 25 '22 07:09

Jay McDoniel