【问题标题】:What does jest.fn() do and how can I use it?jest.fn() 做什么以及如何使用它?
【发布时间】:2017-04-20 22:20:11
【问题描述】:

谁能解释jest.fn() 的实际工作原理,并举一个真实世界的例子,因为我对如何使用它以及必须在哪里使用它感到困惑。

例如,如果我有组件国家,它在 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 函数被调用

【问题讨论】:

    标签: unit-testing reactjs es6-promise jestjs


    【解决方案1】:

    Jest Mock Functions

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

    Check the documentation for jest.fn()

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

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

    【讨论】:

    • 例如,如果我有如下函数 function abc() { def() } function def(){ return "call by abc" } 在这种情况下我该如何使用 mock
    • 这是const mockFn = jest.fn(() =&gt; {});const mockFn = jest.fn();一样吗?
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2012-04-26
    • 2013-07-28
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2011-12-16
    相关资源
    最近更新 更多