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

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

    Based on Bergi answer I've suggest more universal solution that utilizes original assert.throws for error messages:

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

    Usage:

    it('should throw', async function () {
        await assertThrowsAsync(async () => await asyncTask(), /Error/);
    });
    

提交回复
热议问题