简体   繁体   中英

Angular testing observable in service

I would like to test function in service. But i can't test subscribe. How can i do this?

Function to test:

  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');
          }
        });
  }

Found how to test this function. But still, can't test error.

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

spec:

 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);
  }));

think i should add public error in function and make mock function, that return mockInvestigates or error?

something like this.

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();
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM