How does jest.fn() work

NaveenThally picture NaveenThally · Dec 6, 2016 · Viewed 32.9k times · Source

Can anyone explain how does jest.fn() actually work with a real world example , as i'm literally 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

Answer

Yadhu Kiran picture Yadhu Kiran · Dec 6, 2016

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();
  });
});