![](/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.