From dc12823a1462a95bac76901ec67401cce9e39358 Mon Sep 17 00:00:00 2001 From: Alex J Burke Date: Wed, 24 Jun 2015 10:48:56 +0200 Subject: [PATCH] Allow all formulations of application/json content type. --- lib/BeanBag.js | 6 +++++- test/BeanBag.js | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/lib/BeanBag.js b/lib/BeanBag.js index 327c69e..e85afeb 100644 --- a/lib/BeanBag.js +++ b/lib/BeanBag.js @@ -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())); @@ -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) { diff --git a/test/BeanBag.js b/test/BeanBag.js index 0a0e37c..a413323 100644 --- a/test/BeanBag.js +++ b/test/BeanBag.js @@ -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); + } })); }); }) @@ -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 () {