简体   繁体   English

角度单元测试,可观察到的错误

[英]Angular unit testing, for Observable errors

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 此外,我试图使用spyOn方式并遇到错误

 it('should check for the getPrefixSuffixDetails error call ', () => {
 spyOn(ProfileBeneficiaryService,'getPrefixSuffixDetails').and.returnValue(Observable.throw('error'));});

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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM