【发布时间】:2025-12-16 02:00:01
【问题描述】:
我有一个具有不同验证方法的验证服务。通常我会像这个例子一样将控件发送到验证:
dateTodayOrlater(control: FormControl): ValidationErrors | null {
const selectedDate = new Date(control.value);
if ("more stuff here") {
return { dateTodayOrlater: true };
}
//"more stuff here"
return null;
}
并测试构建具有价值的新控件:
it('should validate dateTodayOrlater with errors', () => {
const control = new FormControl('2000-01-20');
const res = service.dateTodayOrlater(control);
expect(res).toEqual({ dateTodayOrlater: true });
});
但现在我有一个依赖于另一个表单控件的验证,如下所示:
dateRange(
startDateControl: string,
endDateControl: string
): ValidationErrors | null {
return (controls: AbstractControl): ValidationErrors | null => {
const startControl = controls.get(startDateControl);
const endControl = controls.get(endDateControl);
const startVal = startControl?.value;
const endVal = endControl?.value;
if ("more stuff here") {
return { dateRange: true };
}
//"more stuff here"
return null;
};
}
作为
开始日期控制
和
结束日期控制
都是字符串,在验证中我从表单中获取控件:
const startControl = controls.get(startDateControl);
const endControl = controls.get(endDateControl);
我如何测试或模拟一些东西来测试这种情况?谢谢
【问题讨论】:
标签: angular unit-testing jasmine karma-jasmine