The Angular RXJS HTTPClient fails to properly handle HttpErrorResponses

In my Angular 12 project, I am facing an issue with setting up unit tests that should capture errors from HTTP responses. However, when running the tests, instead of receiving the error as an actual error object, it is being passed within the response body.

Here is a snippet from my Spec.ts file:

it('Test post method failure', () => {
      const expected: HttpErrorResponse = new HttpErrorResponse({
        error: 'Bad Request',
        status: 400,
        statusText: 'Bad Request'
      });
      service.post({ urlIdentifier: 'test', endpoint: '123' }).subscribe({
        next: res => {
          // This block is executed
          console.log(res)
        },
        error: error => {
          // This block is not getting executed
          expect(error.status).toBeCloseTo(expected.status);
          expect(error.statusText).toEqual(expected.error);
        }}

      );

Below is the method being tested in the HttpService class:

export class HttpService {
  constructor(public http: HttpClient) {};
  post<T>({ urlIdentifier, endpoint, body }: HttpMethodsArguments): Observable<T> {
    const url: string = this.getBaseUrl(urlIdentifier) + endpoint;
    return this.http.post<T>(url, body, {
      headers: this.getHttpHeaders()
    }).pipe(
        catchError(err => {
          return throwError(err);
        })
      );
  }

The response object LOG shows: HttpErrorResponse(headers:..., status:400, statusText: "Bad Request" ...) The expected outcome is embedded in the response object in the test instead of triggering an error. I suspect there's a small detail that I'm overlooking, but I haven't been able to figure it out yet.

Answer №1

After reviewing Melvin's feedback, I realized that there was an issue with error handling in the code. In situations where an HttpErrorResponse occurred, the Catch Error functionality was not triggering as expected.

export class UpdatedHttpService {
  constructor(public http: HttpClient) {};
  post<T>({ urlIdentifier, endpoint, body }: HttpMethodsArguments): Observable<T> {
    const url: string = this.getBaseUrl(urlIdentifier) + endpoint;
    return this.http.post<T>(url, body, {
      headers: this.getHttpHeaders()
    }).pipe(
      map(x => {
        if (x instanceof HttpErrorResponse) {
          throw x;
        }
        return x;
        })
      )
      .pipe(
        catchError(err => {
          return throwError(err);
        })
      );
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

How to disable the onChange event in PrimeNG p-dropdown?

I'm currently utilizing PrimeNG's dropdown component. Each option in the list includes an icon that, when clicked, should trigger a specific method. Additionally, I need to execute another method when the onChange event of the dropdown is trigger ...

The TypeScript error ts2322 occurs when using a generic constraint that involves keyof T and a

Trying to create a generic class that holds a pair of special pointers to keys of a generic type. Check out an example in this playground demo. const _idKey = Symbol('_idKey') const _sortKey = Symbol('_sortKey') export interface BaseSt ...

The Replay Subject will not activate the async pipe when utilizing the subscribe shorthand during initialization

I'm curious about the behavior of a replay subject created using the subscribe shorthand method, specifically why it does not trigger the async pipeline when the next method is called. When I follow this approach, everything functions as expected: ex ...

Utilize ASP.NET Boilerplate Core and Angular on Microsoft Azure for seamless deployment

I am looking to deploy ASP.NET Boilerplate Core & Angular on Microsoft Azure. The current version of ASP.NET Boilerplate consists of two solutions (one for the backend and one for the frontend), so I need to deploy them on two separate AppServices along wi ...

Merging Two mat-error Elements in Angular

I recently dived into the world of Angular by following their official tutorial. Curiosity got the best of me and I started experimenting with error handling using Angular Material when a user enters their email. I'm wondering if there's a way to ...

Sharing information between different components in React can be done using props, context, or a

When attempting to edit by clicking, the parent information is taken instead of creating a new VI. I was able to achieve this with angular dialog but I am unsure how to do it with components. This is done using dialog: <div class="dropdown-menu-item" ...

Exploring Polymorphism in Typescript through Data Model Interfaces

Seeking out a design pattern for the following scenario: IApp.ts export interface IApp { platform: PlatformEnum; version: string; islive: boolean; title: string; iconurl: string; } IAppleApp.ts export interface IAppleApp extends IApp { ...

How can I use TypeScript to copy data from the clipboard with a button click?

One of the functionalities I have implemented is copying data to the clipboard with a button press. However, I am now looking to achieve the same behavior for pasting data from the clipboard. Currently, the paste event only works when interacting with an i ...

Incorporating Typescript with Chart.js: The 'interaction.mode' types do not match between these two entities

I am working on developing a React Functional Component using Typescript that showcases a chart created with chartjs. The data and options are passed from the parent component to the child component responsible for rendering the line chart. During the pr ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

Struggling to retrieve the header in Angular 6

When setting headers from an Express server written in NodeJS, I use the following code: app.use('/routes', function(req, res, next) { res.setHeader('test', 'test'); next(); ); The headers are successfully sent to th ...

How to access data within nested objects using ngFor in Ionic 4

How can I access the data I need from an API when it is nested within multiple objects? I am attempting to retrieve the full_url from the data object, which is nested inside the avatar object. I have already attempted the following: <ion-list> ...

What is the best way to configure distinct proxy and backend API URLs for development and production environments?

My goal is to seamlessly link an Angular / C# Web Api project on localhost while developing. For this, I typically use the following URL in the Angular app: http://localhost:5000/api/something However, this setup does not work once deployed. Ideally, I w ...

A guide on applying color from an API response to the border-color property in an Angular application

When I fetch categoryColor from the API Response, I set border-left: 3px solid {{element.categoryColor}} in inline style. Everything is functioning correctly with no development issues; however, in Visual Studio, the file name appears red as shown in the i ...

`Is it possible to integrate npm libraries with typescript and ES6?`

I am looking to focus on using ES6 as the output for a node server-side app that I plan to run on the cutting-edge iojs distribution, which hopefully has support for the latest ES6 syntax. However, I'm unsure about how to integrate standard NPM libra ...

What is the best way to retrieve a value from async/await functions?

async function fetchNetworkStatus() { const network = await Network.getConnection(); setConnection(network.isConnected); console.log(connectionStatus); if (network.isConnected) { return true; } else { ...

Tips for mocking Dependent Modules in Jasmine when dealing with a plethora of dependencies in Angular 9

Looking to create a unit test for a component within an Angular project. The main component has 5-6 dependencies and extends another class with around 7 additional dependencies. What is the most effective method to set up the TestBed for this component? ...

Error: Angular 2 Application lacks 'Access-Control-Allow-Origin' header

Currently, I am working on a project where I am focusing on learning and practicing Angular 2. Since I do not have a server-side setup, I am making API requests to the barchart ondemand api. I am facing an issue with CORS and I am wondering if there is a ...