Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 905
Stanley Avatar asked May 24 '17 03:05

Stanley


People also ask

How do you mock a function in Sinon?

Mocks allow you to create a fake function that passes or fails depending on your needs. You can ensure it was called with certain arguments, or check how many times it was called. You must call mock() on an object.

When to use sinon mock?

When to use mocks? Mocks should only be used for the method under test. In every unit test, there should be one unit under test. If you want to control how your unit is being used and like stating expectations upfront (as opposed to asserting after the fact), use a mock.


1 Answers

sinon.stub(a, 'getText').yields(null, 'a string');

yields() will call the first function argument that gets passed to the stubbed function with the arguments provided (null, 'a string').

like image 70
robertklep Avatar answered Sep 18 '22 11:09

robertklep