【问题标题】:How to write a unit test case for a custom validator for angular reactive forms?如何为角度反应形式的自定义验证器编写单元测试用例?
【发布时间】:2018-04-28 14:41:47
【问题描述】:

我有一个自定义模型驱动的表单验证器来验证最大文本长度

export function maxTextLength(length: string) {
  return function (control: FormControl) {
    const maxLenghtAllowed: number = +length;
    let value: string = control.value;
    if (value !== '' && value != null) {
      value = value.trim();
    }

    if (value != null && value.length > maxLenghtAllowed) {
      return { maxTextLength: true };
    }else {
      return null;
    }
  }
}

如何编写单元测试用例?

【问题讨论】:

    标签: angular unit-testing karma-jasmine angular-reactive-forms custom-validators


    【解决方案1】:

    这是一个受 Subashan 回答启发的示例,它概述了基本程序:

    import { maxTextLength } from '...';
    
    describe('maxTextLength', () => {
      const maxTextLengthValidator = maxTextLength(10);
      const control = new FormControl('input');
    
      it('should return null if input string length is less than max', () => {
        control.setValue('12345');
        expect(maxLengthValidator(control)).toBeNull();
      });
    
      it('should return correct object if input string length is more than max', () => {
        control.setValue('12345678901');
        expect(maxLengthValidator(control)).toEqual({ maxTextLength: true });
      });
    });
    

    我还没有测试过,但它与我写的类似,它显示了基本方法。

    我建议将验证器参数类型更改为number

    export function maxTextLength(length: number) {
    

    【讨论】:

    • 如果你有一个验证器的参数呢?你将如何测试它?
    【解决方案2】:

    您可以使用一个 formControl(在本例中为一些输入)在您的测试中创建一个来自组。

    然后利用 formControl 的 setValue 函数设置一个可以通过单元测试的值。

    然后您可以将此表单控件传递给验证器函数并断言它返回 null(如果没有错误,则应返回 null)。

    还有另一个有错误的测试。

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2017-10-06
      • 1970-01-01
      • 2020-05-02
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多