最后,我编写了自己的一小部分帮助函数来包装 SuperAgent。现在测试代码(CoffeeScript 和 Jasmine)看起来像:
describe "A suite", ->
resource = null
it "and a spec", (done) ->
expectResponse(request.get "/path/to/resource")
.ok()
.json()
.andDo (response) -> resource = response.body
.end(done)
一个助手类看起来像这样
class ExpectResponseWrapper
constructor: (req) ->
@req = req
@expectations = []
end: (done) ->
@req.end (err, res) =>
if (err)
expect( -> throw err).not.toThrow()
else
for exp in @expectations
exp(res)
done?()
ok: ->
@expectations.push (res) ->
expect(res.statusType).toEqual(2)
this
json: ->
@expectations.push (res) ->
expect(res.type).toEqual('application/json')
this
andDo: (fn) ->
@expectations.push fn
this
# ... and the list of other helper expectations goes on ...
expectResponse = (req) -> new ExpectResponseWrapper(req)