![](/img/trans.png)
[英]How to write unit test case for a custom validator for angular reactive forms
[英]How to write a unit test case for a custom validator for angular reactive forms?
我有一个自定义模型驱动的表单验证器来验证最大文本长度
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;
}
}
}
如何编写单元测试用例表单?
这是一个受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) {
您可以使用一个formControl(在本例中为某些输入)在测试中创建一个from组。
然后利用formControl的setValue函数来设置一个将通过单元测试的值。
然后,您可以将此表单控件传递给验证器函数并断言它返回null(如果没有错误,则应返回null)。
还有一个错误的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.