简体   繁体   English

unt 测试 jest 自定义验证类(类验证器)及其消息?

[英]unt test for jest custom validation class (class-validator) and its message?

I am working on a nodeJs project, using typescript.我正在使用打字稿进行 nodeJs 项目。 Here I am using class-validator to validate inputs and uses jest to run unit test.在这里,我使用 class-validator 来验证输入并使用 jest 来运行单元测试。

However, I'm not sure how I could test customized error message.但是,我不确定如何测试自定义错误消息。 I saw a lots of to use functions but almost none for class.我看到了很多使用函数,但几乎没有用于课堂。

Here's the error message这是错误信息

Matcher error: received value must be a function

Received has type:  string
Received has value: "1"

Here's my code这是我的代码

unit_test.ts unit_test.ts


  
 
  
  
  
  describe("GET: search/api", () => {
      class MyClass {
       @IsDefined()
       @Validate(DateConditionCheck, {
      message: 'Please check your date input!'
    })
       dd: number;
    };

    const model: any = new MyClass ();

    model.dd = 1;

    it('should throw an error message when date input is incorrect', async () => {
      return validate(model).then(errors => {
         expect(errors.length).toBe(1);
         expect(model.dd).toThrow('Date condition seems wrong!');
     });
   });
 });

dateconditioncheck.ts日期条件检查.ts


  
 
  
  
  
    import {
      IsDefined,
      IsBoolean,
      IsString,
      IsEmail,
      IsNumberString,
      IsAlphanumeric,
      IsNotEmpty,
      MaxLength,
      MinLength,
      IsNumber,
      IsEnum,
      IsOptional,
      Max,
      Min,
      Length,
      Matches,
      Validate,
      ValidatorConstraint,
      ValidatorConstraintInterface,
      ValidationArguments,
      registerDecorator,
      ValidationOptions
    } from 'class-validator'
    import * as moment from 'moment'

    /**
     * Custom validator
     *
     */
    @ValidatorConstraint({ name: 'dateConditionCheck', async: false })
    export class DateConditionCheck implements ValidatorConstraintInterface {
      validate(text: any, args: ValidationArguments) {
        const jsondata = JSON.parse(JSON.stringify(args.object))
        if (args.property === 'dd') {
          return moment(Number(jsondata.yyyy) + '-' + Number(jsondata.mm) + '-' + Number(jsondata.dd), 'YYYYMMDD').isValid()
        }

        if (args.property === 'dd2') {
          return moment(
            Number(jsondata.yyyy2) + '-' + Number(jsondata.mm2) + '-' + Number(jsondata.dd2),
            'YYYYMMDD'
          ).isValid()
        }
        return true
      }

      defaultMessage(args: ValidationArguments) {
        return 'Please check your date input!'
      }
    }

Please let me know if you need any extra infos.如果您需要任何额外的信息,请告诉我。 Appreciate all your helps!感谢您的所有帮助!

Kinda late, but here is why you can test a customized error message:有点晚了,但这就是您可以测试自定义错误消息的原因:

First of all, is important to know how the "error" object is returned (i simply debbuged it, mine was like this):首先,重要的是要知道“错误”对象是如何返回的(我只是对其进行了调试,我的就是这样):

[
    ValidationError {
      target: LoginDto {},
      value: undefined,
      property: 'username',
      children: [],
      constraints: { isNotEmpty: "Username can't be empty" }
    },
    ValidationError {
      target: LoginDto {},
      value: undefined,
      property: 'password',
      children: [],
      constraints: { isNotEmpty: "Password can't be empty" }
    }
  ]

Okay!好的! Now we need to expect something matching these patterns (You can ignore non important stuff现在我们需要期待匹配这些模式的东西(你可以忽略不重要的东西

it('should not accept undefined username nor password', () => {
    return validate(logindto).then(errors => {
        expect(errors.length).toBe(2);
        const expectedErrorObject = [
            { property: 'username', constraints: { isNotEmpty: "Username can't be empty" } },
            { property: 'password', constraints: { isNotEmpty: "Password can't be empty" } }
        ]
        expect(errors).toMatchObject(expectedErrorObject);
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM