Sub topic 21
Unit Testing Form Models and Validators
Reactive forms keep their state in plain TypeScript objects, so most form logic can be tested without rendering a template. This chapter covers three levels of testing: validator functions called on their own, form models built in memory, and a small number of component tests that check the template is wired to the model.
This chapter assumes you can already write describe/it/expect tests in the runner your Angular project uses (Jasmine with Karma, or Vitest in newer CLI projects). The examples use only matchers that both runners support. It also builds on the passwordsMatch and usernameAvailable validators and the ProfileFormComponent from earlier chapters.
Choosing the Right Test Level
A validator is a function that takes an AbstractControl and returns errors or null. A form model is a tree of controls. Neither needs the DOM, a TestBed, or change detection. Keep template tests for the questions only a template can answer, such as "is the Save button disabled?" or "does typing update the model?"
| What you are checking | Test level | Needs TestBed |
|---|---|---|
| A validator returns the right error object | Validator function | No |
| Group status, cross-field errors, `patchValue`, `reset`, disabled controls | Form model | No |
| Async validator moves through `PENDING` | Form model | No |
| Input events update the model, error messages render | Component | Yes |
Testing a Validator Directly
The cheapest test calls the validator with a hand-built control. You need no form group and no component, and the assertion targets the exact error object your template will read.
import { FormControl, FormGroup } from '@angular/forms';
import { passwordsMatch } from './passwords-match.validator';
describe('passwordsMatch (direct call)', () => {
function group(password: string, confirmPassword: string) {
return new FormGroup({
password: new FormControl(password, { nonNullable: true }),
confirmPassword: new FormControl(confirmPassword, { nonNullable: true }),
});
}
it('returns null when values match', () => {
expect(passwordsMatch(group('abc', 'abc'))).toBeNull();
});
it('returns passwordsMismatch when values differ', () => {
expect(passwordsMatch(group('abc', 'xyz'))).toEqual({ passwordsMismatch: true });
});
it('treats two empty values as matching', () => {
expect(passwordsMatch(group('', ''))).toBeNull();
});
});The groups here have no validators attached. The test calls the function explicitly, so a mistake in how the validator is registered cannot hide a bug in the function itself.
Testing the Form Model
Model tests check that the validator is attached where you intended and that the status updates when values change. A cross-field validator on the group puts its error on the group, not on a child control, and a test should confirm that.
import { FormControl, FormGroup } from '@angular/forms';
import { passwordsMatch } from './passwords-match.validator';
describe('signup form model', () => {
function createForm() {
return new FormGroup(
{
password: new FormControl('secret1', { nonNullable: true }),
confirmPassword: new FormControl('secret2', { nonNullable: true }),
},
{ validators: passwordsMatch },
);
}
it('puts the mismatch error on the group, not the child', () => {
const form = createForm();
expect(form.hasError('passwordsMismatch')).toBe(true);
expect(form.controls.confirmPassword.errors).toBeNull();
});
it('becomes valid once the values match', () => {
const form = createForm();
form.controls.confirmPassword.setValue('secret1');
expect(form.valid).toBe(true);
});
it('resets to initial values because controls are nonNullable', () => {
const form = createForm();
form.controls.password.setValue('changed');
form.markAsDirty();
form.reset();
expect(form.getRawValue()).toEqual({ password: 'secret1', confirmPassword: 'secret2' });
expect(form.dirty).toBe(false);
});
});Build a fresh form in each test with a factory function. A form shared across tests carries over values, dirty flags, and errors, so the result of one test starts to depend on which tests ran before it.
Testing Async Validators
An async validator depends on a service. Pass in a fake that implements the same interface, so the test never touches the network. To assert on the transition into and out of PENDING, back the fake with a Subject and decide in the test when it emits.
import { FormControl } from '@angular/forms';
import { Observable, Subject, firstValueFrom, of, throwError } from 'rxjs';
import { UsernameChecker, usernameAvailable } from './username-available.validator';
describe('usernameAvailable', () => {
it('returns usernameTaken when the checker says taken', async () => {
const checker: UsernameChecker = { isTaken: () => of(true) };
const result = await firstValueFrom(
usernameAvailable(checker)(new FormControl('ada')) as Observable<unknown>,
);
expect(result).toEqual({ usernameTaken: true });
});
it('returns null when the checker errors', async () => {
const checker: UsernameChecker = { isTaken: () => throwError(() => new Error('down')) };
const result = await firstValueFrom(
usernameAvailable(checker)(new FormControl('ada')) as Observable<unknown>,
);
expect(result).toBeNull();
});
it('is PENDING until the checker responds', () => {
const response = new Subject<boolean>();
const checker: UsernameChecker = { isTaken: () => response };
const control = new FormControl('ada', {
nonNullable: true,
asyncValidators: [usernameAvailable(checker)],
});
expect(control.status).toBe('PENDING');
response.next(true);
expect(control.status).toBe('INVALID');
expect(control.hasError('usernameTaken')).toBe(true);
});
});The Subject lets you check the in-between state without timers or fakeAsync. Angular skips async validators while any synchronous validator fails, so if you add Validators.required here, give the control a non-empty starting value or the async check never runs.
Testing Template Wiring
Write a component test only for template wiring: the bindings between the DOM and the model. Configure the standalone component, render it, then drive it through the model or through DOM events.
import { TestBed } from '@angular/core/testing';
import { ProfileFormComponent } from './profile-form.component';
describe('ProfileFormComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({ imports: [ProfileFormComponent] }).compileComponents();
});
it('disables Save until the form is valid', () => {
const fixture = TestBed.createComponent(ProfileFormComponent);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
expect(button.disabled).toBe(true);
fixture.componentInstance.profileForm.setValue({ name: 'Ada', email: '[email protected]' });
fixture.detectChanges();
expect(button.disabled).toBe(false);
});
it('copies typed input into the model', () => {
const fixture = TestBed.createComponent(ProfileFormComponent);
fixture.detectChanges();
const input: HTMLInputElement = fixture.nativeElement.querySelector('input[formControlName="name"]');
input.value = 'Grace';
input.dispatchEvent(new Event('input'));
expect(fixture.componentInstance.profileForm.controls.name.value).toBe('Grace');
});
});DOM-to-model updates happen synchronously inside the input event handler. Model-to-DOM updates need fixture.detectChanges() before you query the element again.
Common Mistakes
- Asserting on the wrong control. A group-level error does not appear on the child, so
confirmPassword.errorsstaysnull. Checkform.hasError(...). - Forgetting the touched flag. Tests for error messages fail without explanation because the
@ifcondition requirestouched. - Calling real services in async validator tests. Inject a fake through the factory parameter instead.
- Testing disabled controls with
value. A disabled control is left out ofform.value. UsegetRawValue()when you need every field. - Putting every check in TestBed. Component tests are slower and fail for unrelated template reasons. Push logic down to model tests.
Exercise
You add Validators.required to the username control alongside usernameAvailable, create it with an initial value of '', and your test expects status 'PENDING'. The test fails. Why, and how do you fix it?
Show answer
Angular runs async validators only after all synchronous validators pass. With an empty value, required fails, the status is 'INVALID', and the async validator never runs. Start the control with a non-empty value such as 'ada', or call setValue('ada') before asserting 'PENDING'.
Exercise
A test calls form.controls.email.setValue('bad') on ProfileFormComponent's form, runs fixture.detectChanges(), and expects the "Enter a valid email address." message. The message does not appear. What is missing?
Show answer
The template shows the message only when the email control is touched, and setValue does not mark it touched. Call form.controls.email.markAsTouched() (or dispatch a blur event on the input) before fixture.detectChanges().
Exercise
Write a one-line assertion that checks the usernameAvailable validator returns null when the checker reports the name as free, given checker = { isTaken: () => of(false) }.
Show answer
expect(await firstValueFrom(usernameAvailable(checker)(new FormControl('ada')) as Observable<unknown>)).toBeNull(); inside an async test.