Jest: Async / Await expect().toThrow() does not work as expected

Created on 12 Feb 2018  ·  5Comments  ·  Source: facebook/jest

I'm trying to assert that a promise throws an error with Async / Await.

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  expect(async () => {
    await throws()
  }).toThrow()
})

This is what I'm getting:

● promise throws

expect(function).toThrow(undefined)

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

Any thoughts? Does Jest not support this? Or am I using it incorrectly?

Most helpful comment

What?

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  await expect(throws()).rejects.toThrow()
})

This is solved, please read the docs before commenting on old issues. https://jestjs.io/docs/en/asynchronous#resolves-rejects

All 5 comments

However this passes:

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  let message = false
  try {
    await throws()
  } catch (e) {
    message = e.message
  }
  expect(message).toBeTruthy()
})

Basic functionality candidate.

What?

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  await expect(throws()).rejects.toThrow()
})

This is solved, please read the docs before commenting on old issues. https://jestjs.io/docs/en/asynchronous#resolves-rejects

What?

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  await expect(throws()).rejects.toThrow()
})

This is solved, please read the docs before commenting on old issues. https://jestjs.io/docs/en/asynchronous#resolves-rejects

The important thing in the solution is to await the expect. Otherwise your checks will always pass.
Alternatively you could also return the expect like they do it in the docs.

Was this page helpful?
0 / 5 - 0 ratings