【问题标题】:Angular test reactive form validation service method getting controls ourside the methodAngular 测试反应式表单验证服务方法获取方法外的控件
【发布时间】: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


    【解决方案1】:

    我认为你应该能够传递一个 formGroup。

    我不是 100% 确定,但我认为这样的事情应该可行。

    it('should do stuff', () => {
      const formGroup = new FormGroup({
        startDate: new FormControl('2000-01-20'),
        endDate: new FormControl('2000-12-20'),
      });
      // this method returns a function
      const func = service.dateRange('startDate', 'endDate');
      // call the function with the formGroup
      const result = func(formGroup);
      expect(result).toBe(....);
    });
    

    【讨论】:

    • 您好,感谢您的回复。我不太了解您的解决方案。如何使用 formGroup 调用该函数?看来我做不到,我在 valdiations 服务内的任何函数中都没有 formGroup 之类的参数。我不知道我是否理解你
    • 您好,我认为您的验证器已被调用,它正在返回一个函数。我认为我向您展示的解决方案是调用您的验证器并将其存储在func 中。我们稍后用formGroup 调用func,看看返回的函数给了我们什么。
    • 嗨,再次感谢。问题是使用 func 我有这个错误:这个表达式是不可调用的。类型“ValidationErrors”没有调用签名。
    • 有趣。我认为您应该做的是使用验证器创建一个 formGroup,然后测试 form.errors 对象是否具有您想要的内容。像这样的东西:pashozator.medium.com/….
    • 好的,我会试试的,非常感谢
    最近更新 更多