簡體   English   中英

Jest/SuperTest 如何在一組承諾中正確預期 Socket Hangup?

[英]Jest/SuperTest how to correctly expect Socket Hangup across a set of promises?

我有一個測試,上面寫着“在大約 X 個並發連接之后,我應該看到套接字掛斷,因為我的服務將停止回答有人錘我。”

經過大量痛苦的試驗和錯誤后,這工作得很好,但是因為我第一次看到掛斷時使用的是await Promise.all(myrequests) ,它會引發socket hang up異常。

這可行,但會導致一些錯誤消息,因為我的掛機例程會進行一些調試日志記錄,此時測試已經結束。

最好的說法是:“等待所有這些,即使它們拋出錯誤?”

我的笑話/超級測試問題塊看起來像:

 //Send enough concurrent connections to trip the dropout
 for(var i = 0;MAX_CONCURRENT_CONNECTIONS+5;i++) 
    {
       requests.push(request(app).get('/'))   
    }
    //wait for all the connections to resolve    
    const t = async () => {          
       await Promise.all(requests);                    
    };
    //and make sure some drop off
    expect(t).toThrow("socket hang up"); //this also doesn't match the error string right but that is because I'm not as experienced in this sort of thing as I'd like!

    //however after this, the test ends, and my back end logging causes problems since the test is over!

即使拋出await Promise.all(requests) ,仍然等待請求中所有承諾的最佳方法是什么?

我可以做以下丑陋的代碼,但我正在尋找正確的方法來寫這個:)

        let gotConnReset = false
        try
        {
           await Promise.all(requests);                                    
        }
        catch(err)
        {
            if(err.message == "socket hang up")
            {
                gotConnReset = true;
            }            
        }
        assert(gotConnReset === true);
        //wait for all the other requests so that Jest doesn't yell at us!
        await Promise.allSettled(requests); 

我不知道 Jest 有什么可以幫助的,但有Promise.allSettled將等待所有承諾履行或拒絕,返回所有結果的數組。 被拒絕的承諾將附加一個.reason

主要區別在於 Jest 將匹配錯誤對象而不是使用拋出的錯誤匹配器,因此某些特定於錯誤的功能不存在。

test('allSettled rejects', async () => {
  class Wat extends Error {}
  const resError = new Wat('Nope')
  resError.code = 'NO'
  const res = await Promise.allSettled([
    Promise.resolve(1),
    Promise.reject(resError),
    Promise.resolve(3),
  ])
  expect(res).toEqual(
    expect.arrayContaining([
      { status: 'rejected', reason: new Error('Nope') },
    ])
  )
})
  ✓ allSettled rejects (2 ms)

如果您想避免上面示例的“松散”匹配,如果message匹配,則通過任何Error object,它可能需要類似jest-matcher-specific-errorexpect.extend錯誤匹配器

結果可以使用filter / map或直接reduce到測試拒絕。

(await Promise.allSettled())
  .filter(o => o.status === 'rejected')
  .map(o => o.reason)`

暫無
暫無

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

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