Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing nested function calls in sinon

There are three seperate questions that are similar to this one but none of them resembles the case I have.

So I basically have a function which takes a function as a parameter

var myfunc ( func_outer ) {
    return func_outer().func_inner();
}

In my unit tests I want to be able to make a stub of a myfunc2. Basically I need to be able to stub a stub which is a nested stub. I currently use this kind of a manual stub but I would rather do it using sinon stubs if there is a way.

const func_outer = () => {
    return {
       func_inner: () => {return mockResponse;}
    }
};

Has anyone ever faced this situation. Is there an easy way to solve this issue?

like image 278
ralzaul Avatar asked Mar 24 '16 10:03

ralzaul


1 Answers

From sinon documentation you can check the returns section

stub.returns(obj);
Makes the stub return the provided value.

You can try the following:

First you should make sure that you stub your inner function, and then make it return the value you want.

func_innerStub = sinon.stub().returns('mockResponse')  

Then stub your outer function and make it return the object with your stubbed inner function.

func_outerStub = sinon.stub().returns({func_inner: func_innerStub})

You can follow this pattern with the myfunc function, as well and pass as a param the func_outerStub.

like image 152
Bettina Avatar answered Nov 15 '22 15:11

Bettina