Unit Test of FormControl in Angular 9: TypeError: Cannot read property 'validate' of null (Validators.compose)

Viewed 596

I always get the error TypeError: Cannot read property 'validate' of null with Validators.compose when trying to test the below code

this.form.controls.phoneNumber.setValidators([
Validators.compose([this.utilsService.conditionalRequired(isRequired)]), Validators.pattern(Regex[regexKey])
]);

any idea how can I mock (Validators.compose) part?

1 Answers

These 'validate' of undefined (or null in your case) are tough to find out the cause, but generally make sure that everything is defined before it's being used.

Below is how you instantiate your FormGroup, that a component then does a .addControl or a setValidators

let formBuilder: FormBuilder = new FormBuilder();
let mockFormGroup: FormGroup = formBuilder.group({phoneNumber:new FormControl(this.obj.id, Validators.required));});

You'll also need to make a MockUtilsService and provide it into the spec

Related