Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? https://github.com/danvk/mocha-react/blob/jsx-stubs/BigComplicatedComponent.js Or am I incorrectly trying to override it.

like image 432
timhc22 Avatar asked Aug 05 '26 14:08

timhc22


1 Answers

Finally got this working. Added this to the top. I'd imagine it should work with overriding any class.

var FakeXMLHTTPRequests = require('fakexmlhttprequest')
var requests   = []

XMLHttpRequest = function() {
    var r =  new FakeXMLHTTPRequests(arguments)
    requests.push(r)
    return r
}

Thanks to this article for helping me to think this through. http://www.asbjornenge.com/wwc/testing_react_components.html

Can also so this for if using XMLHttpRequest: correct usage of sinon's fake XMLHttpRequest

like image 154
timhc22 Avatar answered Aug 07 '26 03:08

timhc22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!