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

后端 未结 5 725
失恋的感觉
失恋的感觉 2021-02-05 03:44

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

const test = async () => await aPromi         


        
5条回答
  •  無奈伤痛
    2021-02-05 04:42

    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.

提交回复
热议问题