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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With