Anticipate an asynchronous function causing an error in a Jest test scenario

If I were to play around and execute the code snippet below:

    await expect(async () => {
      const asyncFunc = async () => {
        return Promise.reject(new Error('Foo'))
      };
      await asyncFunc();
    }).toThrow();

I assumed it would pass since the promise is rejected with an error, but surprisingly it passes. Is there a method to confirm that the async function actually throws the error?

Answer №1

An async function won't throw an exception. Instead, it will always return a promise that could potentially be rejected.

To verify this behavior, you should test the promise using Jest as shown below:

const asyncFunc = async () => {
  return Promise.reject(new Error('Foo'))
};
await expect(asyncFunc()).rejects.toEqual('Foo');

For more information on testing rejected promises with Jest, check out these resources: How do I properly test for a rejected promise using Jest? and Best Way to Test Promises in Jest.

Answer №2

It seems like you are looking for the .rejects function.

Make sure to use async/await when testing asynchronous functions:

To validate that an asynchronous function throws an error, you can do something like this:

await expect(asyncFunc()).rejects.toThrow();

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 Group Formation Issue

I keep encountering the following error: formGroup expects a FormGroup instance. Please pass one in. This is how it looks in HTML: <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> And in my Typ ...

The type 'HTMLDivElement | null' cannot be assigned to the type 'HTMLDivElement' in this context

Struggling with a scroll function to maintain position while scrolling up or down - encountering an error: Error: Type 'HTMLDivElement | null' is not assignable to type 'HTMLDivElement'. Type 'null' is not assignable to type & ...

Update button Image upon click

Is there a way to swap the image on a button when it's clicked? I want my button to start with one icon, but then change to another icon once it has been clicked. How can I achieve this effect? Any suggestions on how to make this happen? Check out ...

The React Fabric TextField feature switches to a read-only mode once the value property is included

I've been grappling with how to manage value changes in React Fabric TextFields. Each time I set the value property, the component goes into read-only mode. When utilizing the defaultValue property, everything functions correctly, but I require this i ...

Issues with the md-radio-button not functioning properly in Angular 2

I'm in need of two radio buttons to choose between two options. Here's the code I'm using: <md-radio-button [value]=true [(ngModel)]="carSelected" name="carOption">Car</md-radio-button> <md-radio-button [value]=false [(ngMode ...

What NonNullable<T> Means in TypeScript

During my search for a Nullable type in TypeScript, I stumbled upon the NonNullable type in the file path: C:\Program Files\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.es6.d.ts T ...

TypeScript Redux expands the type system

Currently, I am working with Redux along with React and Typescript. I have been following the official Redux documentation's "Usage with TypeScript" section available at https://redux.js.org/usage/usage-with-typescript. export type AppDispatch = type ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

Guidance on transferring information from a parent component to an Angular Material table child component

Currently, I am implementing an angular material table with sorting functionality. You can view the example here: Table Sorting Example I intend to transform this into a reusable component so that in the parent component, all I have to do is pass the colu ...

What methods can be used to search within one array in order to filter another array contained in a list?

Looking for suggestions on creating a filter in one list based on another list How can I handle filtering an array within a list by searching in another array? For example... myArray = [ { "name": "Item-A", "tags": ["Facebook" ...

Implement a system in Angular Service that automatically generates user IDs for an array of user inputs

How can I automatically increment the user ID for each new user input and use that value for deletion or updating of specific entries? If a user adds their details as shown in the output picture link below, I want to display the output in a similar format ...

Issue with Jest while testing a React component library that has been bundled without the React library

I have extensive experience building React applications and decided to create a React Component library. After researching different approaches, I chose to use Webpack and Babel for bundling without including React itself in the library. This decision was ...

Enhancing the TypeScript typings of modules in Angular 2

In my Angular2 application, I am facing an issue with an external NPM package that has an outdated typings file. This means there are functions within the package that are present but not declared in the typings file. My main goals are: To create and ut ...

What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified) This is my current component ...

Assign a dynamic class to an element within an ngFor iteration

I am working with a template that includes an app-subscriber component being iterated over using *ngFor: <app-subscriber *ngFor="let stream of streams" [stream]="stream" [session]="session" (speakEvents)='onSpeakEvent($event)'> ...

Dealing with performance issues in React Recharts when rendering a large amount of data

My Recharts use case involves rendering over 20,000 data points, which is causing a blocking render: https://codesandbox.io/s/recharts-render-blocking-2k1eh?file=/src/App.tsx (Check out the CodeSandbox with a small pulse animation to visualize the blocki ...

Angular does not propagate validation to custom form control ng-select

In my Angular 9 application, I am utilizing Reactive Forms with a Custom Form Control. I have enclosed my ng-select control within the Custom Form Control. However, I am facing an issue with validation. Even though I have set the formControl to be requir ...

Error: ngModel does not reflect dynamic changes in value

After calling a Spring service, I am receiving JSON data which is stored in the "etapaData" variable. 0: id: 266 aplicacao: {id: 192, nome: "Sistema de Cadastro", checked: false} erro: {id: 220, nome: "Falta de orçamento", checked: false} perfil: {id: 8, ...

Unveiling the proper extension of component props to default HTML button props

Currently, I am in the process of developing a button component that includes a variant prop to specify its color scheme. Below is a simplified version of the code: interface Props extends React.HTMLProps<HTMLButtonElement> { variant: 'yellow ...

I find it confusing how certain styles are applied, while others are not

Working on my portfolio website and almost done, but running into issues with Tailwind CSS. Applied styling works mostly, but some disappear at certain breakpoints without explanation. It's mainly affecting overflow effects, hover states, and list sty ...