mardi 2 mars 2021

How to unit test whether form validations are added dynamically in Jest?

I'm struggling with how to write a unit test for checking if my form validations were added to a FormControl in Angular.

It's a simple form with a phone field. I subscribe to that field and add or remove a validator depending on the field being empty or not. The code works as intended but I don't get how to test the subscription and valueChanges portion.

How can I write a Jest test to cover the following subscription?

this.form = new FormGroup({
  name: new FormControl('', [Validators.required]),
  phone: new FormControl(''),
)}

// Validate that phone is either blank or a valid phone number
this.form.controls.phone.valueChanges.subscribe(data => {
  if (data.phone !== '') {  // Add validations to phone
    this.form.controls.phone.setValidators([Validators.pattern(PHONE_VALIDATOR)]);
  } else {  // Remove validation from phone when field is blank
    this.form.controls.phone.clearValidators();
  }
});

Best Attempt at Testing. It passes but my coverage is showing 0% for the .valueChanges section.

    it('should add phone validation when phone is not blank', () => {
      component.ngOnInit();
      let phoneField = component.form.controls.phone;
      phoneField.setValidators([Validators.pattern(PHONE_VALIDATOR), beetweenxAndyNumericChars(7, 11, false)]);
      phoneField.setValue('123');

      component.save();

      expect(phoneField.valid).toBeFalsy();
    });

The above test runs but doesn't improve my code coverage. I'm stuck on how to improve the code coverage

Aucun commentaire:

Enregistrer un commentaire