Jest expect exception not working with async

Viewed 3607

I am writing a test that supposedly should catch an exception

describe('unauthorized', () => {
  const client = jayson.Client.http({
    host: 'localhost',
    port: PORT,
    path: '/bots/uuid',
  })

  it('should return unauthorized response', async () => {
    const t = async () => {
      await client.request('listUsers', {})
    }

    expect(t()).toThrow(Error)
  })
})

I am pretty sure that client.request is throwing an exception but Jest says:

Received function did not throw

const test = async () => {
 ...
}

Is the correct way to check?

UPDATE

If I change to

expect(t()).toThrow(Error)

I got

expect(received).toThrow(expected)

Matcher error: received value must be a function

Received has type:  object
Received has value: {}
1 Answers

You can use rejects

 it('should return unauthorized response', async () => {
    await expect(client.request('listUsers', {})).rejects.toThrow(/* error you are expecting*/);
 })

Or

You can use try/catch

 it('should return unauthorized response', async () => {
    const err= null;
    try {
      await client.request('listUsers', {});
    } catch(error) {
      err= error; //--> if async fn fails the line will be executed
    }

    expect(err).toBe(/* data you are expecting */)
  })

You can check the error type of and the error message

Related