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

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


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