diff --git a/README.md b/README.md index cea44c1..e475566 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ xhr.respond(200, {"Content-Type": "application/json"}, '{"key":"value"}'); xhr.status; // 200 xhr.statusText; // "OK" xhr.responseText; // '{"key":"value"}' +xhr.response; // { key: "value" } (parsed JSON object) // simulate failed response xhr = new FakeXMLHttpRequest(); @@ -48,4 +49,4 @@ karma start In order to have a more open and welcoming community this project adheres to a [code of conduct](CONDUCT.md) adapted from the [contributor covenant](http://contributor-covenant.org/). -Please adhere to this code of conduct in any interactions you have with this project's community. If you encounter someone violating these terms, please let a maintainer (@trek) know and we will address it as soon as possible. \ No newline at end of file +Please adhere to this code of conduct in any interactions you have with this project's community. If you encounter someone violating these terms, please let a maintainer (@trek) know and we will address it as soon as possible. diff --git a/fake_xml_http_request.js b/fake_xml_http_request.js index 86b15d2..2fb09c8 100644 --- a/fake_xml_http_request.js +++ b/fake_xml_http_request.js @@ -447,6 +447,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) { + if (!(e instanceof SyntaxError)) throw e; + } } if (this.async) { diff --git a/src/fake-xml-http-request.js b/src/fake-xml-http-request.js index ae46d77..85fdfb7 100644 --- a/src/fake-xml-http-request.js +++ b/src/fake-xml-http-request.js @@ -441,6 +441,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) { + if (!(e instanceof SyntaxError)) throw e; + } } if (this.async) { diff --git a/test/responding_test.js b/test/responding_test.js index 6db50c2..34696fe 100644 --- a/test/responding_test.js +++ b/test/responding_test.js @@ -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)); + deepEqual(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;