From e8031d4c16e2e4fbb1b4ca962b2dfbba4295f37f Mon Sep 17 00:00:00 2001 From: Ryan Grove Date: Wed, 9 Mar 2011 21:59:45 -0800 Subject: [PATCH] Parse JSON responses even when the content-type includes a charset. --- lib/http.js | 2 +- test.js | 26 +++++++++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/http.js b/lib/http.js index ba39287..2fdcca4 100644 --- a/lib/http.js +++ b/lib/http.js @@ -18,7 +18,7 @@ function responseEventForRequest (req) { data += chunk; }); response.on("end", function () { - if (response.headers["content-type"] === "application/json") { + if (/^application\/json\s*(?:;|$)/.test(response.headers["content-type"])) { data = JSON.parse(data); } event.emit("response", response, data); diff --git a/test.js b/test.js index ef1d562..aef1af3 100644 --- a/test.js +++ b/test.js @@ -16,7 +16,7 @@ function mockServer(cb, port) { pact.httpify(http.createServer(function(req, res) { cb(req, res, port); }), port).apply(this); - } + }; } var headers = { 'Content-Type' : 'text/plain' }; @@ -40,6 +40,30 @@ vows.describe('Pact').addBatch({ 'contains valid data' : function(topic) { assert.strictEqual(topic.body, 'ok!'); } + }, + }, + 'A JSON API' : { + topic: mockServer(function(req, res) { + if (req.url === '/') { + res.writeHead(200, {'Content-Type': 'application/json'}); + } else if (req.url == '/with-charset') { + res.writeHead(200, {'Content-Type': 'application/json;charset=utf-8'}); + } + res.end('{"foo": "bar"}'); + }), + 'when / is requested' : { + topic: pact.request(), + 'contains a parsed JSON response object' : function(topic) { + assert.isObject(topic.body); + assert.strictEqual(topic.body.foo, 'bar'); + } + }, + 'when /with-charset is requested' : { + topic: pact.request(), + 'contains a parsed JSON response object' : function(topic) { + assert.isObject(topic.body); + assert.strictEqual(topic.body.foo, 'bar'); + } } }, 'A 302 redirecting server with a relative path' : {