Can anyone explain how jest.fn()
actually works, with a real world example, as I'm confused on how to use it and where it has to be used.
For example if I have the component Countries which fetches country List on click of a button with help of the Utils Function
export default class Countries extends React.Component { constructor(props) { super(props) this.state = { countryList:'' } } getList() { //e.preventDefault(); //do an api call here let list = getCountryList(); list.then((response)=>{ this.setState({ countryList:response }) }); } render() { var cListing = "Click button to load Countries List"; if(this.state.countryList) { let cList = JSON.parse(this.state.countryList); cListing = cList.RestResponse.result.map((item)=> { return(<li key={item.alpha3_code}> {item.name} </li>); }); } return ( <div> <button onClick={()=>this.getList()} className="buttonStyle"> Show Countries List </button> <ul> {cListing} </ul> </div> ); } }
Utils function used
const http = require('http'); export function getCountryList() { return new Promise(resolve => { let url = "/country/get/all"; http.get({host:'services.groupkt.com',path: url,withCredentials:false}, response => { let data = ''; response.on('data', _data => data += _data); response.on('end', () => resolve(data)); }); }); }
Where could I use Jest.fn()
or how can I test for getList
function is called when I click on the button?
jest. fn() is a method to create a stub, it allowing you to track calls, define return values etc... jest. spyOn() came from jasmine, it allow you to convert an existing method on an object into a spy, that also allows you to track calls and re-define the original method implementation.
To create a test case in Jest we use the test() function. It takes a test name string and handler function as the first two arguments. The test() function can also be called under the alias - it() . Choose one over the other depending on readability or personal preference.
Jest Mock Functions
Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than just testing the output. You can create a mock function with jest.fn()
.
Check the documentation for jest.fn()
Returns a new, unused mock function. Optionally takes a mock implementation.
const mockFn = jest.fn(); mockFn(); expect(mockFn).toHaveBeenCalled();
With a mock implementation:
const returnsTrue = jest.fn(() => true); console.log(returnsTrue()) // true;
So you can mock getList
using jest.fn()
as follows:
jest.dontMock('./Countries.jsx'); const React = require('react/addons'); const TestUtils = React.addons.TestUtils; const Countries = require('./Countries.jsx'); describe('Component', function() { it('must call getList on button click', function() { var renderedNode = TestUtils.renderIntoDocument(<Countries />); renderedNode.prototype.getList = jest.fn() var button = TestUtils.findRenderedDOMComponentWithTag(renderedNode, 'button'); TestUtils.Simulate.click(button); expect(renderedNode.prototype.getList).toBeCalled(); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With