如何在SinonJS中的模拟方法上存根返回值

jos*_*iah 5 javascript asynchronous callback node.js sinon

我想做如下事情:

sinon.mock(obj)
.expects('func')
.atLeast(1)
.withArgs(args)
.returns(somePredefinedReturnValue);
Run Code Online (Sandbox Code Playgroud)

我期望所有内容都包括 withArgs,但随后我需要存根该方法的返回值,以便在它返回时不会中断被测方法中的其余执行流程。

我这样做的原因是因为我发现我的一些 REST 端点测试将在它们应该真正失败时默默地通过,如果没有调用内部有断言的带有回调的存根方法。我正在尝试验证这些回调实际上是否被调用,以便我的测试不会给出误报。

Zab*_*iAG 5

在官方文档中 http://sinonjs.org/docs/#stubs

var stub = sinon.stub(object, "method", func);
Run Code Online (Sandbox Code Playgroud)

您可以传递一个返回所需值的函数参数。

编辑:

这已从 v3.0.0 中删除。相反,你应该使用

stub(obj, 'meth').callsFake(fn)
Run Code Online (Sandbox Code Playgroud)

  • 这个答案有点过时了,因为`v3.0.0`你应该使用 _callsFake_ 来这样做,比如:`var stub = sinon.stub(object, "method").callsFake(func);`参考[这里](http: //sinonjs.org/releases/v6.1.4/stubs/#var-stub--sinonstubobject-method-func)。 (8认同)