谁能用一个现实世界的例子来解释一下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()
函数?
最佳答案
模拟函数也称为“ 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/