如何在Karma中正确测试可观察物以进行端到端测试?

时间:2018-12-20 11:24:47

标签: jasmine observable e2e-testing angular7 angular-e2e

当前,我正在尝试编写一个将执行以下操作的测试:

  • 加载我的组件
  • 等待从服务类返回(HTTP调用+可观察)
  • 返回检查值。

服务类别:

getMyInfo(): Observable<any[]> {
        return this.httpClient.get(`${this.serviceurl}/all`) as Observable<any[]>;
}

相关组件代码:

ngOnInit() {
    this.myService.getMyInfo().subscribe((data: any[]) => {
      console.log('I was called')
      this.myInfo = data;
    })
}

在测试类中,将无法使用Service中的此方法,将调用该方法,但是该返回值永远不会应用于类(订阅)中。

使用存根有效,但这不是我想要的,因为我想e2e。

const serviceStub = {
  getMyInfo() {
    return fakeAsyncResponse([{  id: 1,name: 'myname'}]);
  }
};

 it("should request names on component initiation.", inject([FrontendComponent, Service], async(component: FrontendComponent, service: Service) => {
    let debugElement = fixture.debugElement;
    let Service = debugElement.injector.get(Service);
    let incrementSpy = spyOn(Service, 'getMyInfo').and.callThrough();
    component.ngOnInit();
    expect(incrementSpy).toHaveBeenCalled();
    await fixture.whenStable();
    fixture.detectChanges();    
    console.log(component.myInfo);
    expect(component.myInfo.length).toEqual(1);
  }));

总而言之,我如何处理真实的http调用,然后处理预期的断言而又不存根服务类?

0 个答案:

没有答案
相关问题