Sub topic 11
Unit testing validators
This chapter shows how to test the validators you wrote in earlier chapters. It covers synchronous validators, factories, cross-field validators, async validators and the directive wrapper. It assumes you can write a validator function, attach it to a FormControl or FormGroup, and read basic RxJS. The examples use describe, it and expect, which work in Jasmine, Jest and Vitest. Where a runner-specific API would be needed, the examples avoid it.
Why validators are cheap to test
A validator is a plain function from a control to ValidationErrors | null. It needs no component, no template and no dependency injection. To test it, create a standalone FormControl, pass it to the function, and check the return value.
That makes validator tests fast and precise. Most of them need no TestBed, which compiles components and is much slower. The exceptions are the directive wrapper and anything that depends on injected services, and those are covered later in this chapter.
Testing a synchronous validator
Start with the whitespace validator from earlier in the tutorial. Each test builds a control with one value and asserts on the result.
import { FormControl } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
describe('noWhitespaceValidator', () => {
it('returns an error for a whitespace-only string', () => {
expect(noWhitespaceValidator(new FormControl(' '))).toEqual({ whitespace: true });
});
it('returns null for text', () => {
expect(noWhitespaceValidator(new FormControl('alice'))).toBeNull();
});
it('returns null for text with surrounding spaces', () => {
expect(noWhitespaceValidator(new FormControl(' alice '))).toBeNull();
});
});Use toEqual for error objects and toBeNull for the valid case. Do not use toBeFalsy, because undefined, 0 and '' would all pass it. Angular treats only null as "valid", so your test should require exactly that.
Cover the edges
Validators run on every value change, including values you did not plan for. Test the inputs that are easy to forget:
- An empty string. The whitespace validator returns
nullhere on purpose, so thatValidators.requiredis the only validator that reports a missing value. null. A control created withnew FormControl(null)or reset withreset()holdsnull.- A non-string value such as a number, if the control could ever hold one.
import { FormControl } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
describe('noWhitespaceValidator edge cases', () => {
const ignoredValues: unknown[] = ['', null, 42];
ignoredValues.forEach((value) => {
it(`returns null for ${JSON.stringify(value)}`, () => {
expect(noWhitespaceValidator(new FormControl(value))).toBeNull();
});
});
});Looping with forEach works in every runner. Jest and Vitest also offer it.each, but Jasmine does not.
Factories: one validator per configuration
A validator factory returns a new function for each configuration. Build the validator once per describe block and test the behavior that depends on the parameters.
import { FormControl } from '@angular/forms';
import { forbiddenNameValidator } from './forbidden-name.validator';
describe('forbiddenNameValidator', () => {
const validator = forbiddenNameValidator(['admin', 'root']);
it('returns an error that carries the rejected value', () => {
expect(validator(new FormControl('Admin'))).toEqual({
forbiddenName: { value: 'Admin' },
});
});
it('matches every name in the list', () => {
expect(validator(new FormControl('root'))).not.toBeNull();
});
it('returns null for an allowed name', () => {
expect(validator(new FormControl('alice'))).toBeNull();
});
it('returns null for a non-string value', () => {
expect(validator(new FormControl(7))).toBeNull();
});
it('does not share state between instances', () => {
const other = forbiddenNameValidator(['guest']);
expect(other(new FormControl('admin'))).toBeNull();
expect(other(new FormControl('guest'))).not.toBeNull();
});
});The last test checks that the configuration is captured per call and not stored in a module-level variable. It catches a common refactoring mistake.
The first test also pins down a quirk. The validator lowercases the control value but not the forbidden list. A factory call such as forbiddenNameValidator(['Admin']) would therefore never match anything. A test that documents this tells future readers whether the behavior is intended.
Testing a validator through a FormControl
Calling the validator directly proves that the function is correct. It does not prove that it is wired up correctly. A second kind of test attaches the validator to a control and checks the control's state. The state shows how Angular merges errors from several validators.
import { FormControl, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
describe('name control wiring', () => {
function createControl(value: string): FormControl<string> {
return new FormControl(value, {
nonNullable: true,
validators: [Validators.required, noWhitespaceValidator],
});
}
it('reports only required for an empty value', () => {
const control = createControl('');
expect(control.errors).toEqual({ required: true });
});
it('reports only whitespace for blank text', () => {
const control = createControl(' ');
expect(control.hasError('whitespace')).toBeTrue();
expect(control.hasError('required')).toBeFalse();
});
it('is valid for normal text', () => {
expect(createControl('alice').valid).toBeTrue();
});
});toBeTrue() and toBeFalse() exist in Jasmine. In Jest or Vitest, write toBe(true) and toBe(false).
These tests exercise the same errors object and hasError method that your template reads. If you rename an error key in the validator but not in the template, a test like this one, which asserts the key a template depends on, will fail.
Testing a cross-field validator
A group-level validator receives a FormGroup. Build a real group with real child controls, so the validator reads the same structure it will see in the application.
import { FormControl, FormGroup } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
describe('passwordsMatchValidator', () => {
function createGroup(password: string, confirm: string): FormGroup {
return new FormGroup(
{
password: new FormControl(password),
confirm: new FormControl(confirm),
},
{ validators: passwordsMatchValidator },
);
}
it('reports the error on the group, not on a child', () => {
const group = createGroup('secret', 'other');
expect(group.errors).toEqual({ passwordsMismatch: true });
expect(group.get('confirm')?.errors).toBeNull();
});
it('is valid when both values match', () => {
expect(createGroup('secret', 'secret').valid).toBeTrue();
});
it('revalidates when a child value changes', () => {
const group = createGroup('secret', 'other');
group.get('confirm')?.setValue('secret');
expect(group.valid).toBeTrue();
});
it('passes when the controls it reads do not exist', () => {
expect(passwordsMatchValidator(new FormGroup({}))).toBeNull();
});
});The second assertion in the first test checks where the error lives. The error belongs to the group, so a template that looks at confirm.hasError('passwordsMismatch') will never see it. The revalidation test shows that Angular reruns the group validator when any child changes.
The last test records a gotcha. When group.get('password') returns null, both sides of the comparison are undefined, so they are equal and the validator returns null. A typo in a control name therefore disables the check without any error. This test makes that behavior visible. If you would rather fail loudly, change the validator and update the test.
Testing an async validator
Async validators depend on time and on a service, and tests need to control both.
- Replace the service with a small stub object. The
UsernameServiceinterface has one method, so a literal object is enough. No mocking library is needed. - Use
fakeAsyncandtickfrom@angular/core/testingto advance thetimer(300)delay without waiting. This needszone.jsin the test environment. If your project does not use it, use your runner's fake timers instead.
The factory returns an AsyncValidatorFn, whose return type is a Promise or an Observable. Wrapping the call in RxJS from converts either into an Observable, so the test can subscribe without a type cast.
import { fakeAsync, tick } from '@angular/core/testing';
import { FormControl, ValidationErrors } from '@angular/forms';
import { Observable, from, of, throwError } from 'rxjs';
import { UsernameService, uniqueUsernameValidator } from './unique-username.validator';
describe('uniqueUsernameValidator', () => {
function setup(response: Observable<boolean>) {
const calls: string[] = [];
const service: UsernameService = {
isTaken: (username) => {
calls.push(username);
return response;
},
};
return { calls, validator: uniqueUsernameValidator(service) };
}
it('reports usernameTaken after the delay', fakeAsync(() => {
const { validator, calls } = setup(of(true));
let result: ValidationErrors | null | undefined;
from(validator(new FormControl('alice'))).subscribe((errors) => (result = errors));
expect(result).toBeUndefined();
tick(300);
expect(result).toEqual({ usernameTaken: true });
expect(calls).toEqual(['alice']);
}));
it('returns null when the name is free', fakeAsync(() => {
const { validator } = setup(of(false));
let result: ValidationErrors | null | undefined;
from(validator(new FormControl('bob'))).subscribe((errors) => (result = errors));
tick(300);
expect(result).toBeNull();
}));
it('sends no request when the subscription is cancelled early', fakeAsync(() => {
const { validator, calls } = setup(of(true));
const subscription = from(validator(new FormControl('al'))).subscribe();
tick(200);
subscription.unsubscribe();
tick(300);
expect(calls).toEqual([]);
}));
it('treats a failing service as valid', fakeAsync(() => {
const { validator } = setup(throwError(() => new Error('offline')));
let result: ValidationErrors | null | undefined;
from(validator(new FormControl('alice'))).subscribe((errors) => (result = errors));
tick(300);
expect(result).toBeNull();
}));
});The first test asserts undefined before tick(300), which proves the validator waits. The third test is the one that matters most for correctness. It shows that a superseded subscription never reaches the service, which is the reason for the timer(300) and switchMap combination. Angular unsubscribes from the previous async validation when the value changes, and this test reproduces that.
The last test pins down a design decision. The validator returns null when the service fails, so a network error never blocks the form. Some applications want the opposite. If yours does, change the catchError branch and this test together.
Check the pending state
To verify the integration with Angular, attach the validator to a control and watch status.
import { fakeAsync, tick } from '@angular/core/testing';
import { FormControl } from '@angular/forms';
import { of } from 'rxjs';
import { uniqueUsernameValidator } from './unique-username.validator';
describe('async validator status', () => {
it('moves from PENDING to INVALID', fakeAsync(() => {
const validator = uniqueUsernameValidator({ isTaken: () => of(true) });
const control = new FormControl('alice', { asyncValidators: [validator] });
expect(control.status).toBe('PENDING');
tick(300);
expect(control.status).toBe('INVALID');
expect(control.errors).toEqual({ usernameTaken: true });
}));
});PENDING is the status Angular uses while an async validator is running. Async validators run only if all synchronous validators pass, so a control that fails required never reaches PENDING. Add a test for that case if your form relies on it.
Testing the directive wrapper
The directive from the template-driven chapter delegates to forbiddenNameValidator. The validator logic is already covered, so the directive needs only a wiring test. This is one of the few places where TestBed is worth its cost.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { FormsModule, NgModel } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { ForbiddenNameDirective } from './forbidden-name.directive';
@Component({
standalone: true,
imports: [FormsModule, ForbiddenNameDirective],
template: `<input [(ngModel)]="name" [appForbiddenName]="['admin']" />`,
})
class HostComponent {
name = 'admin';
}
describe('ForbiddenNameDirective', () => {
it('registers the validator on the ngModel control', async () => {
const fixture = TestBed.createComponent(HostComponent);
fixture.detectChanges();
await fixture.whenStable();
const model = fixture.debugElement.query(By.directive(NgModel)).injector.get(NgModel);
expect(model.errors).toEqual({ forbiddenName: { value: 'admin' } });
});
});whenStable is needed because ngModel writes its initial value to the control asynchronously. Without the await, errors is still null and the test would pass or fail for the wrong reason.
Choosing the test level
Pick the cheapest test that can fail for the bug you are guarding against.
| Part under test | Needs TestBed | Needs fake time | What the test proves |
|---|---|---|---|
| Sync validator | No | No | Return value for each input |
| Validator factory | No | No | Parameters change the result |
| Group validator | No | No | Error lands on the group, revalidates on change |
| Async validator | No | Yes | Delay, cancellation, error handling, PENDING status |
| Directive wrapper | Yes | No | The validator is registered with `ngModel` |
Common mistakes
- Asserting on truthiness.
expect(result).toBeTruthy()passes for any error object, including the wrong one. Assert the exact object withtoEqual. - Forgetting the valid case. A validator that always returns an error passes every "returns an error" test. Pair each failing input with a passing one.
- Testing only the direct call. Direct calls miss wiring bugs such as a missing entry in
validatorsor a mismatched error key in the template. Add at least one test through a control or group. - Real timers in async tests. Waiting 300 ms with a real timer makes the suite slow and flaky. Use
fakeAsync. - Leftover timers.
fakeAsyncfails a test that ends with pending timers. If you see that error, the validator is still waiting on a delay, and the test needs anothertickor an unsubscribe. - Calling a real service. An async validator test that makes an HTTP request depends on the network. Stub the service.
Exercise
Write a test for passwordsMatchValidator that confirms the validator can be called without building a FormGroup of real child controls, and explain why a test built from real controls is still the better default.
Show answer
A minimal group is enough: passwordsMatchValidator(new FormGroup({})) returns null because both group.get(...) lookups yield undefined, which compare as equal. A real group with password and confirm controls is the better default because it matches the structure the validator sees in the application, lets you test revalidation through setValue, and exposes mistakes such as a mistyped control name that the empty-group call hides.
Exercise
A teammate changes uniqueUsernameValidator to call service.isTaken directly, removing timer(300) and switchMap. Which test from this chapter fails, and what does its failure tell you?
Show answer
The test "sends no request when the subscription is cancelled early" fails, because calls now contains the username instead of staying empty. The first test also fails, since the result is available before tick(300) and the assertion that it is still undefined breaks. The failures show that the debounce is gone: every keystroke would send a request.