本文介绍了jest.fn() 有什么作用,我该如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,如果我有一个组件 Country,它可以在 Utils 功能的帮助下单击按钮获取国家列表

export default class countries extends React.Component {构造函数(道具){超级(道具)this.state = {国家列表:''}}获取列表(){//e.preventDefault();//在这里做一个api调用让列表 = getCountryList();list.then((response)=>{ this.setState({ countryList:response }) });}使成为() {var cListing = "单击按钮加载国家列表";如果(this.state.countryList){让 cList = JSON.parse(this.state.countryList);cListing = cList.RestResponse.result.map((item)=> { return(
  • {item.name}
  • ); });}返回 (<div><button onClick={()=>this.getList()} className=buttonStyle">显示国家列表 </button><ul>{cListing}

    );}}

    使用的Utils函数

    const http = require('http');导出函数 getCountryList() {返回新的承诺(解决 => {让 url = "/country/get/all";http.get({host:'services.groupkt.com',path: url,withCredentials:false}, response => {让数据 = '';response.on('data', _data => data += _data);response.on('end', () => resolve(data));});});}

    我可以在哪里使用 Jest.fn() 或者我如何测试当我点击按钮时调用 getList 函数

    解决方案

    Jest Mock 函数

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

    检查 jest.fn() 的文档

    返回一个新的、未使用的模拟函数.可选地采用模拟实现.

     const mockFn = jest.fn();模拟Fn();期望(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 Country = require('./Countries.jsx');描述('组件',函数(){it('必须在点击按钮时调用 getList', function() {var renderNode = TestUtils.renderIntoDocument();renderNode.prototype.getList = jest.fn()var button = TestUtils.findRenderedDOMComponentWithTag(renderedNode, 'button');TestUtils.Simulate.click(button);期望(renderedNode.prototype.getList).toBeCalled();});});

    Can anyone explain how jest.fn() actually works, with a real world example, as I'm confused on how to use it and where it has to be used.

    For example if I have the component Countries which fetches country List on click of a button with help of the Utils Function

    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 function used

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

    where could i use Jest.fn() or how can i test for getList function is called when i click on the Button

    解决方案

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

    这篇关于jest.fn() 有什么作用,我该如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-13 04:30