How does jest.fn() work

后端 未结 1 1523
广开言路
广开言路 2020-12-24 06:29

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

相关标签:
1条回答
  • 2020-12-24 06:49

    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();
      });
    });
    
    0 讨论(0)
提交回复
热议问题