Testing an HTTP error Observable with Jasmine and RxJS simulations

I encountered a similar issue, but due to commenting constraints on other questions, I had to create a new one. The problem lies in a jasmine test where a function is expected to manage an error from a service call. The service call returns an RxJS `Observable` of an `HttpResponse`, yet the function under test does not seem to receive any response from the service, even when using a spy to simulate the error. Here's the code structure:

component.ts:

public thingThatCallsService() {
    this.foo = false;
    this.service.bar()
        .subscribe(
            (res) => {log(res)},
            (err) => {
                log(err) // Logs empty string during test
                if (err.status === 400) this.foo = true;
            }
        );
}

mockService.ts: (Used by the test suite instead of the actual service)

public bar() {
    return of(new HttpResponse());
}

test.ts:

it("sets foo to true if bar returns an error", fakeAsync(() => {
    spyOn(service, "bar").and.returnValue(
        throwError(() => new HttpErrorResponse({status: 400}))
    );
    component.thingThatCallsService();
    tick();
    componentFixture.detectChanges();
    expect(service.bar).toHaveBeenCalled();
    expect(component.foo).toBeTrue(); // Failing consistently
}))

Similar questions like this and this lack suitable solutions – some suggest returning a string rather than an object with a `status` field, or provide outdated/inaccurate code snippets.

It's worth mentioning that the code functions correctly outside the test environment; when the service encounters an error with a specific status code, `foo` is indeed set to true.

If you have any insights on how to properly handle errors thrown by the `Observable` for subscription handling, your guidance would be greatly appreciated. Thank you!

Answer №1

Could you please attempt the following to check if it resolves the issue?

spyingOn(service, "bar").and.returnValue(
        throwingError(() => ({ status: 400 }))
    );

Additionally, examine the log results in this situation too. I am uncertain why HttpErrorResponse is not functioning as expected.

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

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

I attempted to use ng add @angular/pwa, but encountered an error code that is baffling to me. Are there any steps I can take to resolve this issue?

npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While trying to find a solution: [email protected] npm ERR! Found: @angular/[email protected] npm ERR! in node_modules/@angular/common npm ERR! @angular/common@"^14.2.3" ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

Dragging and dropping elements onto the screen is causing them to overlap when trying

I am having trouble merging the drag and drop functionality from Angular Material with resizing in a table. Currently, both features are conflicting and overlapping each other. What I am hoping for is to automatically cancel resizing once drag and drop s ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

I possess both a minimum and maximum number; how can I effectively create an array containing n random numbers within

Given a minimum number of 10.5 and a maximum number of 29.75, the task is to generate an array within these two ranges with a specific length denoted by 'n'. While the function for generating the array is provided below, it is important to calcul ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Sign up for the completion event within the datetime picker feature in Ionic 2

How can I subscribe to the "done" event in Ionic2, where I want to trigger a function after selecting a date? <ion-icon class="moreicon" name="funnel"> <ion-datetime type="button" [(ngModel)]="myDate" (click)="getData()"></ion-datetime> ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

Exploring the depths of nested JSON with Angular2

I'm a beginner in Angular 2 using Typescript. I am trying to figure out how to access the 'D' and 'G' elements in my JSON data using NgFor. Is there a specific way or method that I can use to achieve this? [ { "A":"B", "C" ...

The tsconfig.json file does not support the path specified as "@types"

Having set up multiple absolute paths for my Next.js application, I encounter an issue where importing a component from the absolute path results in something like "../componentName" instead of "@components/componentName" when I am inside another folder. T ...

No errors encountered during compilation for undefined interface object types

Hey there, I'm currently exploring the Vue composition API along with Typescript. I'm facing an issue where I am not receiving any errors when an interface does not align with the specified types for that interface. Although my IDE provides aut ...

The type '{ children: Element; }' is lacking the specified properties within type - NextJS version 13.0.6 with TypeScript version 4.9.3

Currently, I am delving into NextJS / TypeScript and have come across a type error. The component structure is as follows: interface LayoutProps { children: React.ReactNode; title: string; keywords: string; description: string; } const Lay ...

Enhancing nested structures in reducers

Currently, I am utilizing react, typescript, and redux to develop a basic application that helps me manage my ingredients. However, I am facing difficulties with my code implementation. Below is an excerpt of my code: In the file types.ts, I have declared ...

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

Acquired this as empty

I encountered a strange error message saying "this is null" and I can't figure out what the issue is. Here is my demo on Stackblitz.com with an example code for your reference. Component ngOnInit() { this.getCurrentLocation(); } getCurrentL ...

Prevent Typescript from flagging unnecessary warnings about unassigned values that will never be assigned

One of my functions serves as a shortcut for selecting values from synchronous observable streams. The function in its entirety looks like this: export function select<T>(inStream: Observable<T>): T { let value: T; race( inStream, ...