Sub topic 11
Unit testing validators
This chapter assumes you can write a validator function and a validator factory, and that you know FormControl and FormGroup. You also need to read a Jasmine or Jest test (describe, it, expect) and know the basics of RxJS Observable.
Why validators are easy to test
A synchronous validator is a plain function. It takes a control and returns ValidationErrors | null. It does not need a component, a template, or TestBed. You build a standalone FormControl with the value you want, call the validator, and check the result.
Tests that skip TestBed run faster and fail for fewer unrelated reasons. A good split looks like this:
Most of your effort belongs in the first branch, because that is where the rules live.
Testing a synchronous validator
Test each branch of the function: an invalid value, a valid value, and the edge cases the code explicitly handles. For noWhitespaceValidator, the edge cases are an empty string and a non-string value, both of which return null so that Validators.required can own the "missing" case.
import { FormControl } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
describe('noWhitespaceValidator', () => {
it('flags a value made only of spaces', () => {
expect(noWhitespaceValidator(new FormControl(' '))).toEqual({ whitespace: true });
});
it('accepts text with surrounding spaces', () => {
expect(noWhitespaceValidator(new FormControl(' a '))).toBeNull();
});
it('leaves empty and null values to the required validator', () => {
expect(noWhitespaceValidator(new FormControl(''))).toBeNull();
expect(noWhitespaceValidator(new FormControl(null))).toBeNull();
});
});Use toEqual for error objects, not toBe. Each call returns a new object, so reference equality would fail. Use toBeNull for the valid case. Checking only for a falsy value would also accept undefined or {}, and Angular treats {} as invalid.
Testing a validator factory
A factory returns a validator, so create it once per configuration and test the result. You should also check that the error payload carries the detail the template relies on.
import { FormControl } from '@angular/forms';
import { forbiddenNameValidator } from './forbidden-name.validator';
describe('forbiddenNameValidator', () => {
const validator = forbiddenNameValidator(['admin']);
it('returns an error for a forbidden name, ignoring case', () => {
expect(validator(new FormControl('Admin'))).toEqual({
forbiddenName: { value: 'Admin' },
});
});
it('returns null for an allowed name', () => {
expect(validator(new FormControl('alice'))).toBeNull();
});
it('uses the list it was given', () => {
const other = forbiddenNameValidator(['root']);
expect(other(new FormControl('admin'))).toBeNull();
});
});The last test guards against a factory that accidentally shares state between calls.
Testing a cross-field validator
A group validator reads sibling controls, so build a real FormGroup. You can call the validator on the group directly, or read group.errors after construction.
import { FormControl, FormGroup } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
describe('passwordsMatchValidator', () => {
function makeGroup(password: string, confirm: string): FormGroup {
return new FormGroup(
{ password: new FormControl(password), confirm: new FormControl(confirm) },
{ validators: passwordsMatchValidator },
);
}
it('reports a mismatch on the group, not on a control', () => {
const group = makeGroup('secret', 'other');
expect(group.errors).toEqual({ passwordsMismatch: true });
expect(group.controls['confirm'].errors).toBeNull();
});
it('clears the error when the values match', () => {
const group = makeGroup('secret', 'other');
group.controls['confirm'].setValue('secret');
expect(group.errors).toBeNull();
});
});The second test checks revalidation. Changing a child control makes the parent group run its validators again.
Testing an asynchronous validator
An async validator returns an Observable, and uniqueUsernameValidator waits 300 ms before it calls the service. Replace the service with a stub, and use fakeAsync with tick so the test controls the clock instead of waiting.
import { fakeAsync, tick } from '@angular/core/testing';
import { FormControl, ValidationErrors } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { uniqueUsernameValidator, UsernameService } from './unique-username.validator';
describe('uniqueUsernameValidator', () => {
it('waits for the delay, then reports a taken name', fakeAsync(() => {
let calls = 0;
const service: UsernameService = {
isTaken: () => {
calls++;
return of(true);
},
};
const validator = uniqueUsernameValidator(service);
let result: ValidationErrors | null | undefined;
(validator(new FormControl('alice')) as Observable<ValidationErrors | null>)
.subscribe((errors) => (result = errors));
tick(299);
expect(calls).toBe(0);
tick(1);
expect(calls).toBe(1);
expect(result).toEqual({ usernameTaken: true });
}));
});The cast is needed because AsyncValidatorFn may return a Promise or an Observable, and this validator always returns an Observable. The tick(299) and tick(1) pair proves the request is not sent early. You can add a second test whose stub returns throwError(() => new Error('down')) and expect null, which checks the catchError branch.
Testing the wiring
A validator can be correct and still never run, for example when you forget to put it in the validators array. One short test on a configured control covers this and also checks that Angular merges errors from several validators.
import { FormControl, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
describe('name control', () => {
it('is invalid for whitespace and valid for text', () => {
const name = new FormControl(' ', {
nonNullable: true,
validators: [Validators.required, noWhitespaceValidator],
});
expect(name.invalid).toBeTrue();
expect(name.hasError('whitespace')).toBeTrue();
name.setValue('Ada');
expect(name.valid).toBeTrue();
});
});toBeTrue is a Jasmine matcher. In Jest, use toBe(true).
Common mistakes
- Comparing errors with
toBe, which fails because each call returns a new object. - Checking
toBeFalsy()instead oftoBeNull(), which hides a validator that returns{}orundefined. - Forgetting
tickin async tests, so the assertion runs before the observable emits. - Using a real HTTP service in a validator test. Stub the service instead.
Exercise
Write the assertion you would use to check that a validator accepts the value 'alice'. Then explain why toBeTruthy() on the result would be a wrong check.
Show answer
Use expect(validator(new FormControl('alice'))).toBeNull();. A valid value must return exactly null. toBeTruthy() passes for any error object, so it would pass when the validator reports an error. Assertions on a valid value must check for null, never for truthiness.
Exercise
In the async test, why does tick(299) followed by expect(calls).toBe(0) matter?
Show answer
It shows that the service is not called until the 300 ms delay has passed. This matters because the delay keeps the app from sending a request for every keystroke. A test that only checked the final result would still pass if the delay were removed.