How jest.fn () works

Can anyone explain how jest.fn () really works with an example of the real world, since I was literally confused about how to use it and where it should be used.

For example, if I have a Country component that selects a list of countries at the click of a button using 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 can I use Jest.fn () or how can I test the getList function is called when I click

+6
source share
1 answer

Jest Mock Features

Layout functions are also known as β€œspies,” because they allow you to monitor the behavior of a function that is indirectly called some other code, rather than just testing the output. You can create the mock function with jest.fn() .

jest.fn()

Returns a new unused mock function. Optionally performs a mock implementation.

  const mockFn = jest.fn(); mockFn(); expect(mockFn).toHaveBeenCalled(); 

With mock implementation:

  const returnsTrue = jest.fn(() => true); console.log(returnsTrue()) // true; 

So you can mock getList with 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(); }); }); 
+10
source

Source: https://habr.com/ru/post/1012935/


All Articles