I'm trying out the chai-http plugin for Mocha/Chai. Which wraps around Superagent. Everything seems to work well, except I'm wondering...
Shouldn't I be able to make the http call once and write separate tests for each? The tests seem to expect you to write your assertion inside the response function like so:
describe "github test", ->
it "should connect with a 200 status", ->
chai.request(githubReqObj.base)
.get(githubReqObj.url)
.req (req) ->
req.set
'Accept': 'application/vnd.github.beta+json'
return
.res (res) ->
expect(res).to.have.status 200
But I want to run several assertions, and have each of them under their own "it" block.
Is there a way to run
before ->
And then just call my assertions on the value of response?
Yep, like this:
describe("github test", function () {
var res;
before(function (done) {
chai.request(...)
.get(..)
.req(...)
.res(function (response) {
res = response; // Record the response for the tests.
done(); // Tell mocha that the ``before`` callback is done.
});
});
it("should connect with a 200 status", function () {
expect(res).to.have.status(200);
});
it("should whaterver", function () {
expect(res).whatever;
});
});
I notice you did not use the done
callback in your example. It's really important to use it for asynchronous tests. In the code I show above, the before
callback is asynchronous but the tests themselves are synchronous.