[英]How to unit test arrow functions in JavaScript?
我有这个javascript类:
class SearchService {
/*@ngInject*/
constructor($log, $timeout) {
this._log = $log;
this._timeout = $timeout;
}
startSearch(value, updateCallBack) {
this.startSearchPrj(updateCallBack);
}
startSearchPrj(updateCallBack) {
chunkedRequest({
url: 'http://localhost:9090',
method: 'GET',
chunkParser: (rawChunk, prevChunkSuffix = '') => {
return [JSON.parse(rawChunk), prevChunkSuffix];
},
onChunk: (err, parsedChunk) => {
var data = this.cleanResults(parsedChunk)
if(!this.activeChunkId) {
this.activeChunkId = data.resultCategoryId;
}
this.searchResults[data.resultCategoryId] = data;
updateCallBack();
}
});
}
...
}
export default SearchService;
onChunk
有一个箭头函数,我喜欢用onChunk
编写一个单元测试(因为它将很快变得更加复杂)。 我怎样才能做到这一点?
我试图重构该类,并将代码移到onChunk方法中。 但是, this
还有其他含义,我无法访问对象数据。
对于回调函数,ES.next类属性(当前在阶段1 )是可行的方法:
class SearchService {
onChunk = (err, parsedChunk) => { ... };
...
chunkedRequest({
...
onChunk: this.onChunk
});
...
}
只是ES2015上的语法糖:
class SearchService {
/*@ngInject*/
constructor($log, $timeout) {
this.onChunk = (err, parsedChunk) => { ... }
...
}
...
}
这样,事件处理程序便可以进行测试,而不必为ES5风格的Function.prototype.bind
困扰。
或者,可以将原型方法而不是arrow属性与bind运算符结合使用(当前在阶段0 ):
class SearchService {
onChunk(err, parsedChunk) { ... };
...
chunkedRequest({
...
onChunk: ::this.onChunk
});
...
}
这是加糖的Function.prototype.bind
:
onChunk: this.onChunk.bind(this)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.