Reputation: 147
Getting an error when trying to build the form in the test spec. The form build function also build a sub form array. Looking for the best way to test this
component.ts
buildForm() {
return this.peopleForm = this.fb.group({
people: this.fb.array([this.buildSubFormGroup()]),
effective_date: [this.firstOfNextMonth(), Validators.required]
});
}
buildSubFormGroup(type: string = 'primary') {
return this.fb.group({
type: [type],
first_name: ['', Validators.required],
last_name: ['', Validators.required],
dob: ['', Validators.required],
gender: ['', Validators.required],
uses_tobacco: ['', Validators.required],
affordable_care: ['', Validators.required],
is_pregnant: [''],
});
}
component.spec.ts
it('should be able to build the peopleForm', () => {
component.buildForm();
fixture.detectChanges();
expect(component.peopleForm.controls['type'].value).not.toBeNull();
});
Error: Error: There is no FormControl instance attached to form control element with name: 'effective_date'
Upvotes: 1
Views: 421
Reputation: 26342
When you run the detectChanges()
the component is initialized. Check the following:
beforeEach
function before the it()
function?[FormControl]
instead of formControlName
The idea in unit testing is to cause actions that call the respective functions.
Example:
ngOnInit
when the detectChanges() is called.
onClickSomething
when you click the item that calls it, not by calling the compoment.onClickSomething function.
You are testing the component on the whole.
For more information, please add the html and the entire component code.
Upvotes: 1