vendredi 27 novembre 2015

React testing Fake XMLHttpRequest

I am writing some test code for someone's application. I am new to writing tests specifically for React.

In one of the methods inside the component, a new XMLHttpRequest object is instantiated and then used like so:

var myModal = React.createClass({
  postRequest: function(data) {
    var json = JSON.stringify(data)
    var request = new XMLHttpRequest()

    request.open('POST', '/my/endpoint', true)
    request.setRequestHeader('Content-Type', 'application/json')
    request.send(json)
  }

  //...
}

I am using Sinon, and their documentation says there is a Fake XMLHttpRequest which can be used for testing AJAX requests. I am trying to understand how exactly to override this newly instantiated object with the Sinon one, so that the tests uses it to make api calls.

If I try and assign the fake to the request variable:

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

the test still falls over when it reaches the component's new XMLHttpRequest() line. Should I just be creating and importing a stub object instead like here? http://ift.tt/1NzaQbM Or am I incorrectly trying to override it.

Aucun commentaire:

Enregistrer un commentaire