gpt4 book ai didi

javascript - Sinon stub 函数内的函数

转载 作者:行者123 更新时间:2023-11-30 11:43:50 26 4
gpt4 key购买 nike

我要在我工作的地方对我们的 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
}

因为我正在对排序函数进行单元测试,所以我想 stub 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 是一个没有对象的函数。非常感谢任何见解。

最佳答案

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

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

关于javascript - Sinon stub 函数内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41685467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com