【发布时间】:2017-04-20 22:20:11
【问题描述】:
谁能解释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 函数被调用
【问题讨论】:
标签: unit-testing reactjs es6-promise jestjs