Issue with detecting errors in Angular unit test when using jest throwError method

Imagine I have a component that contains the following method:

someMethod() {
  this.someService
    .doServicesMethod(this.id)
    .pipe(
      finalize(() => (this.loading = false)),
      catchError((e) => {
        this.showErrorMessage = true;
        return throwError(e);
      }),
    )
    .subscribe({
      next: (result) => {/* handle result*/},
    });
}

Now, I want to create a unit test using jest. Here is how I proceed:

it(
  'should test someMethod',
  waitForAsync(() => {
    spyOn(someService, 'doServicesMethod').and.returnValue(throwError('someError'));

    expect(component.showErrorMessage).toBeFalsy();
    expect(component.loading).toBeTruthy();

    try {
      component.someMethod();
    } catch (error) {
      expect(component.loading).toBeFalsy();
      expect(component.showErrorMessage).toBeTruthy();
    }
  }),
);

Unfortunately, the unit test does not work as expected. I initially attempted running the test without waitForAsync, which caused the error to be detected in subsequent tests, leading to failure with someError.

Using waitForAsync helps detect the error but not within the try-catch-block, causing the test itself to fail.

Even calling tick(); after component.someMethod(); detects the error, however, it is not properly caught and results in a failure with someError.

I am having trouble finding a solution, so if anyone has any ideas on how to make this test successful, please share them!

Answer №1

I have always relied on using the expect().toThrow() or expect().toThrowError() methods

it('should test someMethod', async () => {
    expect( () => {
        await component.someMethod()
    }).toThrow();
});

You can also handle specific errors by using

toThrowError(<Replace with Error>)

If I'm not working with a promise, I typically do:

it('should test someMethod', () => {
    expect( () => {
        component.someMethod()
    }).toThrow( ... );
});

If your try/catch isn't catching errors and this approach isn't effective, ensure that someMethod is actually throwing an error.

Here's a sample function I use:

export function ExpandTextStringToArray(
    DataField: string,
    Separator: string = ',',
    TrimText: boolean = false
): string[] {
    if (DataField === undefined || DataField === null) {
        throw new Error(APPLICATION_EXCEPTIONS.VALUE_MUST_BE_STRING);
    }
    const ExpandedString: string[] = DataField.split(Separator);
    if (TrimText) {
        ExpandedString.forEach((Text, Index, Data) => {
            Data[Index] = Text.trim();
        });
    }
    return ExpandedString;
}

Here's a successful test case that catches the thrown error:

it('should throw an exception when passing null for the DataField', () => {
    expect(() => {
        ExpandTextStringToArray(null);
    }).toThrowError(APPLICATION_EXCEPTIONS.VALUE_MUST_BE_STRING);
});

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

Display the initial MUI components from an array of data in a distinctive manner

Trying to display the content of an Accordion by passing props down through a list array to a component. I have identified the issue but unsure how to call the component and pass the props differently. Below is the code snippet. Code for the parent compon ...

The input tag loses focus after its value is updated using a class method in Angular 8.x

Currently, I am working on integrating a credit card payment method and formatting its number through specific methods. Here is how it is done: HTML <div class="form-group" *ngFor="let formField of cardFields; let cardFieldIndex = index;"> ...

The issue of Angular 6 view failing to display accurate data upon page load

In my Angular 6 application, I've implemented a login feature using Firebase's Google login. The interface includes a button labeled Login when the user is logged out, and changes to Logout with the current email address displayed when the user i ...

Generating React Components Dynamically using TypeScript

Attempting to generate an element in React using Typescript based on the given tagName passed as props, along with additional relative element properties depending on that particular tagName. Take a look at the code snippet below: type ElementProps<Tag ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

Verify Angular route path using an interceptor

I have configured a route path like this: { path: 'user/:id/edit/:type', component: UserEditTypeComponent, }, I am trying to access this path from an interceptor using activated routes: constructor(private activatedRoute: ActivatedRout ...

The defaultValue of the Observable TextArea is blank space following the transmission of a sendMessage using SignalR in a Typescript

i am currently in the process of modifying a basic SignalR Chat feature. Here is the situation: when a user sends a message, the message gets sent successfully. However, the textarea from which it was sent remains filled with empty space (aside from the p ...

Server Components can only receive plain objects and select built-ins from Client Components. Any classes or null prototypes will not be compatible

I am encountering an error when wrapping the App.ts with queryclientprovider: "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." Below is the code snippet from ...

There was an issue with the program: "ERROR TypeError: When trying to call a method from the

Hey everyone, I'm attempting to retrieve data from an API using a specific service and then log the data in the console. However, I'm encountering an error with the component and service I'm using that reads: ERROR TypeError: Cannot read pro ...

Tips for avoiding the transmission of className and style attributes to React components

Hey there! I'm working on a custom button component that needs to accept all ButtonHTMLAttributes except for className and style to avoid any conflicts with styling. I'm using TypeScript with React, but I've run into some issues trying to ac ...

Guide on integrating the plyr npm module for creating a video player in Angular2

Looking to implement the Plyr npm package in an Angular 6 application to create a versatile video player capable of streaming m3u8 and Youtube videos. The demos on their npm page are written in plain JavaScript, so I need guidance on how to integrate it in ...

What is the best way to transform a JSON data-storing object into an array within Angular?

I am currently working on developing a machine learning model using tensorflow.js, but I have encountered a roadblock. The issue I am facing is that I have stored my JSON content in a local object, but for it to be usable in a machine learning model, I ne ...

Disable the selection of the year option in the Angular Material Date picker

I need help with disabling the year selection in the Angular Material date picker component. To achieve this, I have implemented a custom native date adapter which only allows the selection of the day and month, keeping the year fixed. Here is a snippet ...

How can I verify the value of a class variable in TypeScript by using a method?

I need a more concise method to inform TypeScript that my client has been initialized (no longer null). While I have achieved this functionality, the current implementation seems unnecessarily verbose. Here is how it currently looks: export abstract class ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

The element in TS 7023 is implicitly assigned an 'any' type due to the fact that an expression of type 'any' is not valid for indexing in type '{}'

I have implemented a select-box that includes options, labels, optgroups, and values. Is my approach correct or is there something wrong with the way I have defined my types? interface Option { label: string value: string selected?:boolean mainGrou ...

Issue with displaying international characters when using HttpClient's http.get() function in Angular.The

I am facing an issue that I can't quite figure out as I am new to Angular. My goal is to read a local .csv file and display its contents in a table. Everything seems to be working fine, except for the fact that when special characters like "č, ć, š ...

What is the most effective way to retrieve the width and height of an oversized image in Angular?

After attempting to retrieve the image width using the ngAfterViewInit method, a result of width = 0 is returned due to the large size of the image. Is there a way to accurately determine the image width without relying on a setTimeout() function? For re ...