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...
});
})
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:
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.