[英]Unit Testing in Jasmine: Spy on service function and call another service function
[英]Testing a function that uses a service Jasmine spyOnObject
我正在尝试测试由按钮单击启动的功能
如果按钮值等于“是”,则将自定义验证器应用于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不是函数”
您正在定义的模拟( mockStateService
)没有currentCheckedCount
方法。
mockStateService
仅有两个方法getCategoryState
和getCheckedCount
。
如果只想模拟对象的某些方法,则可以在spyOn
的实例上尝试spyOn。
依此类推,还有其他方法可以窥探/模拟某些方法。
您还可以尝试使用createSpyObj定义要返回的内容:
const mockStateService = jasmine.createSpyObj('StateService',
{
getCategoryState: function() {
return "ifItMathersReturnSomething";
},
getCheckedCount: function() {
return "anotherThing";
},
currentCheckedCount: function() {
return 0;
}
}
);
@ 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.