How to write a unit test case for a custom validator for angular reactive forms?

Ankit Raonka picture Ankit Raonka · Nov 15, 2017 · Viewed 7k times · Source

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?

Answer

camden_kid picture camden_kid · May 3, 2018

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) {