问题
When using supertest
for testing async HTTP requests in JavaScript, what's the difference between these two snippets? Is one of them correct and the other one wrong?
request('http://localhost:8080/').get('/api/people')
.expect(res => res.body.should.have.length(5))
vs.
request('http://localhost:8080/').get('/api/people')
.then(res => res.body.should.have.length(5))
The only differences I could notice were:
expect
returns aTest
object and, when test fails, prints a large stack tracethen
returns aPromise
object and, when test fails, prints a small stack trace
回答1:
Depending on what test runner you're using will obviously affect the answer, but something like Mocha
will allow you to return the Promise
directly in your test and this will wait to be resolved before the test passes.
So if you having something like:
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))
})
})
Whereas in the other instance you really should use a done callback as per https://www.npmjs.com/package/supertest docs.
来源:https://stackoverflow.com/questions/50919242/difference-between-supertests-expect-and-then