Search code examples
angularunit-testingjestjs

Angular - Verify FormControl has Validator failing in unit test


I am writing unit tests for a service that receives a FormControl and options specify which Validators should be added and then returned.

My unit test should validate that the FormControl has the required, minLength and maxLength validators, however, it always fails checking that the min or max length validator exists.

When debugging i can verify that it has 3 validators in its array.

For brevity, i've just written it in one test function:

  it('should create input form field validators', () => {
    const control = new FormControl<string>(
      '',
      [
        Validators.required,
        Validators.minLength(1),
        Validators.maxLength(9)
      ]
    );

    expect(control.hasValidator(Validators.required)).toBeTruthy();

    // the next two lines should pass as true, but both fail.
    expect(control.hasValidator(Validators.minLength(1))).toBeTruthy();
    expect(control.hasValidator(Validators.maxLength(9))).toBeTruthy()
  });

This should be very straight forward. Is there something I am missing here? Why is the logic for Required passing, but the others fail?


Solution

  • Looks like a reference issue:

    Example Code from Angular docs: https://angular.io/api/forms/AbstractControl#reference-to-a-validatorfn-1

    // Reference to the RequiredValidator
    const ctrl = new FormControl<number | null>(0, Validators.required);
    expect(ctrl.hasValidator(Validators.required)).toEqual(true)
    
    // Reference to anonymous function inside MinValidator
    const minValidator = Validators.min(3);
    const ctrl = new FormControl<number | null>(0, minValidator);
    expect(ctrl.hasValidator(minValidator)).toEqual(true)
    expect(ctrl.hasValidator(Validators.min(3))).toEqual(false)
    

    So your code should look like that:

    it('should create input form field validators', () => {
      const minValidator = Validators.minLength(1);
      const maxValidator = Validators.maxLength(9);
    
      const control = new FormControl<string>('', [Validators.required, minValidator, maxValidator]);
    
      expect(control.hasValidator(Validators.required)).toBeTruthy();
      expect(control.hasValidator(minValidator)).toBeTruthy();
      expect(control.hasValidator(maxValidator)).toBeTruthy();
    });