0

我正在使用打字稿进行 nodeJs 项目。在这里,我使用 class-validator 来验证输入并使用 jest 来运行单元测试。

但是,我不确定如何测试自定义错误消息。我看到了很多使用函数,但几乎没有用于类。

这是错误消息

Matcher error: received value must be a function

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

这是我的代码

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

日期条件检查.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!'
      }
    }

如果您需要任何额外信息,请告诉我。感谢您的所有帮助!

4

1 回答 1

0

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);
    })
});
于 2021-07-08T19:41:20.357 回答