unit-testing - jest.fn() 有什么作用以及如何使用它?

标签 unit-testing reactjs es6-promise jestjs

谁能用一个现实世界的例子来解释一下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()函数?

最佳答案

Jest Mock Functions

模拟函数也称为“ spy ”,因为它们可以让您监视由其他代码间接调用的函数的行为,而不仅仅是测试输出。您可以使用 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();
  });
});

关于unit-testing - jest.fn() 有什么作用以及如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40992628/

相关文章:

javascript - 测试捕获 Promise 错误

javascript - 来自 API 的 Promise.all 拒绝

android - 单元测试: Observer onChanged should be called twice instead of once

java - 如何初始化 JAX-RS HttpHeader

reactjs - Recharts ScatterChart 未在 XAxis 中渲染点和重复值

javascript - 如果错误源较多,则拒绝 Promise

Javascript 单元测试框架

java - Mockito 单元测试用例调用不明确(需要使其不明确)

css - 无法在 React Js 元素中使用 Font Awesome

javascript - 如何在删除组件(自定义html元素)时使动态文本在react中显示正确的句子