【问题标题】:How to unit test arrow functions in JavaScript?如何在 JavaScript 中对箭头函数进行单元测试?
【发布时间】:2016-09-04 02:32:40
【问题描述】:

我有这个 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 有一个箭头函数,我喜欢用 jasmin 为它编写一个单元测试(因为它很快就会变得更加复杂)。我该怎么做?

我尝试重构类并将代码移动到 onChunk 方法中。但是this 得到了另一个含义,我无法访问对象数据。

【问题讨论】:

  • 显而易见的答案是将其拆分为自己的函数(不是公共函数)并执行onChunk: (err, parsedChunk) => onChunk.call(this, err, parsedChunk) 或干脆onChunk: onChunk.bind(this),但希望有比这更好的答案!
  • 您在进行单元测试时遇到什么问题?如果您可以显示单元测试代码,它可能会提供更有用的答案。
  • 与单元测试任何其他功能的方式相同?

标签: javascript unit-testing jasmine ecmascript-6


【解决方案1】:

对于回调函数 ES.next 类属性(目前在stage 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 的阻碍。

或者,原型方法而不是箭头属性可以与绑定运算符一起使用(目前在stage 0):

class SearchService {
    onChunk(err, parsedChunk) { ... };
    ...
        chunkedRequest({
            ...
            onChunk: ::this.onChunk
        });    
    ...
}

这是加糖的Function.prototype.bind:

            onChunk: this.onChunk.bind(this)

【讨论】:

  • "对于回调函数 ES7 类属性(当前处于阶段 1)" 如果是阶段 1,那么它不是 ES7 (ES2016) ;) E2016 已经“关闭”(没有将添加新功能)。
  • @FelixKling 这是造成混乱的 ES6 == ES2015 相等性。 ES7不等于 ES2016。 ES2016 是公认的标准。 ES7(ECMAScript 7,又名 ES Next)是 WIP,也是一个口语术语,表示不属于任何标准的 ES 功能。
  • 我从未见过委员会中的任何人使用这个词。当我询问他们将什么用于进行中的功能时,他们说“ES next”:twitter.com/fkling42/status/702905807583596544。既然你说这很容易混淆,为什么不避免它;)
  • @FelixKling 感谢您的澄清,很高兴知道他们再次使用“下一个”东西
  • 仅供参考,我现在很好奇其他人的想法并创建了一个 Twitter 民意调查:twitter.com/fkling42/status/729700943164399616。不确定它会得到多少分布,但我们会看到:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 2021-05-21
  • 1970-01-01
  • 2014-02-08
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多