Angular 测试服务中的可观察性

Angular testing observable in service

我想测试服务中的功能。但我无法测试订阅。 我该怎么做?

要测试的函数:

  getInvestigates(page, lim): any {
    return this.http.get(`${this.bcUrl}/api/investigates?page=${page}&size=${lim}`, this.httpOptions)
      .subscribe(
        (data: DataInterface) => {
          this.investigates = data.content;
          this.st.totalPages = data.totalPages;
          this.st.totalElements = data.totalElements;
        },
        error => {
          if (error.status === 404) {
            alert('Not found');
          }
        });
  }

找到了如何测试这个功能。但是,仍然无法测试错误。

error => {
      if (error.status === 404) {
        alert('Not found');
      }

规格:

 it('should get investigate', inject([InvestigateService, HttpTestingController],
    (service: InvestigateService, backend: HttpTestingController) => {
    const mockInvestigates = {
      'content':
        {
          'id': 6,
          'investigateType': 'WARN',
          'number': '12018150030005555',
          'investigatePriority': 'NORMAL',
          'investigateStatus': 'OPEN',
          'correction': {
            'create': 1527454800,
            'action': 'CREATE',
            'user_id': 6
          },
          'hide': false,
          'tags': [
            {
              'id': 1,
              'name': 'Кражи',
              'correction': {
                'action': 'UPDATE',
                'user_id': 1
              }
            }
          ],
        }};

    service.getInvestigates(1, 1);
    backend.expectOne({
      method: 'GET',
      url: 'http://30.30.0.101:8080/api/investigates?page=1&size=1'
    }).flush(mockInvestigates);
    expect(service.investigates).toBe(mockInvestigates.content);
  }));

认为我应该在函数中添加 public 错误并制作模拟函数,return mockInvestigates 或错误?

像这样。

class InvestigatesStub {
  public error = false;
  mockGetInvestigates() {
    if (this.error) {
      return Observable.throw(new Error('Test error'));
    } else {
      return Observable.from(data);
    }
  }
}
it('should not get investigate if error', inject([InvestigateService, 
HttpTestingController],
(service: InvestigateService, backend: HttpTestingController) => {

  service.getInvestigates(1, 1);
  backend.expectOne({
    method: 'GET',
    url: 'http://30.30.0.101:8080/api/investigates?page=1&size=1'
  }).flush(null, {status: 404, statusText: 'Not Found'});
  expect(service.investigates).toBeFalsy();
}));