如何为Angular响应式表单编写自定义验证器的单元测试用例?

11

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

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个回答

19

下面是一个受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
如果您为验证器提供了一个参数,那该怎么测试呢? - Imad El Hitti

3

您可以在测试中使用一个formControl(在本例中是一些输入)创建一个表单组。

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

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

还有另一个测试,其中存在错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接