1

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'));});
Cœur
  • 37,241
  • 25
  • 195
  • 267
Developer
  • 279
  • 6
  • 22
  • You don't need to use two providers, one is enough. `spyOn(ProfileBeneficiaryService,'getPrefixSuffixDetails').and.returnValue(Observable.throw('error'));});` should be enough to make a call to `profileBeneficiaryService.getPrefixSuffixDetails()` fails. If you post the test that you are writing for `setPrefixSuffixDetails` I could help you more. – Castro Roy Jul 12 '18 at 18:59

1 Answers1

5

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();
});
Developer
  • 279
  • 6
  • 22