![](/img/trans.png)
[英]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.