Angular 中十进制验证器的单元测试

Unit Test for Decimal Validator in Angular

我试图寻找源代码,但找不到关于为十进制验证器创建单元测试的信息。如果我在 component.ts 中的代码像这样

  DecimalValidator(decimal: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      const value = control.value;
      if (value.includes('.')) {
        const valArray = value.split('.');
        if (valArray[1].length > decimal) {
          return { 'maxDecimal': true };
        } else {
          return null;
        }
      } else {
        return null;
      }
    };
  }

如何在 component.spec.ts 中为此函数编写单元测试?

A ValidatorFn 通过执行传入 FormControl 的函数进行测试,测试值:

describe('DecimalValidator', () => {

    it('should not error on an empty string', () => {
        expect(MyValidators.DecimalValidator(2)(new FormControl(''))).toBeNull();
    });

    it('should not error on null', () => {
        expect(MyValidators.DecimalValidator(2)(new FormControl(null))).toBeNull();
    });

    it('should not error on undefined', () => {
        expect(MyValidators.DecimalValidator(2)(new FormControl(undefined))).toBeNull();
    });

    it('should not error if decimal digit count is less than or equal to parameter', () => {
        expect(MyValidators.DecimalValidator(2)(new FormControl('1.11'))).toBeNull();
        expect(MyValidators.DecimalValidator(2)(new FormControl('1.1'))).toBeNull();
        expect(MyValidators.DecimalValidator(2)(new FormControl('1'))).toBeNull();
        expect(MyValidators.DecimalValidator(1)(new FormControl('1.1'))).toBeNull();
        expect(MyValidators.DecimalValidator(1)(new FormControl('1'))).toBeNull();
        expect(MyValidators.DecimalValidator(0)(new FormControl('1'))).toBeNull();
    });

    it('should error if decimal digit count is greater than parameter', () => {
        expect(MyValidators.DecimalValidator(2)(new FormControl('1.111'))).toEqual({ 'maxDecimal': true });
        expect(MyValidators.DecimalValidator(1)(new FormControl('1.11'))).toEqual({ 'maxDecimal': true });
        expect(MyValidators.DecimalValidator(0)(new FormControl('1.1'))).toEqual({ 'maxDecimal': true });
    });

});

您可以在此处查看 Angular 内置验证器的测试,这可能会有所帮助:https://github.com/angular/angular/blob/a92a89b0eb127a59d7e071502b5850e57618ec2d/packages/forms/src/validators.ts

评论:您可能想要 return 错误对象中的最大十进制数 return { 'maxDecimal': decimal };,因为它可能对向用户显示有用。