【问题标题】:Jest expect exception not working with async [duplicate]开玩笑期望异常不适用于异步[重复]
【发布时间】:2021-05-06 01:35:33
【问题描述】:

我正在编写一个应该捕获异常的测试

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

我很确定 client.request 正在抛出异常,但 Jest 说:

接收到的函数没有抛出

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: {}

【问题讨论】:

  • 您可能需要等待test 函数,因为此时它只是一个未解析的异步函数,因此它没有抛出。
  • 异步函数 return promises,可能会被拒绝,但它们不会抛出错误。阅读jestjs.io/docs/en/asynchronous

标签: javascript typescript jestjs


【解决方案1】:

您可以使用rejects

 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

【讨论】:

  • 您也可以使用 toStrictEqual 代替 toBe 并将抛出的异常添加为参数。 expect(err).toStrictEqual(Exception);
猜你喜欢
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 2018-06-11
相关资源
最近更新 更多