我正在尝试测试通过单击按钮启动的功能
如果按钮值等于“是”,则将自定义验证器应用于formGroup
验证器需要一个参数,该参数是服务“ this.stateService”,该参数将为此测试返回数字“ 0”。
实际功能:
onSelected(): void {
const myFormGroup: AbstractControl = this.form.controls.fGroup;
if (this.form.get('button').value === 'Yes') {
myFormGroup.validator = myValidation.requireCheckboxesToBeChecked(this.stateService);
} else {
myFormGroup.setValidators(null);
}
myFormGroup.updateValueAndValidity();
}
在验证程序文件中:
static requireCheckboxesToBeChecked(stateService: StateService): ValidatorFn {
return function validate (formGroup: FormGroup): { [key: string]: boolean } | null {
const checkedCount = stateService.currentCheckedCount();
if (checkedCount === 0) {
return {
'isNotChecked' : true
};
}
return null;
};
}
测试功能:
import { myValidation } from '@app/shared/validators/modification.validator';
const mockStateService = jasmine.createSpyObj('StateService',
[ 'getCategoryState',
'getCheckedCount'
]);
it('should add validation to my form group when value is Yes', () => {
const vehicleModificationsFormGroup = component.form.controls['vehicleModifications'];
component.form.get('button').setValue('Yes');
component.onSelected();
myFormGroup.validator = myValidation.requireCheckboxesToBeChecked(mockStateService);
expect(mockStateService.currentCheckedCount).toEqual(0);
expect(myFormGroup.validator.length).toBe(1);
});
我在验证程序文件中得到“ stateService.currentCheckedCount不是一个函数”
答案 0 :(得分:2)
您要定义的模拟(mockStateService
)没有currentCheckedCount
方法。
mockStateService
仅有两种方法getCategoryState
和getCheckedCount
。
如果只想模拟对象的某些方法,则可以在ExampleService的实例上尝试spyOn
。
以此类推,还有其他方法可以窥探/模拟某些方法。
您还可以尝试使用createSpyObj定义要返回的内容:
const mockStateService = jasmine.createSpyObj('StateService',
{
getCategoryState: function() {
return "ifItMathersReturnSomething";
},
getCheckedCount: function() {
return "anotherThing";
},
currentCheckedCount: function() {
return 0;
}
}
);
答案 1 :(得分:1)
@ stp18的答案将我带入正确的轨道,该函数在数组中丢失
但是,我确实必须修改对嘲笑服务的调用以返回值,而不是等于
import { myValidation } from '@app/shared/validators/modification.validator';
const mockStateService = jasmine.createSpyObj('StateService',
[ 'currentCheckedCount',
'getCheckedCount'
]);
it('should add validation to my form group when value is Yes', () => {
const vehicleModificationsFormGroup = component.form.controls['vehicleModifications'];
component.form.get('button').setValue('Yes');
component.onSelected();
myFormGroup.validator = myValidation.requireCheckboxesToBeChecked(mockStateService);
mockStateService.currentCheckedCount.and.returnValue(0);
expect(myFormGroup.validator.length).toBe(1);
});