UnhandledPromiseRejectionWarning while using assert.doesNotReject

Viewed 46
const assert = require('assert');

main = () => {
    try {
        const toTest = async () => {
            return Promise.reject('ERROR'); // or throw 'Error';
        }
        assert.doesNotReject(toTest, TypeError);
    } catch (e) {
        console.log(e);
    }
}

main();

After copying to file and run it. It prompts out

(node:3056) UnhandledPromiseRejectionWarning: ERROR
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3056) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:3056) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

It just gives the warnings. Anyway to fix this? thanks

2 Answers

This is because from Node v7 if you don't handle a rejected promise you would get the UnhandledPromiseRejectionWarning warning. It's expected that you handle all promise rejections with a .catch(...) or if you are using async/await then you handle it with a try...catch block. This is to ensure that you don't ignore any errors that happen in your code, in a future Node version this warning would actually be an error.

Your code is giving this warning because toTest is returning a Promise rejection but it's not being handled.
When you call assert.doesNotReject(toTest, TypeError); it awaits the toTest promise and checks that the promise is not rejected. Since the awaited promise returns a rejection the assertion will catch it and reject it again and since the rejected promise isn't handled it will give a warning saying UnhandledPromiseRejectionWarning.

Using assert.doesNotReject() is actually not useful because there is little benefit in catching a rejection and then rejecting it again.

Source: https://nodejs.org/api/assert.html#assert_assert_doesnotreject_asyncfn_error_message

I found out that assert.doesNotReject returns a promise so instead of 'assert.doesNotReject(...)', it should be 'await assert.doesNotReject(...)'

Related