sinon.js withArgs回调函数

4

我希望在服务器端JavaScript中测试某个函数以某种方式被调用。我正在使用Sinon模拟和存根。Sinon有一个withArgs()方法,可以检查函数是否按照指定参数进行调用。如果我将一个大而复杂的回调函数作为参数之一传递,是否可以使用该方法withArgs()?

var foo = function(){ method: function () {}};
// use: foo.method(function(){ console.log('something') } );
var spy = sinon.spy(foo, 'method');
spy.withArgs( ??? );
1个回答

2

您的示例有点令人困惑,因为您将foo定义为函数,但随后的注释调用了foo.method()

var foo = function(){ method: function () {}};
// use: foo.method(function(){ console.log('something') } );

无论如何,“大型复杂回调函数”只是一个对象。 withArgs 返回一个由给定参数过滤的间谍对象,您可以将函数用作该过滤器的一部分。例如:
var arg1 = function () { /* large, complex function here :) */ };
var arg2 = function() {};
var foo = {
    method: function () {}
};
var spy = sinon.spy(foo, 'method');
foo.method(arg1);
foo.method(arg2);
console.assert(spy.calledTwice);  // passes
console.assert(spy.withArgs(arg1).calledOnce); // passes
console.assert(spy.withArgs(arg1).calledWith(arg1));  // passes
console.assert(spy.withArgs(arg1).calledWith(arg2));  // fails, as expected

JSFiddle


看,我更倾向于在测试中不使用复杂的函数。 - Victor Pudeyev
你能使用间谍或存根(Spy或Stub)吗? - psquared
JavaScript 是一种动态语言,我目前的做法是通过存根来实现。不使用 sinon.js 或任何其他框架 - 我只需重写复杂的回调以执行最小功能并设置一些内部测试标志。因此,我的当前解决方案不依赖于 sinon.js。 - Victor Pudeyev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接