Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FakeXMLHttpRequest falsly sets responseXML #1678

Closed
Ninerian opened this issue Jan 26, 2018 · 1 comment
Closed

FakeXMLHttpRequest falsly sets responseXML #1678

Ninerian opened this issue Jan 26, 2018 · 1 comment

Comments

@Ninerian
Copy link

Ninerian commented Jan 26, 2018

  • Sinon version : 4.2.1
  • Environment: Node 9.4.0, Chrome, Firefox, Safari
  • Other libraries you are using: karma, chai, mocha

What did you expect to happen?
When a invalid xml file is loaded with XMLHttpRequest, the responseXML is null.

What actually happens
The FakeXMLHttpRequest fills the responseXML with the parsed xml document with included parseErrors.

How to reproduce

const invalidXMLData = `!!!<?xml version="1.0" encoding="UTF-8"?><start>`;

function testXMLRequest(options) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', options.url, true);

  // If specified, responseType must be empty string or "document"
  xhr.responseType = 'document';

  // overrideMimeType() can be used to force the response to be parsed as XML
  xhr.overrideMimeType('text/xml');

  xhr.onload = function() {
    if (xhr.readyState === xhr.DONE) {
      if (xhr.status === 200) {
        if (xhr.responseXML) {
          options.onSuccess();
        } else {
          options.onErrorCallback();
        }
      }
    }
  };

  xhr.send(null);
}

let xhr, requests, requestor;

before(() => {
  xhr = sinon.useFakeXMLHttpRequest();
  requests = [];
  xhr.onCreate = function(xhr) {
    requests.push(xhr);
  };
});

after(() => {
  xhr.restore();
});

it('Should throw an error, when the xml is invalid', () => {
  let successCallback = sinon.spy();
  let errorCallback = sinon.spy();

  const reqSettings = {
    url: '/xml',
    onSuccess: successCallback,
    onErrorCallback: errorCallback,
  };

  testXMLRequest(reqSettings);

  requests[0].respond(200, { 'Content-Type': 'text/text' }, invalidXMLData);

  expect(successCallback.notCalled, 'Success callback is not called').to.be.true;
  expect(errorCallback.calledOnce, 'Error callback is called').to.be.true;
});

Solution
After parsing the response, you should check for parseerrors and return null.

@mroderick
Copy link
Member

Issue migrated to sinonjs/nise#25

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants