Sub topic 15
Testing a template-driven form
This chapter assumes you can write Angular standalone components and know the basics of TestBed, ComponentFixture, and a Jasmine-style describe/it/expect. It also assumes you have read the earlier chapters on ngModel, control state, validation, and custom validator directives. The examples test the SignupComponent and ForbiddenNameDirective from this tutorial.
What you are testing
A template-driven form keeps most of its logic in the template. The component class holds a plain model object, and Angular builds the FormControl objects behind the scenes. You therefore have two choices of test target:
- The rendered DOM: type into inputs, blur them, submit the form, and check what appears on screen.
- The directive or validator class on its own: call
validate()with a fake control.
Test the DOM for behavior a user would notice, such as messages, a disabled button, and the submitted value. Test validators in isolation for the rules themselves. DOM tests are slower and more brittle, so keep them for wiring. Put the edge cases in the unit tests.
Why template-driven tests need extra waiting
NgModel does not create or update its control synchronously. When it sees a value, it schedules the work on a resolved promise. The consequences are:
- After the first
fixture.detectChanges(), the form has no registered controls yet. - After you change
component.model, the input's value does not update until that promise runs. f.invalidand[disabled]="f.invalid"can lag one change-detection pass behind.
The fix is a short helper that runs change detection, waits for pending async work, and runs change detection again.
Setting up the test
The component is standalone, so it goes in imports, not declarations. It already imports FormsModule itself, so the test does not need to.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SignupComponent } from './signup.component';
describe('SignupComponent', () => {
let fixture: ComponentFixture<SignupComponent>;
let component: SignupComponent;
let root: HTMLElement;
async function settle(): Promise<void> {
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
}
function type(input: HTMLInputElement, value: string): void {
input.value = value;
input.dispatchEvent(new Event('input'));
}
const nameInput = () => root.querySelector<HTMLInputElement>('#name')!;
const saveButton = () =>
root.querySelector<HTMLButtonElement>('button[type="submit"]')!;
const alertBox = () => root.querySelector('[role="alert"]');
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [SignupComponent],
}).compileComponents();
fixture = TestBed.createComponent(SignupComponent);
component = fixture.componentInstance;
root = fixture.nativeElement;
await settle();
});
it('starts pristine with the Save button disabled', () => {
expect(alertBox()).toBeNull();
expect(saveButton().disabled).toBeTrue();
});
});The type helper sets value and then dispatches an input event. Setting value alone does nothing, because the DefaultValueAccessor listens for the event, not for the property change.
Testing control state and messages
The template shows errors only when the control is invalid and either dirty or touched. Each of those conditions needs its own test, because a regression in either one is easy to miss by hand.
it('shows the required message after the field is touched', async () => {
nameInput().dispatchEvent(new Event('blur'));
await settle();
expect(alertBox()?.textContent).toContain('Name is required.');
});
it('shows the minlength message once the user types a short value', async () => {
type(nameInput(), 'Al');
await settle();
expect(alertBox()?.textContent).toContain('at least 3 characters');
expect(saveButton().disabled).toBeTrue();
});
it('clears the message and enables Save for a valid name', async () => {
type(nameInput(), 'Al');
await settle();
type(nameInput(), 'Alice');
await settle();
expect(alertBox()).toBeNull();
expect(saveButton().disabled).toBeFalse();
expect(component.model.name).toBe('Alice');
});The blur event is what marks the control as touched, through the same value accessor. The second test passes without a blur because typing makes the control dirty.
Testing the model-to-view direction
Two-way binding runs both ways, so also test that a change to the component updates the input.
it('writes model changes into the input', async () => {
component.model.name = 'Bob';
await settle();
expect(nameInput().value).toBe('Bob');
});Without await fixture.whenStable(), this test fails, and the input is still empty. That failure is the most common sign that a template-driven test is missing its wait.
Testing submission
Dispatch a real submit event on the form element. This exercises the same path a user's click takes, and it goes through NgForm's own submit listener, which emits ngSubmit.
it('logs the model when a valid form is submitted', async () => {
const log = spyOn(console, 'log');
type(nameInput(), 'Alice');
await settle();
root.querySelector('form')!.dispatchEvent(new Event('submit'));
expect(log).toHaveBeenCalledWith('Submitted', { name: 'Alice' });
});Note that dispatchEvent(new Event('submit')) bypasses the disabled button. If you want to prove that an invalid form cannot be submitted by clicking, assert on saveButton().disabled, as the earlier tests do. In a real browser, a disabled submit button blocks the click, but a test that dispatches submit directly does not.
For a form that calls a service, provide a fake service in TestBed and assert on the fake instead of on console.log. That keeps the test independent of how the component reports success.
Using fakeAsync instead of whenStable
If your project uses zone.js, fakeAsync and tick give you control over the same waiting without real promises:
import { fakeAsync, tick } from '@angular/core/testing';
it('reflects the model in the input (fakeAsync)', fakeAsync(() => {
fixture.componentInstance.model.name = 'Bob';
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(nameInput().value).toBe('Bob');
}));fakeAsync matters most when a form has timers, such as a debounce through ngModelOptions or an async validator that waits before it calls a server. There, tick(300) moves time forward by exactly 300 ms, so the test stays fast and deterministic. If your project is zoneless, fakeAsync is not available, so use await fixture.whenStable() instead.
Testing a custom validator directive
The rule in ForbiddenNameDirective lives in validate(), which takes a control and returns errors or null. You can test it without Angular at all:
import { AbstractControl } from '@angular/forms';
import { ForbiddenNameDirective } from './forbidden-name.directive';
describe('ForbiddenNameDirective', () => {
const asControl = (value: unknown) => ({ value }) as AbstractControl;
function createDirective(forbidden: string): ForbiddenNameDirective {
const directive = new ForbiddenNameDirective();
directive.forbiddenName = forbidden;
return directive;
}
it('returns an error when the value matches, ignoring case', () => {
const result = createDirective('admin').validate(asControl('Admin'));
expect(result).toEqual({ forbiddenName: { value: 'Admin' } });
});
it('returns null for other values', () => {
expect(createDirective('admin').validate(asControl('alice'))).toBeNull();
});
it('returns null for an empty value or when no name is forbidden', () => {
expect(createDirective('admin').validate(asControl(null))).toBeNull();
expect(createDirective('').validate(asControl('admin'))).toBeNull();
});
});The three cases cover the match, the non-match, and the guard clauses. Adding a short host-component test, with a template such as <input name="u" ngModel forbiddenName="admin" #u="ngModel">, then confirms that the directive is registered under NG_VALIDATORS and that u.errors?.['forbiddenName'] appears after typing admin.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Input is empty after setting `component.model` | `NgModel` writes the value asynchronously | Await `fixture.whenStable()`, then call `detectChanges()` again |
| `ExpressionChangedAfterItHasBeenCheckedError` in the first test | Controls register after the first check, so `f.invalid` changes | Run the `settle()` helper before assertions |
| Error message never appears | Control is neither dirty nor touched | Dispatch `input` or `blur`, not just set `value` |
| `NG01203: No value accessor` or `No provider for NgForm` | `FormsModule` missing from a test host component | Add it to the host's `imports` |
| Spy is never called on submit | Test clicked a disabled button | Make the form valid first, or dispatch `submit` on the `form` |
What to cover
A reasonable suite for one form includes:
- The initial state: pristine, no errors, submit disabled.
- One test per validation rule, with the message that should appear.
- A test for the valid path, where the message clears and submit is enabled.
- The model-to-view direction, if the component sets values programmatically.
- Submission, including what is passed to the handler and the effect of
resetForm(). - Each custom validator as a unit test, plus one integration test per directive.
Exercise
A test sets component.model.name = 'Bob', calls fixture.detectChanges() once, and then expects nameInput().value to be 'Bob'. The expectation fails with an empty string. Why, and what is the smallest change that fixes it?
Show answer
NgModel writes model values to the control asynchronously, on a resolved promise, so the input has not been updated when the assertion runs. Add await fixture.whenStable() after the first detectChanges(), followed by a second fixture.detectChanges() (or wrap the test in fakeAsync and call tick()), so the pending write finishes and the DOM is refreshed before the assertion.
Exercise
Write the expectation for a test that types 'Al' into the name field and then checks that the Save button is disabled. Which two steps must happen between typing and asserting?
Show answer
Dispatch the input event after setting value (the type helper does this), then run await settle(), meaning detectChanges(), await whenStable(), and detectChanges() again. The assertion is expect(saveButton().disabled).toBeTrue();.