Reputation: 289
I am trying to errors in code coverage for service calls. I am following two approaches but doing some mistake.
below is my method for which I am writing test cases
setPrefixSuffixDetails(): void {
this.prefixSuffixDetailSubscription = this.profileBeneficiaryService.getPrefixSuffixDetails()
.subscribe(data => {
if (data.body.prefixlist.length > 0) {
this.prefixConfig.options = data.body.prefixlist;
}
if (data.body.suffixlist.length > 0) {
this.suffixConfig.options = data.body.suffixlist;
}
}, error => {
this.loadingData = false;
this.notificationService.addNotications(error);
});
}
For testing, I am creating providers, below are my providers
{ provide: ProfileBeneficiaryService, useClass: ProfileServiceStub},
{provide: ProfileBeneficiaryService, useClass: ProfileBenficiaryErrorStub},
one is for success call and other is for error call.
beforeEach(async(() => {
TestBed.configureTestingModule({ .............
class ProfileBenficiaryErrorStub {
getPrefixSuffixDetails = function () {
return Observable.throw(Error('Test error'));
}}
class ProfileServiceStub {
getPrefixSuffixDetails = function () {
return Observable.of(this.data);
}
}
But the issue is when I use two providers it only covers for error, If I dont include the provider for error, it covering for success
Please let me know where I am doing mistake using providers.
Also, I was trying to use spyOn way and facing error
it('should check for the getPrefixSuffixDetails error call ', () => {
spyOn(ProfileBeneficiaryService,'getPrefixSuffixDetails').and.returnValue(Observable.throw('error'));});
Upvotes: 1
Views: 9306
Reputation: 289
Below solution worked for me
it('should check for the getPrefixSuffixList error call ', () => {
spyOn(profileDependentsService, 'getPrefixSuffixList').and.returnValue(Observable.throw('error'));
component.getPrefixSuffixList();
expect(profileDependentsService.getPrefixSuffixList).toHaveBeenCalled();
});
Upvotes: 5