mock方法调用回调函数sinon

Sta*_*ley 7 javascript sinon

你如何模拟使用sinon调用回调的外部方法?给出以下代码的示例,getText应该在回调函数中返回'a string'作为响应

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

它应该产生输出'一个字符串',因为它调用回调函数cb但没有输出

Yur*_*nko 17

您可以使用 callsArgWith

sinon.stub(a, 'getText').callsArgWith(1, null, 'kkk')
let cb = function(err, response) {
   console.log(response)
}
a.getText('abc', cb)
Run Code Online (Sandbox Code Playgroud)


rob*_*lep 14

sinon.stub(a, 'getText').yields(null, 'a string');
Run Code Online (Sandbox Code Playgroud)

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