角服务呼叫测试

时间:2019-12-27 16:41:07

标签: angular jasmine karma-runner

我正在尝试测试按钮单击是否触发了服务方法调用。 组件内容(经过清理)看起来像这样

ngOnInit() {
    try {
      //GET ALL ITEMS
      this.service.getAll().pipe(untilDestroyed(this)).subscribe((result) => {
        this.list = result;
      });
    }
    catch (ex) {
      this._utility.showNotification(ex, 2);
    }
  }

refresh() {
  this.ngOnInit();
}

规格文件如下所示:

it('REFRESH Button should call ngOnInit and getAll', () => {
    var spy = spyOn(component, "ngOnInit");
    var spyGet = spyOn(component.service, 'getAll').and.returnValue(of([]))
    let btnRefresh = fixture.debugElement.query(By.css('.btn-info')).nativeElement
    btnRefresh.click()

    fixture.whenStable().then(() => {
      fixture.detectChanges()
      expect(spy).toHaveBeenCalled();
      expect(spyGet).toHaveBeenCalled();
    })
  });

我得到的当前错误如下:

  

预计将被调用的间谍getAll。

2 个答案:

答案 0 :(得分:1)

实际上,您必须首先将服务注入您的测试中。然后,您监视注入的服务,而不是组件中的内容。示例:

it('should get stores', inject([StoresService], async (service: StoresService) => {
    const spy = spyOn(service, 'getStores');
    component.ngOnInit();
    expect(spy).toHaveBeenCalled();
  }));

参考:Is it possible to give one CSS class priority over another?

答案 1 :(得分:1)

删除该组件上的间谍就可以了

it('Refresh button should call getAll', () => {
   var spyGet = spyOn(MockApplicationLogService.prototype, 'getAll')
   let btnRefresh = fixture.debugElement.query(By.css('.btn-info')).nativeElement
   btnRefresh.click()

   expect(spyGet).toHaveBeenCalled();
});