【问题标题】:sinon.js withArgs callback functionsinon.js withArgs 回调函数
【发布时间】:2014-06-18 11:47:26
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js tdd stub sinon


    【解决方案1】:

    您的示例有点令人困惑,因为您已将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

    【讨论】:

    • 看,我宁愿不要在测试中使用复杂的功能。
    • 你可以使用间谍或存根代替吗?
    • JavaScript,是动态的,我目前采用的方式是存根。不使用 sinon.js 或任何其他框架——我只是重写复杂的回调来完成最小的功能并设置一些内部测试标志。所以,我目前的解决方案是在 sinon.js 之外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2018-12-01
    • 1970-01-01
    • 2013-01-07
    • 2013-09-17
    • 2015-07-01
    • 2013-03-21
    相关资源
    最近更新 更多