Search code examples
unit-testingreactjses6-promisejestjs

What does jest.fn() do and how can I use it?


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 that getList() function is called when I click on the button?


Solution

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