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

Should I use connect or refCount with Angular and rxjs?

I was pondering how to reuse data from observables, so I decided to hold an observable and manipulate the data using map operators after researching and seeking advice. By making a single HTTP request, storing it in a variable, and manipulating it there, I ...

The bar chart functions perfectly on localhost but encounters issues after being hosted on Gitpage

Localhost Gitpage The bar chart was displaying correctly on localhost, but once it was hosted on Gitpage, it began to show issues. Any suggestions on how to resolve this? Repository Link: https://github.com/mzs21/bar-chart Live Preview: ...

Comparing the Calculation of CSS Selector Specificity: Class versus Elements [archived]

Closed. This question requires additional information for debugging purposes. It is not currently accepting answers. ...

Enhance your Angular Material Table with split headers and sticky header capabilities

I am having an issue with the header of my Angular Material table. I need help adding a sticky header feature. I tried using sticky: true, but it's not working for my first column since I have hidden it. Additionally, the first row is displaying the ...

Error encountered in Typescript function wrapper: The provided data type of number[] cannot be assigned to [number]

Within this code snippet, the function requires two arguments: one for the function that needs to be wrapped and another for the argument producer. function wrapper<K extends Array<any>, T>(fn: (...args: K) => T, pd: (...args: any) => K): ...

The application is experiencing compilation issues following the creation of mime-type.validator.ts. This problem has been reported by one author

I originally created a file called mime-type.validator.ts. Although I haven't used this file yet in my application, it does exist within my project. However, now my application is failing to compile and displaying the following error message: Faile ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

What is the best way to choose a dropdown item at random from a list using Angular 5?

My current setup involves a list that looks like this... export const inventory= [ 'coffee' 'tea' 'wine' 'beer' 'sake' .... ]; Within the HTML, I am using a loop to create dropdown menus a set number of t ...

The npm build command is triggering an error message that reads "Allocation failed due to ineffective mark-compacts near heap limit."

I'm currently working on a ReactJS/TypeScript project on Windows 10. I've been running into issues when trying to build my TypeScript scripts using the following command: "rimraf ../wwwroot/* && react-scripts-ts build && copyfi ...

Using Typescript to configure a custom proxy in a Create React App

I am looking to implement request proxying from a Create React App to a separate API server, with the ability to set the server dynamically or using environment variables. While I have followed the guide on manually configuring the proxy, I am encounteri ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

When using Typescript with MUI styled components, there may be issues with recognizing common objects for styles

I'm facing a challenge where I have various styled components with some shared styles. To address this, I decided to create a function that takes in a `theme` parameter and outputs the common styles being used. Here's a glimpse of what I came up ...

What is the reason behind permitting void functions in the left part of an assignment in Typescript?

Take a look at this Typescript snippet: let action = function (): void { //perform actions }; let result = action(); What makes it suitable for the TypeScript compiler? ...

Working with JSON data in AngularJS2's templates

Is there a way for me to process JSON from the template in a manner similar to the second code I provided? First code. This method works well when using .json and .map () @Component({ ..// template: `..// <li *ngFor="#user of users"> ...

The parameter type must be a string, but the argument can be a string, an array of strings, a ParsedQs object, or an array of ParsedQs objects

Still learning when it comes to handling errors. I encountered a (Type 'undefined' is not assignable to type 'string') error in my code Update: I added the entire page of code for better understanding of the issue. type AuthClient = C ...

Creation of Card Component with React Material-UI

I am facing difficulties in setting up the design for the card below. The media content is not loading and I cannot see any image on the card. Unfortunately, I am unable to share the original image due to company policies, so I have used a dummy image for ...

When working in React, I often encounter the frustrating TypeError: Cannot read property 'content' of undefined error

Trying to customize a React project, I attempted to add a class to a div using the following code: <div className={styles.content}> In the case of deleting the Data Source, you will lose all configuration sett ...

The implementation of race in React Redux Saga is proving to have negligible impact

I have implemented the following saga effect: function* loginSaga() { const logoutTimeoutCreationDate: string | null = yield localStorage.getItem('logoutTimeoutCreationDate'); let logoutTimeout: number; if (!logoutTimeoutCreationDate || + ...

Encountering a hiccup while attempting to initialize a fresh Angular project with the command "ng new my

I encountered an error issue after running the command npm new project0 npm ERR! path D:\Polytech\Génie Informatique\2- Génie Informatique 4\Programmation Web\Angular\project0\node_modules\js-yaml\bin\js ...

Retrieve every item in a JSON file based on a specific key and combine them into a fresh array

I have a JSON file containing contact information which I am retrieving using a service and the following function. My goal is to create a new array called 'contactList' that combines first names and last names from the contacts, adding an &apos ...