Skip to content

Commit

Permalink
Parse JSON responses even when the content-type includes a charset.
Browse files Browse the repository at this point in the history
  • Loading branch information
rgrove committed Mar 10, 2011
1 parent 2b93b93 commit e8031d4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/http.js
Expand Up @@ -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);
Expand Down
26 changes: 25 additions & 1 deletion test.js
Expand Up @@ -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' };
Expand All @@ -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' : {
Expand Down

0 comments on commit e8031d4

Please sign in to comment.