How to test catchError scenario in Angular 8 jasmine so that handleError method will be covered

Viewed 459

Method in service

createAddress(reqBody): Observable<DataOnPost> {
        return this.http
        .post<DataOnPost>(`APIUrl`, reqBody)
        .pipe(catchError(this.handleError));
    }

handleError method::

handleError(error) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    return throwError(errorMessage);
  }

service.spec.ts

it('should handle error', () => {
    const reqBody = MOCK_BODY;
    spyOn(service, 'handleError').and.callThrough();
    service.createAddress(reqBody).subscribe(
      data => fail('Should have failed with 404 error'),
      (error: HttpErrorResponse) => {
        expect(error.status).toEqual(404);
        expect(error.error).toContain('404 error');
        expect(service.handleError).toHaveBeenCalledTimes(1);
      }
    );
    const request = httpMock.expectOne('api-url');
    request.flush('404 error', { status: 404, statusText: 'Not Found' });
    expect(request.request.method).toBe('POST');
  });

AM getting Error: Expected spy handleError to have been called once. It was called 0 times.

0 Answers
Related