I have this javascript class:
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;
There is an arrow function for onChunk
and I like to write a unit test with jasmin for it (since it will get much more complex soon). How can I do this?
I tried to refactor the class and moved the code into an onChunk method. But then this
get's an other meaning and I cannot access the object data.
For callback functions ES.next class properties (currently at stage 1 ) is the way to go:
class SearchService {
onChunk = (err, parsedChunk) => { ... };
...
chunkedRequest({
...
onChunk: this.onChunk
});
...
}
Which are just syntactic sugar over ES2015:
class SearchService {
/*@ngInject*/
constructor($log, $timeout) {
this.onChunk = (err, parsedChunk) => { ... }
...
}
...
}
This way event handlers are exposed for testing and don't have to be encumbered with ES5-styled Function.prototype.bind
.
Alternatively, prototype method instead of arrow property can be used in conjunction with bind operator (currently at stage 0 ):
class SearchService {
onChunk(err, parsedChunk) { ... };
...
chunkedRequest({
...
onChunk: ::this.onChunk
});
...
}
Which is sugared Function.prototype.bind
:
onChunk: this.onChunk.bind(this)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.