Skip to content

Commit

Permalink
Add support for parsing json response
Browse files Browse the repository at this point in the history
  • Loading branch information
JakeDluhy committed Apr 4, 2017
1 parent fafac97 commit e4ba568
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions fake_xml_http_request.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,12 @@
} catch (e) {
// Unable to parse XML - no biggie
}
} else if(this.responseText && /(application\/json)|(application\/vnd\.api\+json)/.test(type)) {
try {
this.response = JSON.parse(this.responseText);
} catch (e) {
// Unable to parse JSON - no biggie
}
}

if (this.async) {
Expand Down
6 changes: 6 additions & 0 deletions src/fake-xml-http-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,12 @@ var FakeXMLHttpRequestProto = {
} catch (e) {
// Unable to parse XML - no biggie
}
} else if(this.responseText && /(application\/json)|(application\/vnd\.api\+json)/.test(type)) {
try {
this.response = JSON.parse(this.responseText);
} catch (e) {
// Unable to parse JSON - no biggie
}
}

if (this.async) {
Expand Down
11 changes: 11 additions & 0 deletions test/responding_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,17 @@ test("does not parse the body if it's XML and another content type is set", func
equal(xhr.responseXML, undefined);
});

test("parses the body if it's JSON and the json content type is set", function(){
const body = { key: 'value' };
xhr.respond(200, {'Content-Type':'application/json'}, JSON.stringify(body));
equal(xhr.response, body);
});

test("does not parse the JSON body when another content type is set", function() {
xhr.respond(200, {'Content-Type':'application/xml'}, '{"a":"key"}');
equal(xhr.response, undefined);
});

test("calls the onload callback once", function(){
var wasCalled = 0;

Expand Down

0 comments on commit e4ba568

Please sign in to comment.