问题
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