ianh11
ianh11

Reputation: 147

Unit test Angular form and subFormGroup

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

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26342

When you run the detectChanges() the component is initialized. Check the following:

  1. Are you running a beforeEach function before the it() function?
  2. Why are you returning the assignment? When is the buildForm function called in your component? Better to cause the call than re-running it.
  3. What is your HTML. Try to bind on [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

Related Questions