来自组件的观察者成功和错误测试用例问题

时间:2018-03-19 12:42:09

标签: angular karma-jasmine

对于我的应用程序组件创建单元测试用例,在组件中使用该服务连接其余的api以获取数据。

在使用成功和错误案例订阅observable的组件中,使用mockservice我可以实现成功,可以使用带有返回值的spon来覆盖错误场景。但我使用两个返回值测试用例失败,而不是使用mockserive尝试返回值成功案例但成功案例也失败。

  

Component.ts

export class KpiComponent implements OnInit {

  public info: any[] = [];
  servicerError = false;
  constructor(private kpisService: KpisService, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: Params) => {
      this.kpisService.getKpiDetails().subscribe(
        data => {
          this.info = data;
          console.log('25 - Working');
        },
        (error) => {  console.log('27 - Error');  this.servicerError = true }
      );

    });
  }

}
  

component.spec.ts

const info = [{ name: 'kpi' }];

    class MockKpisService {
      public getKpiDetails(): Observable<any> {
        return Observable.of(info);
      }

    }


    describe('KpiComponent', () => {
      let component: KpiComponent;
      let fixture: ComponentFixture<KpiComponent>;
      let kpisService: KpisService;
      let kpisService1: KpisService;

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [BrowserAnimationsModule, NoopAnimationsModule, RouterModule, RouterTestingModule, BrowserModule, MatProgressBarModule, TableModule, MultiSelectModule, FormsModule, CalendarModule, DropdownModule, SpinnerModule, TooltipModule, HttpClientModule],
          declarations: [KpiComponent, DataTableComponent],
          providers: [{ provide: KpisService, useClass: MockKpisService }]
        }).compileComponents();
        fixture = TestBed.createComponent(KpiComponent);
        component = fixture.componentInstance;
        kpisService = TestBed.get(KpisService);
        kpisService1 = fixture.debugElement.injector.get(KpisService);
        fixture.detectChanges();

      }));



      it('should create', () => {
        expect(component).toBeTruthy();
      });

      it('should List the Attachment', () => {
        //spyOn(kpisService, 'getKpiDetails').and.callThrough();
        expect(component.info).toBe(info);
        expect(component.servicerError).toBe(false);

      });

      it('should Error log displayed', () => {
        spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
        fixture.detectChanges();
        expect(component.servicerError).toBe(true);
      });


    });

对于上述代码错误块测试失败。

对于吹码成功测试用例失败,还通过组件ngOnInit进行服务调用。

const info = [{ name: 'kpi' }];

describe('KpiComponent', () => {
  let component: KpiComponent;
  let fixture: ComponentFixture<KpiComponent>;
  let kpisService: KpisService;
  let kpisService1: KpisService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [BrowserAnimationsModule, NoopAnimationsModule, RouterModule, RouterTestingModule, BrowserModule, MatProgressBarModule, TableModule, MultiSelectModule, FormsModule, CalendarModule, DropdownModule, SpinnerModule, TooltipModule, HttpClientModule],
      declarations: [KpiComponent, DataTableComponent],
      providers: [KpisService]
    }).compileComponents();
    fixture = TestBed.createComponent(KpiComponent);
    component = fixture.componentInstance;
    kpisService = TestBed.get(KpisService);
    kpisService1 = fixture.debugElement.injector.get(KpisService);
    fixture.detectChanges();

  }));



  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should List the Attachment', () => {
    spyOn(kpisService, 'getKpiDetails').and.returnValue(info);
    expect(component.info).toBe(info);
    expect(component.servicerError).toBe(false);

  });

  it('should Error log displayed', () => {
    spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
    fixture.detectChanges();
    expect(component.servicerError).toBe(true);
  });


});

2 个答案:

答案 0 :(得分:1)

对于第一种情况,您可以尝试使用此功能。

it('should Error log displayed', () => {
        spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
        component.ngOnInit();
        fixture.detectChanges();
        expect(component.servicerError).toBe(true);
        //verify the spy too
        expect(kpisService.getKpiDetails).toHaveBeenCalled();
 });

您不应该在单元测试中调用您的真实服务。所以,第二种方法不是要走的路。

答案 1 :(得分:0)

请尝试以下错误:

it('should Error log displayed', () => {
  spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
  kpisService.getKpiDetails().subscribe(response => null, error => {
    expect(component.servicerError).toBe(true);
  });
  fixture.detectChanges();
  component.ngOnInit();
});

如果它不起作用,rty在ngOnInit电话上超时。