谁能解释jest.fn()在实际示例中的实际工作原理,因为我对如何使用它以及必须在何处使用感到困惑。
例如,如果我具有在“实用工具”功能帮助下单击按钮即可获取国家/地区列表的国家/地区组件
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函数的调用
笑话模拟功能
模拟函数也称为“间谍”,因为它们使您可以监视由其他代码间接调用的函数的行为,而不仅仅是测试输出。您可以使用创建模拟函数jest.fn()。
jest.fn()
检查文档以了解 jest.fn()
返回一个新的未使用的模拟函数。(可选)采用模拟实现。
const mockFn = jest.fn(); mockFn(); expect(mockFn).toHaveBeenCalled();
使用模拟实现:
const returnsTrue = jest.fn(() => true); console.log(returnsTrue()) // true;
因此,您可以getList使用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(); }); });