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

57

有人可以用实际例子解释一下 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>
    );

  }
}

使用的实用函数

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() 函数?

2个回答

56

Jest Mock 函数

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

查看 jest.fn() 的文档

返回一个新的、未使用过的 Mock 函数。可选地使用一个 Mock 实现。

  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 "called by abc" }在这种情况下,我该如何使用模拟? - NaveenThally
1
这个 const mockFn = jest.fn(() => {});const mockFn = jest.fn(); 是一样的吗? - Hyfy
根据源代码(https://github.com/facebook/jest/blob/main/packages/jest-mock/src/index.ts#L1109),从实际应用角度来看,是的。因此,通过将零个参数传递给 fn,它将默认为 undefined,构造函数将接收一个长度为零的值,并且返回值始终为 undefined,这与使用箭头函数获得的效果相同。 - nascente_diskreta

0
Jest库提供了jest.fn()函数,用于创建一个“模拟”函数。
可以通过传递一个可选的实现函数给jest.fn()来定义模拟函数的行为和返回值。
const mockFunc = jest.fn(() => {
  return "hello testing"
})

test("check return value of mock function", () => {
  expect(mockFunc()).toBe("hello testing")
})

mock函数的行为可以通过提供给mock函数的各种方法来进一步指定,例如.mockReturnValueOnce()。refer
const mockFunc = jest.fn(() => {
  return "hello testing"
})

mockFunc.mockReturnValueOnce("goodbye")

test("check return value of mock function when called once", () => {
  expect(mockFunc()).toBe("goodbye")
})

test("check return value of mock function after called once", () => {
  expect(mockFunc()).toBe("hello testing")
})

可以使用expect() API来验证模拟函数的使用情况(如何调用、返回值等)。
expect(mockFunc).toHaveBeenCalledTimes(2);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接