【问题标题】:Verifying function call and inspecting arguments using sinon spies使用 sinon 间谍验证函数调用和检查参数
【发布时间】:2015-06-30 07:09:06
【问题描述】:

我想通过我的单元测试验证 bar() 是否在 foo() 内部被调用。

我认为Sinon spies 可能合适,但我不知道如何使用它们。

有什么方法可以检查方法是否被调用?甚至可以提取bar() 调用中使用的参数?

var spy = sinon.spy(foo);

function foo(){
    bar(1,2,3);
}

function bar(){ }

foo();

// what to do with the spy?

http://jsfiddle.net/8by9jg07/

【问题讨论】:

    标签: javascript unit-testing sinon


    【解决方案1】:

    你不应该监视 bar 而不是 foo 吗?

    var spy = sinon.spy(bar)
    

    调用 foo:

    foo()
    

    检查栏被调用:

    console.log(spy.calledOnce)
    

    【讨论】:

    【解决方案2】:

    在您的情况下,您正在尝试查看是否调用了 bar,因此您想要监视 bar 而不是 foo

    doc中所述:

    function bar(x,y) {
      console.debug(x, y);
    }
    function foo(z) {
      bar(z, z+1);
    }
    // Spy on the function "bar" of the global object.
    var spy = sinon.spy(window, "bar");
    
    // Now, the "bar" function has been replaced by a "Spy" object
    // (so this is not necessarily what you want to do) 
    
    foo(1);
    
    bar.getCall(0).args => should be [1,2]
    

    现在,监视函数的内部结构将您对“foo”的测试与其实现紧密结合,因此您将陷入通常的"mockist vs classical" 辩论。

    【讨论】:

    • 根据the doc 应该是getCall(0) 而不是getCalls(0)
    • 最后你可以像这样轻松地断言调用参数:expect(window.bar.getCall(0).args).deep.equal([1, 2]);
    【解决方案3】:

    我同意 Adrian 的说法,即您可能想监视酒吧。

    var barSpy = sinon.spy(bar);
    

    然后检查它是否被调用过一次

    assert(barSpy.calledOnce);
    

    刚刚调用

    assert(barSpy.called)
    

    调用 x 次

    assert.equal(barSpy.callCount, x);
    

    如果你想从spy的第一次调用中提取参数:

    var args = barSpy.getCalls()[0].args
    

    然后你可以用这些参数做你想做的事。

    【讨论】:

    猜你喜欢
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2017-07-06
    • 1970-01-01
    • 2017-06-29
    • 2021-04-05
    • 2017-02-22
    相关资源
    最近更新 更多