I have a custom model-driven form validator to validate maximum text length
export function maxTextLength(length: string) {
return function (control: FormControl) {
const maxLenghtAllowed: number = +length;
let value: string = control.value;
if (value !== '' && value != null) {
value = value.trim();
}
if (value != null && value.length > maxLenghtAllowed) {
return { maxTextLength: true };
}else {
return null;
}
}
}
How to write a unit test case form this?
Here's an example inspired by Subashan's answer which outlines the basic procedure:
import { maxTextLength } from '...';
describe('maxTextLength', () => {
const maxTextLengthValidator = maxTextLength(10);
const control = new FormControl('input');
it('should return null if input string length is less than max', () => {
control.setValue('12345');
expect(maxLengthValidator(control)).toBeNull();
});
it('should return correct object if input string length is more than max', () => {
control.setValue('12345678901');
expect(maxLengthValidator(control)).toEqual({ maxTextLength: true });
});
});
I haven't tested it but it's similar to something I've written and it shows the basic approach.
I would recommend changing validator parameter type to number
:
export function maxTextLength(length: number) {