Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test for Decimal Validator in Angular

I tried looking for the source, but I can not find which tell about create unit tests for decimal validators. If my code in component.ts like this

  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;
      }
    };
  }

how do I write the unit test in component.spec.ts for this function?

like image 272
justTrustMe Avatar asked Dec 10 '25 17:12

justTrustMe


1 Answers

A ValidatorFn is tested by executing the function having passed in a FormControl with the test value:

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

});

You can see tests for Angular's built-in validators here, which might help: https://github.com/angular/angular/blob/a92a89b0eb127a59d7e071502b5850e57618ec2d/packages/forms/src/validators.ts

A comment: you might want to return the maximum decimal count in the error object return { 'maxDecimal': decimal }; as it could be useful to show to the user.

like image 72
andrew Avatar answered Dec 12 '25 15:12

andrew