Sub topic 15
Testing a template-driven form
This chapter assumes you know how to write Angular component tests with TestBed, the SignupComponent from earlier in this tutorial, and how to use async/await in a test.
What makes these forms hard to test
A template-driven form builds its model from directives at runtime. The test therefore has to run change detection and let Angular finish its work before it can check anything. Two behaviors cause most failures:
NgModelregisters its control with the parentNgFormasynchronously, after the first change detection pass.- Typing in a test means setting
input.valueand dispatching a DOM event yourself. Setting the value alone does not notify Angular.
Setting up the fixture
A standalone component goes in imports, not declarations. Wait for whenStable() after the first detectChanges() so the control is registered before any assertions run.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SignupComponent } from './signup.component';
describe('SignupComponent', () => {
let fixture: ComponentFixture<SignupComponent>;
let el: HTMLElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [SignupComponent],
}).compileComponents();
fixture = TestBed.createComponent(SignupComponent);
el = fixture.nativeElement;
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
});
function input(): HTMLInputElement {
return el.querySelector('input') as HTMLInputElement;
}
function button(): HTMLButtonElement {
return el.querySelector('button') as HTMLButtonElement;
}
async function type(value: string): Promise<void> {
input().value = value;
input().dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
}
it('disables Save while the form is invalid', () => {
expect(button().disabled).toBe(true);
});
it('copies typed text into the model', async () => {
await type('Ada');
expect(fixture.componentInstance.model.name).toBe('Ada');
});
it('enables Save for a valid name', async () => {
await type('Ada');
expect(button().disabled).toBe(false);
});
it('shows the minlength message after typing a short name', async () => {
await type('ab');
expect(el.querySelector('[role="alert"]')?.textContent)
.toContain('at least 3 characters');
});
it('shows the required message after the field is touched', async () => {
input().dispatchEvent(new Event('blur'));
fixture.detectChanges();
expect(el.querySelector('[role="alert"]')?.textContent)
.toContain('Name is required');
});
});The type helper runs the sequence from the diagram. Reuse it for every field so the tests stay short.
Common errors
- Assertions see stale state. You skipped
whenStable()or the seconddetectChanges(). Check this first when a test passes with an added delay. - Validation message never appears. The template only shows errors when the control is
dirtyortouched. Dispatchinputto make it dirty, orblurto make it touched. Setting.valuealone does neither. No provideror unknown-property errors. The component is missingFormsModulein its ownimports. The test module cannot supply it.- Querying the wrong element.
querySelector('input')returns the first input. Select bynameoridonce the form has several fields.
Testing a custom validator
A validator directive has a plain validate() method, so you can unit test it without a fixture. Create the directive, set forbiddenName = 'admin', and call validate({ value: 'Admin' } as AbstractControl). The result should be a forbiddenName error. A value such as 'ada' should return null. Then add one fixture test that confirms the directive is wired to an ngModel input.
Exercise
A test sets input.value = 'Ada' and then immediately expects fixture.componentInstance.model.name to equal 'Ada'. The test fails. What is missing, and what is the minimal fix?
Show answer
Setting value does not tell Angular anything changed. The test must dispatch an event, such as input.dispatchEvent(new Event('input')). After that, call await fixture.whenStable() and fixture.detectChanges() before asserting on the DOM.
Exercise
Your test types 'ab' into the name field, but the "at least 3 characters" message is not in the DOM. Name two things to check.
Show answer
First, confirm the test dispatched an input event, so the control is dirty and the template's name.dirty || name.touched condition passes. Second, confirm the test called detectChanges() after the event so the template re-rendered. Also check that minlength="3" is on the input.