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

后端 未结 5 694
失恋的感觉
失恋的感觉 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:45

    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);
      }
    }
    

提交回复
热议问题