admin管理员组

文章数量:1277523

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?

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?

Share Improve this question asked Mar 24, 2016 at 10:52 ralzaulralzaul 4,4706 gold badges36 silver badges51 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

本文标签: javascriptStubbing nested function calls in sinonStack Overflow