Search code examples
javascriptsinon

mock method calling callback function sinon


How do you mock an outer method calling a callback using sinon? Example given the following code, getText should return 'a string' as response in the callback function

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

and it should produce the output 'a string' since it calls callback function cb but there is no output


Solution

  • You can use callsArgWith

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