javascript / intermediate
Snippet
Unit Testing Reactive Form Validators under Invalid Inputs
Custom synchronous form validators are pure higher-order functions that accept configuration parameters and return a validation function. Testing these validators in isolation verifies that invalid values produce precise error payloads while valid inputs correctly resolve to null.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { FormControl, ValidationErrors, ValidatorFn } from '@angular/forms';export function forbiddenKeywordValidator(forbiddenWord: RegExp): ValidatorFn {return (control: FormControl): ValidationErrors | null => {if (!control.value || typeof control.value !== 'string') {return null;}const isForbidden = forbiddenWord.test(control.value);return isForbidden ? { forbiddenKeyword: { value: control.value } } : null;};}describe('forbiddenKeywordValidator', () => {const validator = forbiddenKeywordValidator(/admin/i);it('should return null when control contains valid text', () => {const control = new FormControl('johndoe');expect(validator(control)).toBeNull();});it('should return a validation error object when forbidden keyword is present', () => {const control = new FormControl('SuperAdmin123');const result = validator(control);expect(result).toEqual({forbiddenKeyword: { value: 'SuperAdmin123' }});});});
angular
Breakdown
1
export function forbiddenKeywordValidator(forbiddenWord: RegExp): ValidatorFn {
Defines a higher-order factory returning a ValidatorFn configured with a target regular expression.
2
return isForbidden ? { forbiddenKeyword: { value: control.value } } : null;
Returns a ValidationErrors dictionary on match or null if validation passes.
3
describe('forbiddenKeywordValidator', () => {
Groups unit tests targeting the validator function suite.
4
const control = new FormControl('SuperAdmin123');
Instantiates a lightweight FormControl with test payload without needing full DOM TestBed setup.
5
expect(result).toEqual({ forbiddenKeyword: { value: 'SuperAdmin123' } });
Asserts that the validator generates the exact expected error map structure upon invalid input.