javascript – sinon.js withArgs回调函数

我想在我的服务器端
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( ??? );

最佳答案 您的示例有点令人困惑,因为您已将foo定义为函数,但后面的注释调用foo.method():

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

无论如何,“大型复杂回调函数”只是一个对象. withArgs返回由给定args过滤的间谍对象,您可以使用函数作为该过滤器的一部分.例如:

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

点赞