152
votes

I'm writing an async test that expects the async function to throw like this:

it("expects to have failed", async () => {
  let getBadResults = async () => {
    await failingAsyncTest()
  }
  expect(await getBadResults()).toThrow()
})

But jest is just failing instead of passing the test:

 FAIL  src/failing-test.spec.js
  ● expects to have failed

    Failed: I should fail!

If I rewrite the test to looks like this:

expect(async () => {
  await failingAsyncTest()
}).toThrow()

I get this error instead of a passing test:

expect(function).toThrow(undefined)

Expected the function to throw an error.
But it didn't throw anything.
2

2 Answers

308
votes

You can test your async function like this:

it('should test async errors', async () =>  {        
    await expect(failingAsyncTest())
    .rejects
    .toThrow('I should fail');
});

'I should fail' string will match any part of the error thrown.

43
votes

I'd like to just add on to this and say that the function you're testing must throw an actual Error object throw new Error(...). Jest does not seem to recognize if you just throw an expression like throw 'An error occurred!'.