Creating a Mock ErrorHandler in Angular to Handle Rethrown throwErrors (using jasmine)

When using Jasmine, I have implemented tests to handle error logic from a subscribed Observable.

    this.apiService
      .post({})
      .pipe(
        take(1),
        catchError((e) => {
          return throwError(() => e);
        })
      )
      .subscribe(() => {});

The goal is to rethrow the error so it can be managed outside of the component in a custom error handler.

Chrome Headless 109.0.5412.0 (Linux x86_64) ERROR
  An error was thrown in afterAll
  [object Object] thrown
  [object Object] thrown
  [object Object] thrown

I initially attempted to override the ErrorHandler with a spy, but it did not have any effect.

I also experimented with using the jasmine.spyOnGlobalErrorsAsync, which still resulted in errors being produced.

Any suggestions or ideas on how to address this issue?

Answer №1

To handle nested unhandled exceptions within observables, consider using fakeAsync along with flush or tick inside a try-catch block.

it("should trigger uncaught exception in case of service error", fakeAsync(() =>
{
  // Arrange
  apiServiceSpy.post.and.returnValue(throwError(() => new Error("Failed service call")));

  // Act
  component.methodThatSubscribesToApiServicePost();
  let error: unknown = undefined;
  try
  {
      flush();
  }
  catch (ex)
  {
      error = ex;
  }

  // Assert
  expect(error?.message).toBe("Failed service call");
}));

If you have a custom global ErrorHandler (e.g. CustomErrorHandler implementing ErrorHandler), it should be tested separately.

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

Roles in the Nebular system always have the granted status set to true by default

Hey there, I'm currently setting up Nebular to handle roles. Everything is working fine on the server side, but on the front end side, accessControl.isGranted() always returns true regardless of the role. Here's a snippet of the code I have been ...

Is there a way to extract a specific item from a ListView by tapping on it in Nativescript?

Attempting to retrieve data from a tap event using angular2 + typescript: This is the html code for the component: <RadListView row="1" [items]="groceryList" [class.visible]="listLoaded" (tap)="seeItem($event)" swipeActions="true" (itemSwipeProgr ...

Angular error message: Trying to access the property 'name' of an undefined object leads to a TypeError

I'm having trouble phrasing this question differently, but I am seeking assistance in comprehending how to address this issue. The error message I am encountering is as follows: TypeError: _co.create is not a function TypeError: Cannot read property ...

Navigating to a component route in Angular

I need to retrieve the routing URL of a component that is different from the current URL and save it in a service. For example, if my component is called parentComponent and contains another component called childComponent, then the URL of the child compon ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

Maintaining ongoing subscriptions using rxjs in Angular 5

As a newcomer to rxjs in Angular 5, I find it a bit challenging to articulate my question, but I am hopeful for some guidance. I frequently encounter the same setup: Multiple Components to display identical data A single Service for accessing the data ...

Secure authentication for Windows and an Angular 4 web application

Currently, I am working on an Angular 4 project that requires retrieving data from an Asp.Net WebApi. The WebAPI is set up with windows authentication and I am looking for a way to pass the user's windows identity from my Angular Application to the We ...

Exploring the data connections in Firebase Realtime Database using angularfire2

I am in need of querying comments and only requesting users that are listed in the comment by their userId. This is the structure of my database in Firebase realtime db: { "comments" : { "c_id1" : { "commentId" : "c_id1", "commentText" ...

Encountering an issue with Angular where all parameters for NgZone cannot be resolved

Currently, I am in the process of learning Angular and experimenting with the Firebase Authentication services. However, every time I try to load the component that utilizes this service, I encounter an error. Error: Can't resolve all parameters for N ...

Displaying a checkmark button highlighted when the form value is toggled to true

When working with my form, I noticed that the checkboxes, which are styled as buttons, do not remain checked when clicked. Using Angular's template-driven approach to forms, I utilize an *ngFor loop to display a selection of weekdays that can be chec ...

Prep yourself for an incoming response from an object in Angular 9

Greetings, this is my debut post here so my apologies if I am not following the correct procedures. As a novice in Angular with no experience in synchronism, I kindly request that any explanation be kept as simple as possible. I am currently working with ...

The 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

Navigating between pages has become challenging due to issues with the navbar, sidebar,

I successfully developed 4 Angular components: 1st component: menu 2nd component: header 3rd component: home 4th component: login The menu component features a sidebar/navbar created using Material UI. The login component consists of the login page. Howe ...

Error: The URL constructor is unable to process /account as a valid URL address

Working on a new social media app using appwrite and nextjs, encountering an error "TypeError: URL constructor: /account is not a valid URL" upon loading the website. Here's the current file structure of my app: File Structure Below is the layout.tsx ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

Retrieving source in Angular from an async function output within a specified time limit

I have a quick query :). I'm attempting to retrieve the image src from an async function, but so far, I haven't had much success. This is what I have: <img [src]="getProductImage(articleNumber)"/> and in my TypeScript file: publi ...

Executing asynchronous functions within synchronous functions in TypeScript and returning a boolean value

Is there a way to call an asynchronous function from a synchronous function without encountering issues? function showOpenCaseDialog(): boolean { let result = false; var regardingobjectid = (<Xrm.LookupAttribute<string>>Xrm.Page.getA ...

What are the steps to creating a comprehensive bootstrap using Angular 2?

I recently stumbled upon an interesting article discussing the integration of Angular 2 components with Drupal as a backend service. If you're curious, you can read the full article here: In the article, Matt explains how to achieve this integration ...

Troubleshooting the Angular CLI issue: Module 'ansi-colors' not found

Having issues with my angular project, despite installing the latest version of NodeJs and NPM. When I try to run my project using the ng command, I encounter the following error message: Error: Cannot find module 'ansi-colors' Require stack: - ...

To allow users to sign in, the mutation can be filtered based on the boolean value of `isVerified

How can I filter and only allow users with isVerified === true to sign in? If it's false, the user should not be able to sign in through the mutation. Here is my code for the mutation: signin: async ( _: any, { credentials }: SignInArgs, ...