[英]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. 在我的单元测试中,我希望能够创建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.
我目前使用这种手动存根,但如果有办法,我宁愿使用sinon存根。
const func_outer = () => {
return {
func_inner: () => {return mockResponse;}
}
};
Has anyone ever faced this situation. 有没有人遇到过这种情况。 Is there an easy way to solve this issue?
有没有简单的方法来解决这个问题?
From sinon documentation you can check the returns section 从sinon文档中,您可以查看返回部分
stub.returns(obj);
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. 您也可以使用myfunc函数跟随此模式,并将func_outerStub作为参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.