gpt4 book ai didi

angular - Angular 中十进制验证器的单元测试

转载 作者:行者123 更新时间:2023-12-04 14:54:46 25 4
gpt4 key购买 nike

我试着寻找源代码,但找不到关于为十进制验证器创建单元测试的信息。如果我在 component.ts 中的代码是这样的

  DecimalValidator(decimal: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
const value = control.value;
if (value.includes('.')) {
const valArray = value.split('.');
if (valArray[1].length > decimal) {
return { 'maxDecimal': true };
} else {
return null;
}
} else {
return null;
}
};
}

如何在 component.spec.ts 中为此功能编写单元测试?

最佳答案

ValidatorFn 通过执行传入带有测试值的 FormControl 的函数来测试:

describe('DecimalValidator', () => {

it('should not error on an empty string', () => {
expect(MyValidators.DecimalValidator(2)(new FormControl(''))).toBeNull();
});

it('should not error on null', () => {
expect(MyValidators.DecimalValidator(2)(new FormControl(null))).toBeNull();
});

it('should not error on undefined', () => {
expect(MyValidators.DecimalValidator(2)(new FormControl(undefined))).toBeNull();
});

it('should not error if decimal digit count is less than or equal to parameter', () => {
expect(MyValidators.DecimalValidator(2)(new FormControl('1.11'))).toBeNull();
expect(MyValidators.DecimalValidator(2)(new FormControl('1.1'))).toBeNull();
expect(MyValidators.DecimalValidator(2)(new FormControl('1'))).toBeNull();
expect(MyValidators.DecimalValidator(1)(new FormControl('1.1'))).toBeNull();
expect(MyValidators.DecimalValidator(1)(new FormControl('1'))).toBeNull();
expect(MyValidators.DecimalValidator(0)(new FormControl('1'))).toBeNull();
});

it('should error if decimal digit count is greater than parameter', () => {
expect(MyValidators.DecimalValidator(2)(new FormControl('1.111'))).toEqual({ 'maxDecimal': true });
expect(MyValidators.DecimalValidator(1)(new FormControl('1.11'))).toEqual({ 'maxDecimal': true });
expect(MyValidators.DecimalValidator(0)(new FormControl('1.1'))).toEqual({ 'maxDecimal': true });
});

});

您可以在此处查看 Angular 内置验证器的测试,这可能会有所帮助:https://github.com/angular/angular/blob/a92a89b0eb127a59d7e071502b5850e57618ec2d/packages/forms/src/validators.ts

注释:您可能希望在错误对象 return { 'maxDecimal': decimal }; 中返回最大小数计数,因为它可能对向用户显示有用。

关于angular - Angular 中十进制验证器的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68280818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com