11

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?

Steffi Keran Rani J
  • 3,667
  • 4
  • 34
  • 56
Ankit Raonka
  • 6,429
  • 10
  • 35
  • 54

2 Answers2

19

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) {
camden_kid
  • 12,591
  • 11
  • 52
  • 88
3

You can create a from group in your test with one formControl (in this case some input).

Then leverage the setValue function of formControl to set a value that will pass the unit test.

Then you can pass this form control to the validator function and assert that it returns null (should return null if there's no error).

And another test for which there's an error.

S M
  • 41
  • 5