簡體   English   中英

超級測試響應的異步柴斷言

[英]Async chai assertion on supertest response

我正在使用 Superagent(與 Async/Await 一起使用 promise),並希望使用 Chai 的 Expect 對響應進行一些額外的斷言。 問題是當響應斷言需要任何異步操作時,我們無法以響應斷言格式執行它,例如:

it('should check for something on response', async () => {
  await superagent(app)
    .expect(200)
    .expect(res => {
      chai.expect(res.body).to.have.property('something')
    })
})

所以向上面添加異步斷言將是這樣的:

it('should check for something async on response', async () => {
  await superagent(app)
    .expect(200)
    .expect(async res => {
      chai.expect(await checkForSmth(res.body)).to.be.true
    })
})

哪個不起作用並且總是通過,並且當測試失敗時,它將導致未處理的承諾拒絕警告!

根據文檔,如果.expect的函數無異常返回,則認為是通過的斷言。

.expect提供異步函數意味着立即返回一個承諾,之后是否拋出也沒有關系,所以它會通過。

解決方案是在 Superagent 的.expect之外自己做額外的斷言,使用 Superagent 調用的返回值。 就像是:

it('should check for something async after getting the response', async () => {
  const res = await superagent(app)
    .expect(200)
  chai.expect(await checkForSmth(res.body)).to.be.true
})

暫無
暫無

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

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