Published on

Testing Async Code Throws an Error by Passing an Async Function as a parameter

Authors

As JavaScript is a functional language it is easy to pass a function as a parameter to another function. Today I had to pass an async function to another function. I had tests that were using chai where I wanted to test that a piece of async code was throwing an error correctly. I tried using chai's expect(functionThatThrows).to.throw('Expected error message'); but this did not work.

As a result I ended up writing my own helper function to assist in testing this type of scenario:

async function assertThrows(funcThatShouldThrow, expectedErrorMessage) {
  try {
    await funcThatShouldThrow()
    expect.fail('An error should have been thrown!')
  } catch (error) {
    expect(error.message).to.equal(expectedErrorMessage)
  }
}

This code can then be used as follows:

assertThrows(async () => {
  await asyncCodeThatThrowsError(0, 10)
}, 'Whatever error you are expecting')