I'm trying to test my new component and I don't know why every functions from a specific file are blocking my tests and I don't understand why because they all are synchrone functions. My tests are passing because of the timeout but the code always stop at these functions.
I'm using 2 functions atLeastOneCheckbox() (custom Validator) and getRealCheckedValues() (which return formcontrol real values for checkbox control)
I'm importing them like that:
import { atLeastOneCheckbox, getRealCheckedValues } from '@core/validators/validators.service';
And here are the content of the file:
import { ValidatorFn, FormGroup, FormControl, Validators } from '@angular/forms';
/**
* Validators that require at least x checkbox checked
* @param minRequired Number of checkbox required
*/
export function atLeastOneCheckbox(minRequired = 1): ValidatorFn {
return function validate(formGroup: FormGroup) {
let checked = 0;
if (!formGroup.controls) {
return null;
}
Object.keys(formGroup.controls).forEach((key) => {
const control = formGroup.controls[key];
if (control.value) {
checked ;
}
});
if (checked < minRequired) {
return {
requireCheckboxToBeChecked: true,
};
}
return null;
};
}
/**
* Return the real values of checked checkbox
* @param aChecked FormArray values
* @param aValues Checkbox values
*/
export function getRealCheckedValues(aChecked: boolean[], aValues: any[]): any[] {
return aValues.filter((val: any, index: number) => aChecked[index]);
}
// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
};
}
And my test block here:
this.form = this.formBuilder.group({
// Response grids section
grids: this.formBuilder.group({
respGrid: this.formBuilder.array(grids), atLeastOneCheckbox(1))
}),
})
And here (every value used inside the function are corrects):
const selectTransportationType = getRealCheckedValues(
this.f.informations.controls.transportationType.value,
this.aSubcontracts.map((sub: SubcontractData) => sub.key)
);
Even if I try to console.log right inside the function, the log is never called and I don't understand why.
If someone can enlighten me please
CodePudding user response:
Ok, so I found the problem. Every functions from this file was undefined because the path use an alias that doesn't work when testing '@core' and I don't know why. But replace '@core' by '@app/core' correct the issue in my case.