如何编写用于角反应形式的自定义验证器的单元测试用例? [英] How to write a unit test case for a custom validator for angular reactive forms?
本文介绍了如何编写用于角反应形式的自定义验证器的单元测试用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义模型驱动的表单验证器,用于验证最大文本长度
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屋!
查看全文