【问题标题】:mock method calling callback function sinon模拟方法调用回调函数 sinon
【发布时间】:2017-10-24 04:52:54
【问题描述】:

如何模拟使用 sinon 调用回调的外部方法? 给出以下代码的示例,getText 应在回调函数中返回“字符串”作为响应

sinon.stub(a, 'getText').returns('a string')
let cb = function(err, response) {
   console.log(response)
}
a.getText('abc', cb)

它应该产生输出'a string',因为它调用回调函数cb但没有输出

【问题讨论】:

    标签: javascript sinon


    【解决方案1】:
    sinon.stub(a, 'getText').yields(null, 'a string');
    

    yields() 将使用提供的参数 (null, 'a string') 调用传递给存根函数的第一个函数参数。

    【讨论】:

    • 这就像一个魅力。你是救世主 robertklep。
    【解决方案2】:

    您可以使用callsArgWith

    sinon.stub(a, 'getText').callsArgWith(1, null, 'a string')
    let cb = function(err, response) {
       console.log(response); // 'a string'
    }
    
    a.getText('abc', cb)
    

    【讨论】:

    • 感谢这个工作.. 当我在 callArgWith 下用 1 替换 0 时
    • @Stanley 对,应该是 1
    猜你喜欢
    • 2021-01-23
    • 2019-12-15
    • 1970-01-01
    • 2021-12-17
    • 2021-04-15
    • 2018-06-16
    • 2015-12-18
    • 1970-01-01
    • 2020-07-23
    相关资源
    最近更新 更多