我正在使用Superagent(与Async / Await一起使用诺言,并希望对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
提供一个异步函数意味着立即返回一个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
})