Ank*_*nka 10 unit-testing custom-validators karma-jasmine angular 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何编写单元测试用例形成这个?
cam*_*kid 16
这是一个受 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 });
});
});
Run Code Online (Sandbox Code Playgroud)
我没有测试过它,但它类似于我写的东西,它显示了基本方法。
我建议将验证器参数类型更改为number:
export function maxTextLength(length: number) {
Run Code Online (Sandbox Code Playgroud)
小智 3
您可以使用一个 formControl(在本例中为一些输入)在测试中创建一个 from 组。
然后利用 formControl 的 setValue 函数设置一个将通过单元测试的值。
然后,您可以将此表单控件传递给验证器函数并断言它返回 null(如果没有错误,则应返回 null)。
另一个测试有错误。