I\'m struggling to work out the best way to verify that a promise is rejected in a Mocha test while using async/await.
Here\'s an example that works, but I dislike t
A no dependency on anything but Mocha example.
Throw a known error, catch all errors, and only rethrow the known one.
it('should throw an error', async () => {
try {
await myFunction()
throw new Error('Expected error')
} catch (e) {
if (e.message && e.message === 'Expected error') throw e
}
})
If you test for errors often, wrap the code in a custom it function.
function itThrows(message, handler) {
it(message, async () => {
try {
await handler()
throw new Error('Expected error')
} catch (e) {
if (e.message && e.message === 'Expected error') throw e
}
})
}
Then use it like this:
itThrows('should throw an error', async () => {
await myFunction()
})