I was trying to mock ControlContainer for FormArray, but i have searched online that only FormGroup and FormControl could be mocked. Is there any workaround for this?
My code as shown below:
create-trip-details.component.html (this is the parent component)
<app-destinations></app-destinations>
create-trip-details.component.ts (this is the parent component)
ngOnInit(): void {
this.createTripDetailsForm = this.initializeCreateTripDetailsForm();
}
initializeCreateTripDetailsForm() {
return this.fb.group(
{
staticQn2: this.getBasicRequiredControl(),
destinations: this.fb.array([]),
}
);
}
get destinations(){
return this.createTripDetailsForm.controls['destinations'] as FormArray;
}
destinations.component.ts (this is the children component)
constructor(
public controlContainer: ControlContainer) {
}
ngOnInit(): void {
this.destinations.push(this.initDestinationFormGrp());
}
initDestinationFormGrp(){
return this.fb.group({
ctryName: [null, { validators: [Validators.required]}],
cityName: [null, { validators: [Validators.required]}],
dateFrom: [null, { validators: [Validators.required]}],
dateTo: [null, { validators: [Validators.required]}]
},
{
validators: this.validateDateFromLaterThanDateTo()
})
}
get destinations(){
return this.controlContainer.control.get('destinations') as FormArray;
}
destinations.component.spec.ts:
it('validate from and to date in destinations component', () => {
//ERROR here! - COULD NOT GET component.destinations BELOW!
//the objective is to allow my component to access child component (destinations) via control container
component.destinations.setValue(component.sharedVar.createTripModel.tripDetails.destinations);
fixture.detectChanges();
component.validateDateFromAndTo(0);
expect(component.getDestinationFormDateFrom(0).errors).toBe(null);
expect(component.getDestinationFormDateTo(0).errors).toBe(null);
});
Error "TypeError: Cannot read properties of undefined (reading 'get')" was shown on "component.destinations" in destinations.component.spec.ts as shown above in the comments. I have tried mocking Control Container as shown in URL below, but seems like it is not applicable for Form Array.