Unit testing FormGroup/FormArray

Viewed 2931

I have a function that accepts an AbstractControl variable and performs the following action:

new(item: AbstractControl) {
  item['controls'].myArray.push(
    this.formBuilder.group({
      // my attributes here
    )}
  )
}

The object structure when I perform console.log(item) is the following (I have only shown important info):

FormGroup {
  controls: {
    …,
    items: FormArray { 
      …,
      controls: Array(5) [FormGroup, FormGroup, …] 
  }
}

However I cannot seem to test it properly...

it('Should add', () => {
    const fb = new FormBuilder();
    const myObject = fb.group([example]);

    component.new(myObject);

    const packagesLength = component.myFormGroup.get('data')['controls'][0]['controls']['items']['controls'].length;

    expect(packagesLength).toEqual(2);
  });

All I get from the console is

Cannot read property 'push' of undefined

If I remove the array brackets from for my FormBuilder.group (ie fb.group(example);, I receive the message:

customer.controls.packages.push is not a function

1 Answers

Would't you need to add a formArray with the name of 'myArray' in you test rather than an array in a formGroup without a control name? So something like:

it('Should add', () => {
    const fb = new FormBuilder();
    const myObject = fb.group('myArray': fb.array());

    component.new(myObject);

    const packagesLength = component.myFormGroup.get('data')['controls'][0] ['controls']['items']['controls'].length;

    expect(packagesLength).toEqual(2);
});
Related