如何为角度反应形式的自定义验证器编写单元测试用例?

时间:2017-11-15 11:31:32

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

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

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;
    }
  }
}

如何编写单元测试用例?

2 个答案:

答案 0 :(得分:2)

这是一个受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) {

答案 1 :(得分:1)

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

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

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

还有一个错误的测试。