From e4ba5682ef3637c741a5d86f7813b9c83e193789 Mon Sep 17 00:00:00 2001 From: Jake Dluhy Date: Mon, 3 Apr 2017 18:54:35 -0700 Subject: [PATCH] Add support for parsing json response --- fake_xml_http_request.js | 6 ++++++ src/fake-xml-http-request.js | 6 ++++++ test/responding_test.js | 11 +++++++++++ 3 files changed, 23 insertions(+) diff --git a/fake_xml_http_request.js b/fake_xml_http_request.js index ac6ce49..e41af0d 100644 --- a/fake_xml_http_request.js +++ b/fake_xml_http_request.js @@ -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) { diff --git a/src/fake-xml-http-request.js b/src/fake-xml-http-request.js index 3c4aed5..3a3090e 100644 --- a/src/fake-xml-http-request.js +++ b/src/fake-xml-http-request.js @@ -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) { diff --git a/test/responding_test.js b/test/responding_test.js index a2f5b5f..8671188 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)); + 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;