jest.fn() 有什么作用,我该如何使用它?

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

任何人都可以用一个真实世界的例子来解释 jest.fn() 实际上是如何工作的,因为我对如何使用它以及必须在哪里使用它感到困惑。

例如,如果我有组件 Countries,它在 Utils 函数的帮助下通过单击按钮获取国家/地区列表

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 函数

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

我可以在哪里使用 jest.fn() 或如何测试单击按钮时调用 getList() 函数?

Jest Mock Functions

模拟函数也称为“间谍”,因为它们让您可以监视由其他代码间接调用的函数的行为,而不仅仅是测试输出。您可以使用 jest.fn().

创建模拟函数

Check the documentation for jest.fn()

Returns 一个新的、未使用的模拟函数。可选择采用模拟实现。

  const mockFn = jest.fn();
  mockFn();
  expect(mockFn).toHaveBeenCalled();

使用模拟实现:

  const returnsTrue = jest.fn(() => true);
  console.log(returnsTrue()) // true;

因此您可以使用 jest.fn() 模拟 getList,如下所示:

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