簡體   English   中英

開玩笑的期望異常不適用於異步

[英]Jest expect exception not working with async

我正在編寫一個應該捕獲異常的測試

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 說:

收到 function 沒扔

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

您可以使用拒絕

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM