How does jest.fn() work

时光怂恿深爱的人放手 提交于 2019-11-30 04:47:14
Yadhu Kiran

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();
  });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!