【问题标题】:Async chai assertion on supertest response对超测响应的异步 chai 断言
【发布时间】:2020-06-06 09:33:10
【问题描述】:

我正在使用 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
    })
})

哪个不起作用并且总是通过,当测试失败时会导致未处理的 Promise 拒绝警告!

【问题讨论】:

    标签: javascript testing bdd chai supertest


    【解决方案1】:

    根据文档,如果 .expect 中的函数无异常返回,则视为已通过断言。

    .expect提供一个异步函数意味着立即返回一个promise,之后抛出也无所谓,所以它会通过。

    解决方案是使用 Superagent 调用的返回值,在 Superagent 的 .expect 之外自己进行额外的断言。类似:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2012-07-16
      • 2018-03-06
      相关资源
      最近更新 更多