Jest encountered an UnhandledPromiseRejection error because the promise was unexpectedly resolved instead of being rejected

I am facing a difficult error message from Jest that I can't seem to figure out. The error message indicates that the promise is being resolved instead of rejected, causing an unhandled promise rejection. It's confusing because Jest expects an error to be thrown, but when it is thrown, it claims it is unhandled. I feel like I must be missing something here.

Below is the error message I am receiving:

node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled with .catch().
The promise rejected with the reason "Error: expect(received).rejects.toThrowError()

Received promise resolved instead of rejected
Resolved to value: undefined".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
error Command failed with exit code 1.

Here is the code snippet that is causing the error:

    describe('credentials test', () => {
        it('without credentials', async () => {
            const provider = new Provider();
            provider.configure(testConfig);
            const spyon = jest.spyOn(Credentials, 'get').mockImplementation(() => {
                return Promise.reject('err');
            });

            const action = async () => {
                await provider.create({
                    param: val,
                });
            };

            expect(action()).rejects.toThrowError();
            spyon.mockRestore();
        });
    });

And here is the relevant code being tested:

    public async create(
        params: CreateInput
    ): Promise<CreateOutput> {
        const cmd = new Command(params);
        const client = this._init();

        try {
            const credentialsOK = await this._ensureCredentials();
            if (!credentialsOK) {
                logger.error(NO_CREDS_ERROR_STRING);
                throw Error;
            }

            const output = await client.send(cmd);
            return output;
        } catch (error) {
            logger.error(`error - ${error}`);
        }
    }

    private async _ensureCredentials() {
        return await Credentials.get()
            .then(credentials => {
                if (!credentials) return false;
                const cred = Credentials.shear(credentials);
                logger.debug('set credentials', cred);
                this._config.credentials = cred;

                return true;
            })
            .catch(error => {
                logger.warn('ensure credentials error', error);
                return false;
            });
    }

Answer №1

Here to offer guidance on a common problem, drawing inspiration from @bergi's insight. When using await with

expect(someFunction()).rejects.toThrowError()
, your code will resemble:

  it(`Should throw an error when bad things happen`, async () => {
    const result = doThing()
    await expect(result).rejects.toThrowError(`oh no`);
  });

Addressing the follow-up question from the original poster:

expect(received).rejects.toEqual() -- Received promise resolved instead of rejected -- Resolved to value: undefined

This issue arises from the function returning undefined instead of throwing an error, as noted by Jest. To rectify this, consider adding throw new Error('oh no') within the relevant code (keeping in mind this is a separate matter).

Answer №2

Dealt with in jest.config.js

setupFiles: ['<rootDir>/jest.setup.js'],

jest.config.js

process.on('unhandledRejection', reason => {
    return;
});

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

What steps do I need to take to create a custom image for a website?

I'm looking for a way to create a website image using just code, without the need for an actual image file or image tag. Is there a method to do this? Would I use CSS, Javascript, or HTML5 for this task? If using JavaScript to dynamically generate the ...

Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve thi ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

Issue with Redux-form's type prop not functioning as expected with checkbox and radio components

Hey there, I'm new to working with redux forms and I've been trying to figure out how to use input types other than "text". I've read through the documentation but for some reason, types like "checkbox" or "radio" are not showing up in the b ...

Check to see if the user has been redirected to the page using JavaScript

When a file input validation fails in a Laravel project, the user is redirected back to the current page. However, the issue arises when the user has to scroll down to see the error message and understand what went wrong. This doesn't provide the bes ...

Retrieve the nearest identifier text from the tables

I have a table on my webpage with some data: <tbody id="carga"> <tr> <td>1</td> <td id="nombre">esteban</td> <td id="apellido">aguirre</td> <td>N/A</td> <td>N/A</td ...

Kindly include an @Ionic3Annotation for either @Pipe, @Directive, or @Component

During development, this code runs without any issues. However, when attempting to run it in production using the command: Working: ionic cordova run android Not working: ionic cordova run android --prod --release Error Message: [03:34:41] types ...

Tips for ensuring math formulas display correctly in CKEditor

I'm currently struggling to properly display the correct format of a math formula in ckeditor. I have made numerous attempts to find a solution, but so far, none have been successful. Here is an excerpt of my code: <html> <head> <scr ...

Looking for the quickest hash and salt method for IP addresses in Node.JS?

Currently, there are many stipulations regarding the tracking of user data such as unique visits and returning users. An issue arises in certain regions where IP addresses are considered sensitive personal information. To continue identifying unique user ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

Developing a Highchart Graph using JavaScript

I am trying to develop a high chart graph. Check out my code on FIDDLE LINK. I have two values, a and b, for the x-axis and y-axis. The issue arises when the difference between a and b is minimal, such as when both are equal (-9). In such cases, the grap ...

What purpose does the additional symbol "$()" serve in the selector "$($())"?

Currently, I am looking to incorporate a jQuery scrollspy feature into one of my ongoing projects. Upon coming across this jsfiddle (https://jsfiddle.net/mekwall/up4nu/), I successfully integrated it into my project. However, I have hit a roadblock while ...

React and React Router are causing the login screen layout to persistently display

The MUI Theme Provider I have includes a Layout with Dashboard and Order screens. Even though the user hits the '/' endpoint, the Login Screen should be displayed instead of the Layout. -App.js <ThemeProvider theme={theme}> <Router> ...

The functionalities of Google Maps are experiencing issues within AngularJS when utilizing the $route feature

Having Issues with Google Maps in AngularJS when using <ng-view></ng-view> Routing Configuration app.config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { t ...

What is the best method for choosing the final element with a specific class in each row?

Within each row, there are various cells that have the class .meow. How can I target the last .meow element in each row? The provided code currently selects all existing .meows... $("tr").each(function(){ $(".meow").css("border", "3px solid red"); ...

Error: Attempting to access the `isPaused` property of a null object is not possible

For my Vue front-end app, I'm attempting to integrate wavesurfer.js. However, upon receiving the audio file link from the backend, I encounter the following error: wavesurfer.js?8896:5179 Uncaught (in promise) TypeError: Cannot read property 'isP ...

What is the best way to display my table?

In the index.php view, you will find my table located <table class="striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th ...

Opening a new tab in Angular 6 from a component with freshly generated HTML (containing input data)

Hello everyone. I have a requirement where I need to open a new browser tab with formatted input data from a modal component. Here's an example code snippet that attempts to achieve this using ng-template: @Component({ template: '< ...

Vue encountered a double loading issue when utilizing a library compiled with Webpack

I am facing an issue with my TypeScript library of Vue components that gets compiled into a single JS file using Webpack. The problem arises when the TypeScript project consuming this library also depends on Vue. Upon running the application, I noticed tha ...

What could be causing the lack of color change in my boxes even after confirming the prompt?

function changeColor() { if (confirm("Press a button!") == true) { if(this.style.backgroundColor == "white") this.style.backgroundColor = "yellow"; else if(this.style.backgroundColor == "yellow") this.style.backgroundColor = "red"; else i ...