Unit Test Form Custom Validator with Data from Dialog
April 7, 2021 · 3 min readLucian CiobanuSo as I was proof reading my previous post, I realised I can fix another unit test!
The functionality I'm trying to test is a custom validator for a form in a modal which brings data from it's parent that is supposed to be used in said custom validator. The custom validator is performing a a search if the inserted code already exists and it throws an error if there is a value found.
Hard to wrap your head around so I'm showing the code below:
//modal component with form
[...]
export class MyModalComponent {
public myGroupForm: FormGroup;
public myGroupCodes: string[] = [];
constructor(
@Inject(MAT_DIALOG_DATA) public data: string[],
private dialogRef: MatDialogRef<MyModalComponent>,
private fb: FormBuilder
) {
this.myGroupCodes = data;
this.myGroupForm = this.fb.group({
myGroupDescription: [null, Validators,required],
myGroupCode: [null, [Validators.required, this.myGroupCodeValidation(this.myGroupCodes)]]
});
}
private myGroupCodeValidation(myGroupCodes: string[]): ValidatorFn {
//this is a neat trick I picked up just for this challenge
//in order to use the custom validator with specific arguments
//I've returned a function which receives an abastract control
//to the custom validation function
return (control: AbstractControl): ValidationErrors | null => {
//receives inserted value in form
let myGroupCodeValue = control.value?.toString().trim().toLowerCase();
//values received from parent
let myGroupCodesLower = Array.from(myGroupCodes).map(element => element.toLowerCase());
it (myGroupCodesLower.includes(myGroupCodeValue)) {
//return error on form control
return {myGroupCodeUsed: true}
} else {
return null;
}
}
}
Quite challenging for me to implement. Even more challenging for me to test because when I was trying to generate a change in the form with patchValue, I had no idea why I was getting the myGroupCodes as undefined. Here is how I had to inject them:
[...]
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
//so this line gives to the data in the equivalent component the array I've added
{ provide: MAT_DIALOG_DATA, useValue: ["Lucian", "Ciobanu"] },
{ provide: MatDialogRef, useValue: { close: () => {} }
]
})
.compileComponents();
});
it('should return error if form ID entry is already present', () => {
component.myGroupForm.patchValue({
myGroupDescription: "Front End Developer",
myGroupCode: "Lucian"
})
expect(component.myGroupForm.get('myGroupCode').hasError('myGroupCodeUsed')).toBeTrue();
});
There you have it! myGroupCode: "Lucian" will be found in the array of values from the modal created in the provider.
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery