【问题标题】:Sinon stub a function within a functionSinon 存根函数内的函数
【发布时间】:2017-01-16 21:43:22
【问题描述】:

我将在我的工作地点对我们的 JavaScript 文件进行测试。我决定使用 Mocha、Chai 和 Sinon 库来帮助进行测试。我开始为不需要太多重构的函数编写单元测试,然后遇到了一个我不太了解的有趣案例。

function getQueries() {
  code that returns queries in an array -> ['one', 'two', 'three']    
}

function sort(col, type) {
  var queries = getQueries();
  some code that sorts these queries
  return sorted array
}

因为我正在对排序函数进行单元测试,所以我想存根 getQueries() 以返回一个虚拟列表。

var queries = ['one', 'two', 'three'];
sinon.stub(getQueries).returns(queries);

上面的代码没有工作错误消息:

TypeError: Attempted to wrap undefined property undefined as function
at Object.wrapMethod (file://node_modules/sinon/pkg/sinon-1.17.7.js:1359:29)
at Object.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:3459:26)
at F.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:4200:44)
at Context.obj.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:4215:37)
at Context.<anonymous> (unit_tests/unit_test.js:154:10)
at Context.sinonSandboxedTest (file:/node_modules/sinon/pkg/sinon-1.17.7.js:6069:39)

但是,下面的代码确实可以正常工作。

var queries = ['one', 'two', 'three'];
getQueries = sinon.stub();
getQueries.returns(queries); 

我不完全理解为什么这段代码有效,而上面的代码无效。我知道 sinon.stub(obj, method, function) 的语法,但 getQueries 是一个没有对象的函数。非常感谢任何见解。

【问题讨论】:

    标签: javascript unit-testing sinon


    【解决方案1】:

    如果getQueries 似乎不是对象的一部分,它是全局对象window 的一部分,所以sinon.stub(window, 'getQueries', ...) 应该可以解决问题。

    在这种情况下,可以说更好的方法是将 getQueries 的结果传递给排序函数。在您当前的结构中,sort 函数有两个工作:获取列表并对其进行排序。您也许可以将函数命名为 getSortedQueries,但实际的 separation of concerns 更好,您甚至不需要模拟或存根函数,因为您只需将固定列表传递给排序函数。

    【讨论】:

    • 太棒了!我曾尝试使用文档作为我的全局对象,但我猜它的窗口。感谢您的回答。
    猜你喜欢
    • 2020-03-29
    • 2021-01-24
    • 1970-01-01
    • 2016-05-11
    • 2015-02-12
    • 2021-02-20
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多