Search code examples
javascriptnode.jsasync-awaitassertecmascript-next

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


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.)


Solution

  • Since the question is still getting attention, I'd like to sum up the two best solutions, especially to highlight the new standard method.

    Node v10+

    There's a dedicated method in the assert library, assert.rejects.

    For older versions of Node

    A fill from vitalets answer:

    import assert from 'assert';
    
    async function assertThrowsAsync(fn, regExp) {
      let f = () => {};
      try {
        await fn();
      } catch(e) {
        f = () => {throw e};
      } finally {
        assert.throws(f, regExp);
      }
    }