catchError always gets called in HTTP unit testing

£可爱£侵袭症+ 提交于 2021-01-28 17:47:58

问题


I have a service that makes a HTTP call and I am trying to write tests for it. The method in the service that I am trying to test looks like this

// my.service.ts

setUserAgreement(accept: boolean): Observable<any> {
  const data = { accept };

  return this.http.post<any>(this.url, data, this.getHttpHeader('1'))
    .pipe(
      tap(x => this.logHttp(x)),
      map(x => this.parseHttp(x)),
      catchError(this.handleErrorInternal('setUserAgreement'))
    );
}

My test file looks like this

import { TestBed, async } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { myService } from './my.service';

describe('myService', () => {
  let service;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ]
    });

    service = TestBed.get(myService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe(`#setUserAgreement`, () => {
    const mockResponse = 'Mock response';

    afterEach(() => {
      httpMock.verify();
    });

    it(`should not call handleErrorInternal when the call resolves successfully`, async(() => {
      spyOn(service, 'handleErrorInternal');
      service.setUserAgreement(true).subscribe(() => {
        expect(service.handleErrorInternal).not.toHaveBeenCalled();
      });

      const req = httpMock.expectOne(service.url);
      req.flush(mockResponse, { status: 200, statusText: 'OK' });
    }));
  });
});

However the test fails with the message Error: Expected spy handleErrorInternal not to have been called.

Can someone please help?


回答1:


I found the issue, it looks like it was caused by this line

catchError(this.handleErrorInternal('setUserAgreement'))

Doing something like this fixed the behaviour

catchError(x => {
  this.handleErrorInternal('setUserAgreement');
  // return an observable here
})


来源:https://stackoverflow.com/questions/57718654/catcherror-always-gets-called-in-http-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!