Overriding function with Sinon.mock?

17.2k Views Asked by At

The document says

var expectation = mock.expects("method"); Overrides obj.method with a mock function and returns it. See expectations below.

What's the syntax for that?

I tried

var mock = sandbox.mock(myObj).expects(myObj, "myfunc", function(){
                console.log('please!!!')
            }).once();

and

    var mock = sandbox.mock(myObj).expects("myfunc", function(){
                console.log('please!!!')
            }).once();

But neither of them work.

1

There are 1 best solutions below

4
On

Nitpick: you named your variable mock, but expects() returns an expectation.

In any case, Sinon documentation says that mock() takes a single argument and returns a mock object. expects() returns an expectation, which is both a spy and a stub, so you could do something like this:

var mock = sinon.mock(myObj).expects('myfunc').returns('something');

If you wanted to replace myObj.myfunc with a custom function, you could use a stub, perhaps like this:

var stub = sinon.stub(myObj, 'myfunc', function() {
    console.log('something');
});

For Sinon version >= 3.0.0

var stub = sinon.stub(myObj, 'myfunc')
stub.callsFake(() => { 
  console.log('here')
  return Promise.resolve(1)
})