Currently, I am testing a validator that involves making a call to a service. If the call returns zero, an error object is returned.
I have successfully created a spy for the service and used returnValue, which seems to be working well. However, I am facing challenges when it comes to executing the validation function and returning the value.
To solve this issue, I resorted to creating a spy for the function I am testing, although I believe this might not be the correct approach.
This is the validator function:
It takes a service as a parameter and utilizes it internally
static require(service: Service): ValidatorFn {
return (formGroup: FormGroup): { [key: string]: boolean } | null => {
const checkedCount = state.currentCount();
if (checkedCount === 0) {
return {
'isNotChecked' : true
};
}
return null;
};
}
The successful test case is as follows: I am unsure whether spying on the function under test is the appropriate method?
it('should return error object when currentCount === 0', () => {
spyOn(service, 'currentCount').and.returnValue(0);
spyOn(ModValidation, 'require').and.returnValue({ 'isNotChecked' : true });
service.currenCount();
expect(ModValidation.require(service)).toEqual({ 'isNotChecked' : true });
});
My unsuccessful attempt is shown below:
it('should return error object when currentCount === 0', () => {
spyOn(service, 'currentCount').and.returnValue(0);
const resp = ModValidation.require(service);
service.currentCount();
expect(resp).toEqual({ 'isNotChecked' : true });
});
Upon running this failed test, I encountered the following output:
Expected Function to equal Object({ isNotChecked: true }).