如何为角度反应形式的自定义验证器编写单元测试用例? [英] How to write a unit test case for a custom validator for angular reactive forms?

查看:28
本文介绍了如何为角度反应形式的自定义验证器编写单元测试用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom model-driven form validator to validate maximum text length

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

如何编写单元测试用例?

How to write a unit test case form this?

推荐答案

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

Here's an example inspired by Subashan's answer which outlines the basic procedure:

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

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

I haven't tested it but it's similar to something I've written and it shows the basic approach.

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

I would recommend changing validator parameter type to number:

export function maxTextLength(length: number) {

这篇关于如何为角度反应形式的自定义验证器编写单元测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆