Skip to content

Commit 0b035df

Browse files
committed
Add support for parsing json response
1 parent fafac97 commit 0b035df

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
@@ -439,6 +439,12 @@
439439
} catch (e) {
440440
// Unable to parse XML - no biggie
441441
}
442+
} else if(this.responseText && /(application\/json)|(application\/vnd\.api\+json)/.test(type)) {
443+
try {
444+
this.response = JSON.parse(this.responseText);
445+
} catch (e) {
446+
// Unable to parse JSON - no biggie
447+
}
442448
}
443449

444450
if (this.async) {

src/fake-xml-http-request.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,12 @@ var FakeXMLHttpRequestProto = {
433433
} catch (e) {
434434
// Unable to parse XML - no biggie
435435
}
436+
} else if(this.responseText && /(application\/json)|(application\/vnd\.api\+json)/.test(type)) {
437+
try {
438+
this.response = JSON.parse(this.responseText);
439+
} catch (e) {
440+
// Unable to parse JSON - no biggie
441+
}
436442
}
437443

438444
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)