jest.fn()如何工作 [英] How does jest.fn() work
问题描述
任何人都可以解释jest.fn()在实际示例中的实际工作方式,因为我对如何使用它以及必须在何处使用感到困惑.
Can anyone explain how does jest.fn() actually work with a real world example , as i'm literally 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>
);
}
}
使用的实用程序功能
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函数的调用
where could i use Jest.fn() or how can i test for getList function is called when i click on the Button
推荐答案
模拟功能也被称为间谍",因为它们使您可以监视被其他代码间接调用的功能的行为,而不仅仅是测试输出.您可以使用jest.fn()
创建模拟函数.
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()
.
返回一个新的未使用的模拟函数. (可选)采用模拟实现.
Returns a new, unused mock function. Optionally takes a mock implementation.
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
通过模拟实现:
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()) // true;
因此,您可以使用jest.fn()
来模拟getList
,如下所示:
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()如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!