Angular - Forcing a reactive form to be valid in a unit test

Why not just clear the validators list?

// If there are any async validators
//
this.myForm.clearAsyncValidators();
// If there are any normal validators
//
this.myForm.clearValidators();
// Doing the validation on all the controls to put them back to valid
//
this.formGroup.updateValueAndValidity();

This will ensure your form has no validators, thus being valid.


using only javascript, you can do:

      Object.defineProperty(comp.editForm, 'valid', {
        get: () => true
      });

to override the getter, to always return true.


If someone is still struggling with this:

As @realappie answer suggests, we should clear all sync/async validators. But the validators in most cases are on the controls and not the form itself . So, just loop all the controls perform this operation on each control.

From the test file it should look like:

const controls = component.myForm.controls;

for (const control in controls) {
    // Clear sync validators - use clearAsyncValidators() for async
    // validators
    controls[control].clearValidators();
    // should update just the control and not everything
    controls[control].updateValueAndValidity({ onlySelf: true });
}
component.myForm.updateValueAndValidity();