When testing an HTTP call error response with the HttpClientTestingModule
, everything runs smoothly until I introduce a rxjs retry(2)
to the HTTP call. Suddenly, the test starts complaining about finding an unexpected request:
Expected no open requests, found 1
The challenge now is figuring out how to expect two requests using the HttpTestingController
:
service.ts
@Injectable()
export class Service {
constructor(private http: HttpClient) { }
get() {
return this.http.get<any>('URL')
.pipe(
retry(2),
catchError(error => of(null))
)
}
}
service.spec.ts
describe('Service', () => {
let httpTestingController: HttpTestingController;
let service: Service;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [Service],
imports: [HttpClientTestingModule]
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(Service);
});
afterEach(() => {
httpTestingController.verify();
});
it('should handle 404 with retry', () => {
service.get().subscribe((data: any) => {
expect(data).toBe(null);
});
expectErrorResponse(404);
});
function expectErrorResponse(status: number) {
const requests = httpTestingController.match('URL');
// fails -> finds only one request
expect(requests.length).toBe(2);
requests.forEach(req => req.flush('error', {status, statusText: 'Not Found'}));
}
});
If I remove the expect(requests.length).toBe(2)
, the test will fail with the same error message as before.
Example in Action
To see it in action, you can check out this Stackblitz link