没有使用jasmine调用http请求的catch

时间:2017-08-03 15:12:15

标签: angular jasmine rxjs

我正在努力在我的catch请求测试中调用http方法,但我不知道我做错了什么。我已经将我的测试与在这里找到的lthers进行了比较,但我不能错过我所缺少的。

这是我想测试的方法:

public get(apiName, methodName) {
  return this.http.get(this.url + apiName + "/" + methodName, {
    headers: headers,
    search: params
  }).catch((error) => {
    this.backendErrorService.notify(this.handleError(error));

    return Observable.throw(error);
  });
}

如果我运行测试,上面的方法会被调用,我甚至可以检查是否已调用this.http.get,但我无法调用catch

这是我的测试:

it("should show modal when contract service throws", fakeAsync(() => {
  // Arrange
  let http = TestBed.get(Http);
  let backendService = TestBed.get(BackendErrorService);
  let backend = TestBed.get(MockBackend);

  backend.connections.subscribe((connection: MockConnection) => {
    connection.mockError(new MockError(new ResponseOptions({ type: ResponseType.Error, status: 404, body: {} })));
  });

  let httpClientService: HttpClientService = new HttpClientService(http, backendService);

  httpClientService.get("ContractApi", "GetContracts");

  // Act
  fixture.detectChanges();

  tick();

  // Assert
  console.log(fixture.debugElement);
}));

我错过了什么?

1 个答案:

答案 0 :(得分:1)

解决方案是添加订阅。

由于它是 Observable ,如果没有订阅者,则不会进行调用,这里是完整的解决方案:

it("should show modal when contract service throws", fakeAsync(() => {
    // Arrange
    let http = TestBed.get(Http);
    let backendService = TestBed.get(BackendErrorService);
    let backend = TestBed.get(MockBackend);

    backend.connections.subscribe((connection: MockConnection) => {
      connection.mockError(new MockError(new ResponseOptions({ type: ResponseType.Error, status: 404, body: {} })));
    });

    let httpClientService = new HttpClientService(http, backendService);

    httpClientService.get("ContractApi", "GetContracts").map((res: Response) => {}).subscribe((contracts) => {
    });

    // Act
    fixture.detectChanges();

    tick();

    // Assert
    console.log(fixture.debugElement);
}));