Sub topic 15
Testing dynamic forms
This chapter assumes you know TypeScript, Angular standalone components, and the basics of FormControl, FormGroup and Validators. It also assumes you have read the earlier chapters on FormArray, adding and removing controls, validation, and populating from data.
Why test the form model
A dynamic form changes shape at runtime. Bugs usually appear after a sequence of actions, such as adding three rows and removing the middle one. Testing the form model catches these bugs without a browser. Test the model first, then add a few tests that go through the template.
Test the model directly
A FormArray is a plain object. You can test it with no TestBed. The test below checks the minItems validator and the setItems behavior from earlier chapters.
import { FormArray, FormControl } from '@angular/forms';
import { minItems } from './min-items';
describe('FormArray model', () => {
it('reports an error when the array is too short', () => {
const items = new FormArray<FormControl<string>>([], minItems(1));
expect(items.valid).toBe(false);
expect(items.errors).toEqual({ minItems: { required: 1, actual: 0 } });
});
it('becomes valid after a push', () => {
const items = new FormArray<FormControl<string>>([], minItems(1));
items.push(new FormControl('a', { nonNullable: true }));
expect(items.valid).toBe(true);
});
it('removeAt shifts later controls', () => {
const items = new FormArray([
new FormControl('a'),
new FormControl('b'),
new FormControl('c'),
]);
items.removeAt(1);
expect(items.value).toEqual(['a', 'c']);
});
});Adding or removing a control recalculates the validity of the array. You do not need to call updateValueAndValidity() yourself after push or removeAt.
Test the component
For the component, create it with TestBed, call fixture.detectChanges(), and act on the form through its public methods or through the DOM. This example uses OrderFormComponent from the earlier chapter.
import { TestBed } from '@angular/core/testing';
import { OrderFormComponent } from './order-form.component';
describe('OrderFormComponent', () => {
function setup() {
const fixture = TestBed.createComponent(OrderFormComponent);
fixture.detectChanges();
return fixture;
}
it('starts with one row', () => {
const fixture = setup();
const rows = fixture.nativeElement.querySelectorAll('[formgroupname]');
expect(rows.length).toBe(1);
});
it('adds a row when the button is clicked', () => {
const fixture = setup();
const addButton = Array.from<HTMLButtonElement>(
fixture.nativeElement.querySelectorAll('button'),
).find((b) => b.textContent?.includes('Add item'))!;
addButton.click();
fixture.detectChanges();
expect(fixture.componentInstance.items.length).toBe(2);
expect(fixture.nativeElement.querySelectorAll('[formgroupname]').length).toBe(2);
});
it('disables submit while a row is invalid', () => {
const fixture = setup();
const submit: HTMLButtonElement =
fixture.nativeElement.querySelector('button[type="submit"]');
expect(submit.disabled).toBe(true);
fixture.componentInstance.items.at(0).patchValue({ name: 'Pen' });
fixture.detectChanges();
expect(submit.disabled).toBe(false);
});
});Note the call to fixture.detectChanges() after each action. Without it the template still shows the old state, and your assertions on the DOM will fail.
What to cover
Common errors
- Forgetting
detectChanges(). The model changes, but the DOM does not until change detection runs. - Using
patchValueto fill an empty array. It does not create controls. CallsetItemsorpushfirst, then assert onlength. - Reading the wrong value.
valueleaves out disabled controls. Assert ongetRawValue()if your form disables any. - Asserting on row order after
removeAt. Indexes shift, so check the wholevaluearray instead of a single index.
Exercise
A test calls component.items.patchValue([{ name: 'Pen', quantity: 2 }]) on a form whose array is empty, then expects items.length to be 1. Why does it fail, and how do you fix the test?
Show answer
patchValue only updates controls that already exist, and a FormArray does not create controls for missing entries, so the length stays 0. Fix the test by calling setItems([{ name: 'Pen', quantity: 2 }]) (which clears the array and pushes one control per record), or by calling items.push(component.createItem('Pen', 2)), then assert on length.