Unit testing react component that makes ajax calls using JEST

alok mittal picture alok mittal · Jun 24, 2015 · Viewed 10.9k times · Source

I've a react component that makes AJAX call in componentDidMount method. While I try to render it using React.addons.TestUtils, the component gets rendered without making AJAX call. How would I test react component using jest so that it makes AJAX call? Should I need to use phantomJS (or browser like env) as well to provide DOM abilities to react component?

React Component:

return React.createClass({

  componentDidMount : function() {
    $.ajax({
    ... makes http request
    })
  }

  render : function() {
    <div>
      //view logic based on ajax response...
    </div>
  }
});

TestCase:

jest.dontMock(../MyComponent);

var React = require('react/addons');

var TestUtils = React.addons.TestUtils;

var MyComponent = require(../MyComponent);

describe('Sample Test', function(){     

    it('To Render the component', function() {

       var component = <MyComponent />;

       var DOM = TestUtils.renderIntoDocument(component);

       .... // Some other code... 
       });
})

Answer

Michael Parker picture Michael Parker · Jun 24, 2015

I really like Sinon.js and its ability to create a fake server that can respond to ajax requests for testing purposes. You can use it alongside Jest just fine. Here's an example of what it can do for you:

describe('MyComponent', function() {     

    it('successfully makes ajax call and renders correctly', function() {
        //create fake server
        var server = sinon.fakeServer.create();
        //make sure that server accepts POST requests to /testurl
        server.respondWith('POST', '/testurl', 'foo'); //we are supplying 'foo' for the fake response
        //render component into DOM
        var component = <MyComponent />;
        var DOM = TestUtils.renderIntoDocument(component);
        //allow the server to respond to queued ajax requests
        server.respond();
        //expectations go here
        //restore native XHR constructor
        server.restore();
    });

});

I'm not sure how open you are to including another framework in your test suite so feel free to ignore this answer if it does not suit your purposes.