I'm trying to test a react component which takes in input and fires off events whenever the value is changed. I pass it a client and a callback to call when the value is changed.
I'm testing this by using mocha and using react's TestUtils. Here is the component :
var React = require('react');
var SearchBar = React.createClass({
handleChange : function(event){
var algoliaClient = this.props.client;
// call algoliaClient.search with event.target.value
// this returns a promise on which .then is called
// with a function which calls the onSearch callback
},
render: function(){
return (
<div className="search-bar">
<input id="search-bar" type="text" onChange={this.handleChange} />
</div>
);
}
});
module.exports = SearchBar;
In order to test this I wrote the following test :
describe('SearchBar', function(){
it('Sets searchResults state variable on input', function(){
require('es6-promise').polyfill()
var React = require('react/addons');
var SearchBar = require('../app/components/SearchBar.js');
var TestUtils = React.addons.TestUtils;
var mockSearchResults = {};
var mockSearch = function(mockData) {
var mockPromise = new Promise(function(resolve, reject){
resolve(mockData);
});
return mockPromise;
};
var mockAlgoliaClient = {
search : mockSearch
};
var mockSetState = function(data){
mockSearchResults = data;
}
// Rendering component into the testdom
var searchBar = TestUtils.renderIntoDocument(
<SearchBar client={ mockAlgoliaClient } onSearch={ mockSetState } />
);
debugger;
var input = TestUtils.findRenderedDOMComponentWithTag(
searchBar, 'input'
);
assert.equal( Object.keys(mockSearchResults).length, 0 );
TestUtils.Simulate.change(input, {target : {value : 's'}});
debugger;
assert.equal( mockSearchResults , {data : 's'});
});
});
At the end of the Simulate.change
call, the value of mockSearchResults
is still the same.
So I figured how to go about testing functionality involving external api calls or any other function calls to be made my using sinon.js.
So for example if I wanted to mock the search call being made
Passing in the
done
callback to theit
method and calling it in the.then
function and using a assertion framework that supports assertions with promises ensures that the tests run smoothly.