I try to run a test that checks the proper functioning of a date validator. This validator returns an error if the first date entered is greater than the second. Everything works well at the code level. For some reason I do not know the following test does not work. Here is the validator in question:
export function compareTwoDatesValidator(
dateFrom: string,
dateTo: string
): ValidatorFn {
return (form: AbstractControl): ValidationErrors | null => {
let dateFromForm: string = form.get(dateFrom)?.value;
let dateToForm: string = form.get(dateTo)?.value;
const regEx = /^[12]\d{3}-\d{2}-\d{2}$/;
if (!dateFromForm || !dateToForm) {
return null;
}
if (dateFromForm.match(regEx) && dateToForm.match(regEx)) {
let dateTime = luxon.DateTime;
let dateDebut = dateTime.fromISO(dateFromForm);
let dateFin = dateTime.fromISO(dateToForm);
if (dateDebut.startOf('day') > dateFin.startOf('day')) {
return {
incorrectRangeDate: {
dateFrom: dateFromForm,
dateTo: dateToForm
}
};
}
}
return null;
};
}
In the unit test, I create a fake form that takes 2 FormControl with dates in string format I assign a value higher than the first date and I expect my form to contain an error but it does not. Here's my test:
describe('compareTwoDatesValidator', () => {
let dateDebut: AbstractControl | null;
let dateFin: AbstractControl | null;
let form: FormGroup;
beforeEach(() => {
form = new FormGroup(
{
dateDebut: new FormControl(),
dateFin: new FormControl()
},
{ validators: compareTwoDatesValidator('dateDebut', 'dateFin') }
);
dateDebut = form.get('dateDebut');
dateFin = form.get('dateFin');
});
it('retourne une erreur si dateDebut > dateFin', () => {
dateDebut?.setValue('11-11-2020');
dateFin?.setValue('11-11-2019');
console.log(form.errors); // returns null !
expect(form.hasError('incorrectRangeDate')).toBe(true);
});
});
My test fails: the form should have an error. Why doesn't my test return an error ?