Skip to content

Commit

Permalink
Allow all formulations of application/json content type.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexjeffburke committed Jun 24, 2015
1 parent 3050b2d commit dc12823
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
6 changes: 5 additions & 1 deletion lib/BeanBag.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ function addQueryStringToUrl(url, query) {
return url;
}

function isContentTypeJson(contentType) {
return /^application\/json\b|\+json\b/i.test(contentType);
}

function resolveCertKeyOrCa(value) {
if (typeof value === 'string') {
return fs.readFileSync(value.replace(/\{hostname\}/g, os.hostname()));
Expand Down Expand Up @@ -364,7 +368,7 @@ _.extend(BeanBag.prototype, {
currentRequest = null;
if (responseBodyChunks.length > 0) {
response.body = Buffer.concat(responseBodyChunks);
if (response.headers['content-type'] === 'application/json') {
if (isContentTypeJson(response.headers['content-type'])) {
try {
response.body = JSON.parse(response.body.toString('utf-8'));
} catch (e) {
Expand Down
36 changes: 34 additions & 2 deletions test/BeanBag.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@ var BeanBag = require('../lib/BeanBag'),
describe('BeanBag', function () {
var expect = unexpected.clone()
.installPlugin(require('unexpected-mitm'))
.addAssertion('to call the callback with no error', function (expect, subject) {
.addAssertion('to call the callback with no error', function (expect, subject, assertFn) {
this.errorMode = 'nested';
return expect.promise(function (run) {
subject(run(function (err) {
subject(run(function (err, response, body) {
if (err) {
throw err;
}

if (assertFn) {
assertFn(response, body);
}
}));
});
})
Expand Down Expand Up @@ -196,6 +200,34 @@ describe('BeanBag', function () {
}, 'to call the callback with no error');
});

it('should allow any valid formulation of application/json', function () {
var responseObject = {
foo: 'bar'
};
var responseStream = new stream.Readable();
responseStream._read = function () {
responseStream.push(new Buffer(JSON.stringify(responseObject)));
responseStream.push(null);
};

return expect(function (cb) {
new BeanBag({ url: 'http://localhost:5984/' }).request({ method: 'GET', path: 'foo' }, cb);
}, 'with http mocked out', {
request: {
url: 'GET http://localhost:5984/foo'
},
response: {
statusCode: 200,
headers: {
'Content-Type': 'application/json; charset=utf8'
},
body: responseStream
}
}, 'to call the callback with no error', function (response, body) {
expect(body, 'to equal', responseObject);
});
});

it('should throw an error on invalid JSON', function () {
var responseStream = new stream.Readable();
responseStream._read = function () {
Expand Down

0 comments on commit dc12823

Please sign in to comment.