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

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

    The answers given work, but I came across this issue today and came up with another solution, that I think is a little simpler.

    // Code being tested
    async function thisFunctionThrows() {
        throw new Error('Bad response')
    }
    
    
    // In your test.
    try {
        await thisFunctionThrows()
        assert.equal(1 == 0) // Never gets run. But if it does you know it didn't throw.
    } catch (e) {
        assert(e.message.includes('Bad response'))
    }
    

提交回复
热议问题