Skip to content

Commit 848e755

Browse files
committed
Add support for parsing json response
1 parent dfdceb8 commit 848e755

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

fake_xml_http_request.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,12 @@
447447
} catch (e) {
448448
// Unable to parse XML - no biggie
449449
}
450+
} else if(this.responseText && /(application\/json)|(application\/vnd\.api\+json)/.test(type)) {
451+
try {
452+
this.response = JSON.parse(this.responseText);
453+
} catch (e) {
454+
// Unable to parse JSON - no biggie
455+
}
450456
}
451457

452458
if (this.async) {

src/fake-xml-http-request.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,12 @@ var FakeXMLHttpRequestProto = {
441441
} catch (e) {
442442
// Unable to parse XML - no biggie
443443
}
444+
} else if(this.responseText && /(application\/json)|(application\/vnd\.api\+json)/.test(type)) {
445+
try {
446+
this.response = JSON.parse(this.responseText);
447+
} catch (e) {
448+
// Unable to parse JSON - no biggie
449+
}
444450
}
445451

446452
if (this.async) {

test/responding_test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,17 @@ test("does not parse the body if it's XML and another content type is set", func
6161
equal(xhr.responseXML, undefined);
6262
});
6363

64+
test("parses the body if it's JSON and the json content type is set", function(){
65+
const body = { key: 'value' };
66+
xhr.respond(200, {'Content-Type':'application/json'}, JSON.stringify(body));
67+
deepEqual(xhr.response, body);
68+
});
69+
70+
test("does not parse the JSON body when another content type is set", function() {
71+
xhr.respond(200, {'Content-Type':'application/xml'}, '{"a":"key"}');
72+
equal(xhr.response, undefined);
73+
});
74+
6475
test("calls the onload callback once", function(){
6576
var wasCalled = 0;
6677

0 commit comments

Comments
 (0)