10

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: {}
Rodrigo
  • 135
  • 4
  • 45
  • 107
  • You may need to await the `test` function as it's just an unresolved async function at that point, hence why it hasn't thrown. – Mark Atkinson Feb 01 '21 at 21:10
  • 1
    Async functions *return promises*, which may reject, they don't throw errors. Read https://jestjs.io/docs/en/asynchronous. – jonrsharpe Feb 01 '21 at 22:04

1 Answers1

22

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

lissettdm
  • 12,267
  • 1
  • 18
  • 39
  • 1
    You can also use toStrictEqual in place of toBe and add the exception being thrown as argument. ```expect(err).toStrictEqual(Exception); ``` – Anurag Phadnis Apr 20 '21 at 07:59