开玩笑期望异常不适用于异步 [重复]

Jest expect exception not working with async [duplicate]

提问人:Rodrigo 提问时间:2/2/2021 最后编辑:Rodrigo 更新时间:2/2/2021 访问量:7673

问:

我正在编写一个测试,据说应该捕获异常

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)
  })
})

我很确定这引发了一个异常,但 Jest 说:client.request

接收函数未抛出

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

检查方法是否正确?

更新

如果我更改为

expect(t()).toThrow(Error)

我得到了

expect(received).toThrow(expected)

Matcher error: received value must be a function

Received has type:  object
Received has value: {}
JavaScript 打字稿 jestjs

评论

0赞 Mark Atkinson 2/2/2021
您可能需要等待该函数,因为它当时只是一个未解析的异步函数,因此它没有抛出。test
1赞 jonrsharpe 2/2/2021
异步函数返回 promise,这些 promise 可能会拒绝,但不会引发错误。阅读 jestjs.io/docs/en/asynchronous

答:

22赞 lissettdm 2/2/2021 #1

您可以使用拒绝

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

你可以使用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 */)
  })

您可以检查错误和type oferror message

评论

1赞 Anurag Phadnis 4/20/2021
您还可以使用 toStrictEqual 代替 toBe,并将抛出的异常添加为参数。expect(err).toStrictEqual(Exception);