I do it the same way:
var supertest = require("supertest"); var should = require("should"); var util = require('util'); describe("My test",function(){ var response; it("should validate the API key",function(done){ server .post("/validate") .set('authorization', apiKey) .expect("Content-type",/json/) .expect(200) .end(function(err,res){ response = res; res.status.should.equal(200); res.body.error.should.equal(false); done(); }); }); afterEach(function(){ if (this.currentTest.state == 'failed') { console.log(" Response body: " + util.inspect(response.body,{depth: null, colors: true}) + "\n"); } }) });
I highlighted the response variable in my test area, and each test sets it to the given response ( response = res; ). I have to do this once in each test, but then I do not need to worry when and where it fails. Previously, I had to be careful, because if the test failed, some code under it would not be executed, so it would not even reach the print statement. This way I save what I need, regardless of the result.
Then after each test, this afterEach event will start and check if the test passed or failed.
afterEach(function(){ if (this.currentTest.state == 'failed') { console.log(" Response body: " + util.inspect(response.body,{depth: null, colors: true}) + "\n"); } })
This provides a consistent printing method for each test. This is just 1 line for all tests, so itβs easy to change the format or turn it off, and I donβt need to worry about where the test failed, I just care about the end result. It seems to me the best and easiest approach, of all the lazy approaches. Even the JSON output is beautifully and colorfully displayed. There is probably a better way to handle this, but this is a good lazy approach.
source share