首页 > 解决方案 > supertest的expect和then的区别?

问题描述

supertestJavaScript 中用于测试异步 HTTP 请求时,这两个片段有什么区别?其中一个是正确的,另一个是错误的吗?

request('http://localhost:8080/').get('/api/people') .expect(res => res.body.should.have.length(5))

对比

request('http://localhost:8080/').get('/api/people') .then(res => res.body.should.have.length(5))

我能注意到的唯一区别是:

标签: javascriptautomated-testses6-promisesupertest

解决方案


取决于您使用的测试运行器显然会影响答案,但类似的东西Mocha将允许您Promise直接在测试中返回,这将在测试通过之前等待解决。

所以如果你有类似的东西:

describe('Your test case', function () {

  it('will wait for promise to resolve', function () {
    return request('http://localhost:8080/').get('/api/people')
      .then(res => res.body.should.have.length(5))
  })

})

而在另一种情况下,您确实应该按照https://www.npmjs.com/package/supertest文档使用 done 回调。


推荐阅读