Node.js assert.throws with async functions (Promises)

mattecapu picture mattecapu · Mar 3, 2016 · Viewed 10.9k times · Source

I want to check if an async function throws using assert.throws from the native assert module. I tried with

const test = async () => await aPromise();
assert.throws(test); // AssertionError: Missing expected exception..

It (obviously?) doesn't work because the function exits before the Promise is resolved. Yet I found this question where the same thing is attained using callbacks.

Any suggestion?

(I'm transpiling to Node.js native generators using Babel.)

Answer

Bergi picture Bergi · Mar 3, 2016

node 10 and newer

Since Node.js v10.0, there is assert.rejects which does just that.

Older versions of node

async functions never throw - they return promises that might be rejected.

You cannot use assert.throws with them. You need to write your own asynchronous assertion:

async function assertThrowsAsynchronously(test, error) {
    try {
        await test();
    } catch(e) {
        if (!error || e instanceof error)
            return "everything is fine";
    }
    throw new AssertionError("Missing rejection" + (error ? " with "+error.name : ""));
}

and use it like

return assertThrowsAsynchronously(aPromise);

in an asynchronous test case.