Sub topic 15
Testing dynamic forms
This chapter shows how to test a form that grows and shrinks at runtime. It assumes you know TypeScript, Angular components and templates, and basic reactive forms. It also assumes you know the FormArray material from the earlier chapters: push, removeAt, clear, formArrayName, formGroupName, and the minItems validator. The examples use describe, it and expect, which Jasmine, Jest and Vitest all provide.
What to test and at which level
A dynamic form has three kinds of behavior, and each is cheapest to test at a different level.
| Behavior | Example | Cheapest level |
|---|---|---|
| Rules about the array | `minItems(1)` reports an error on an empty array | Plain control, no `TestBed` |
| Component logic | `addItem` and `removeItem` change the row count | Component class |
| Wiring to the template | Clicking Remove deletes one row from the page | Component fixture and DOM |
Start at the lowest level that can fail for the reason you care about. A validator bug shows up in a three-line test. You only need the DOM when the question is whether the template is bound correctly.
Testing the array without Angular's test bed
FormArray, FormGroup and validators are plain classes. You can create them directly and assert on value, errors, valid and length. No TestBed is involved, so these tests run fast.
import { FormArray, FormControl } from '@angular/forms';
import { minItems } from './min-items';
describe('minItems', () => {
it('reports an error when the array is too short', () => {
const list = new FormArray<FormControl<string>>([], minItems(1));
expect(list.valid).toBe(false);
expect(list.errors).toEqual({ minItems: { required: 1, actual: 0 } });
});
it('recomputes validity when controls are added and removed', () => {
const list = new FormArray<FormControl<string>>([], minItems(1));
list.push(new FormControl('a', { nonNullable: true }));
expect(list.valid).toBe(true);
list.removeAt(0);
expect(list.valid).toBe(false);
});
});The second test matters because push and removeAt re-run the array's validators. If you ever replace the array's controls in some other way, this test tells you whether validity still tracks the length.
You can also pin down the setValue and patchValue behavior from the earlier chapter. Neither creates missing controls, but they fail in different ways.
import { FormArray, FormControl } from '@angular/forms';
describe('FormArray value updates', () => {
it('setValue throws when there are more values than controls', () => {
const list = new FormArray([new FormControl('a', { nonNullable: true })]);
expect(() => list.setValue(['x', 'y'])).toThrow();
});
it('patchValue silently ignores the extra values', () => {
const list = new FormArray([new FormControl('a', { nonNullable: true })]);
list.patchValue(['x', 'y', 'z']);
expect(list.length).toBe(1);
expect(list.value).toEqual(['x']);
});
});The second test records a trap: after patchValue with three values, the form looks fine and nothing throws, but two values are gone. A test like this is useful in your own code, because it protects the "clear, then push" loading pattern from being simplified into a patchValue call.
Testing the component class and the DOM
The next spec uses OrderFormComponent from the earlier chapter. It assumes you added the setItems method shown in the chapter on populating from data. Standalone components go in imports, not declarations.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { OrderFormComponent } from './order-form.component';
describe('OrderFormComponent', () => {
let fixture: ComponentFixture<OrderFormComponent>;
let component: OrderFormComponent;
let el: HTMLElement;
const nameInputs = () =>
Array.from(el.querySelectorAll<HTMLInputElement>('input[placeholder="Name"]'));
const button = (label: string) =>
Array.from(el.querySelectorAll('button')).find(
(b) => b.textContent?.trim() === label,
) as HTMLButtonElement;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [OrderFormComponent] });
fixture = TestBed.createComponent(OrderFormComponent);
component = fixture.componentInstance;
el = fixture.nativeElement;
fixture.detectChanges();
});
it('starts with one row and an invalid form', () => {
expect(component.items.length).toBe(1);
expect(nameInputs().length).toBe(1);
expect(component.form.invalid).toBe(true);
expect(button('Submit').disabled).toBe(true);
});
it('adds a row when Add item is clicked', () => {
button('Add item').click();
fixture.detectChanges();
expect(component.items.length).toBe(2);
expect(nameInputs().length).toBe(2);
});
it('removes the row whose Remove button was clicked', () => {
component.addItem();
component.items.at(0).patchValue({ name: 'Pen' });
component.items.at(1).patchValue({ name: 'Ink' });
fixture.detectChanges();
const removeButtons = el.querySelectorAll<HTMLButtonElement>('button');
removeButtons[0].click();
fixture.detectChanges();
expect(component.items.value.map((i) => i.name)).toEqual(['Ink']);
expect(nameInputs()[0].value).toBe('Ink');
});
it('updates the model when the user types', () => {
const input = nameInputs()[0];
input.value = 'Pen';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.form.getRawValue().items[0].name).toBe('Pen');
expect(component.form.valid).toBe(true);
expect(button('Submit').disabled).toBe(false);
});
it('replaces all rows when setItems is called', () => {
component.setItems([
{ name: 'Pen', quantity: 2 },
{ name: 'Ink', quantity: 1 },
{ name: 'Pad', quantity: 5 },
]);
fixture.detectChanges();
expect(nameInputs().map((i) => i.value)).toEqual(['Pen', 'Ink', 'Pad']);
expect(component.form.valid).toBe(true);
});
});Why these tests are written this way
- Call
fixture.detectChanges()after every change. The@forblock renders fromitems.controls. Callingcomponent.addItem()changes the array, but the DOM stays the same until change detection runs. A test that asserts on the DOM right after a method call usually fails for this reason. A click on a real button schedules change detection in a running app, but in a test you should calldetectChanges()yourself so the result does not depend on scheduling. - Assert on the model and the DOM together. The remove test checks
items.valueand the text in the remaining input. A wrongformGroupNameindex would pass the first check and fail the second. The input would then show the other row's data. - Dispatch an
inputevent after settingvalue. Settinginput.valuealone does not notify Angular'sDefaultValueAccessor. The event is what moves the text into the control. - Use
getRawValue()when you assert on submitted data. It matches whatsubmit()reads and includes disabled controls. - Pick stable selectors. The tests find inputs by
placeholderand buttons by label. Selecting by index (removeButtons[0]) is fine here only because the first button in the template is the first row's Remove button. If you add a header button, update the helper.
Testing reactions to changes
valueChanges on a FormArray emits when a control is added, removed or edited. You can test a subscriber without a fixture by collecting emissions into an array.
import { FormArray, FormControl } from '@angular/forms';
describe('FormArray valueChanges', () => {
it('emits on push and removeAt, and can be silenced', () => {
const list = new FormArray<FormControl<string>>([]);
const seen: string[][] = [];
const sub = list.valueChanges.subscribe((v) => seen.push(v));
list.push(new FormControl('a', { nonNullable: true }));
list.removeAt(0);
list.push(new FormControl('b', { nonNullable: true }), { emitEvent: false });
sub.unsubscribe();
expect(seen).toEqual([['a'], []]);
});
});The last push passes { emitEvent: false }, so it produces no emission. Use this to confirm that a bulk load, such as setItems, does not fire a request on every pushed row if your code relies on that.
If a validator is asynchronous, wrap the test in fakeAsync and call tick() with the validator's delay before asserting. Until the async validator resolves, the control's status is PENDING, not VALID.
Common mistakes in dynamic form tests
- Asserting before change detection. Described above. It is the most frequent cause of "the row is not there" failures.
- Sharing state between tests. Build the fixture in
beforeEach. AFormArraycreated at module level keeps its rows between tests, so results depend on test order. - Testing the framework instead of your code. You do not need a test that
pushincreaseslength. Test the rules you added: the validator, the loading pattern, the submit payload. - Forgetting that new rows start empty.
createItem()makes a group with a blank required name, so adding a row makes the form invalid again. A test that expectsvalidafteraddItemis wrong unless it also fills the row. - Checking
valuewhengetRawValue()is meant. If a control is disabled, it is missing fromvaluebut present ingetRawValue().
Exercise
You add a test that calls component.addItem() and then expects el.querySelectorAll('input[placeholder="Name"]').length to be 2. It fails with a length of 1, although component.items.length is 2. What is missing, and how would you also check that the new row is bound correctly?
Show answer
The test never called fixture.detectChanges() after addItem(), so the @for block has not rendered the new row yet. Add fixture.detectChanges() before the DOM assertion. To check the binding, type into the second input (set value, dispatch an input event, call detectChanges()) and assert that component.items.at(1).value.name equals the typed text.
Exercise
Write a test, without TestBed, that proves loading data with patchValue on an empty FormArray of one-control rows leaves the array empty, so the "clear, then push" pattern is required.
Show answer
Create const list = new FormArray<FormControl<string>>([]);, call list.patchValue(['a', 'b']);, then assert expect(list.length).toBe(0); and expect(list.value).toEqual([]);. patchValue only updates controls that already exist at each index, so no controls are created.