如何使用Sinon仅模拟一种方法?

Dan*_*lan 4 javascript qunit coffeescript sinon

我在我的命名空间中有一个我想要模拟的方法,但我更希望所有其他方法正常工作.是否可以让sinon嘲笑一种特定的方法,同时让其他方法保持不变?

我的理解是我不是在寻找间谍,因为我想断言用特定的参数调用了mock.

这是我在CoffeeScript中的代码:

root.targeting.handleUnitsAttack = (gameState) ->
  units = gameState.heroes.concat(gameState.badGuys)
  for source in units
    for target in units
      gameState = root.targeting.sourceAttackTarget(gameState, source, target)
  gameState
Run Code Online (Sandbox Code Playgroud)

我想模仿sourceAttackTarget并验证它的参数是特定的值.

bgu*_*uiz 5

是的,这是sinon @ 2最常见的使用案例之一,但我相信你所寻找的既不是模拟也不是间谍,而是存根.

请参阅:https://sinonjs.org/releases/v2.4.1/stubs/

var stub = sinon.stub(object, "foo");
//do your assertions
stub.restore(); //back to normal now.
Run Code Online (Sandbox Code Playgroud)

这将允许您创建替换的默认函数object.foo().

但是,从你的问题来看,它听起来像是一个无操作的存根函数,而不是你想要的,而是想用你自己的自定义函数覆盖它:

var stub = sinon.stub(object, "foo", function customFoo() { /* ... */ });
//do your assertions
stub.restore(); //back to normal now.
Run Code Online (Sandbox Code Playgroud)

HTH!


编辑:

如何存根单个函数:

以下存根 object.sourceAttackTarget()

var stub = sinon.stub(object, "sourceAttackTarget", function sourceAttackTargetCustom(gameState, source, target) {
    //do assertions on gameState, source, and target
    // ...
    return customReturn;
});
//do any further assertions
stub.restore(); //back to normal now.
Run Code Online (Sandbox Code Playgroud)

如何存根函数来测试特定参数

var stub = sinon.stub(object, "sourceAttackTarget");
stub.withArgs(1, "foo", "bar").returns("correctTarget");
stub.returns("wrongTarget");
var output = object.sourceAttackTarget(gameState, source, target);
equal(output, "correctTarget", 'sourceAttackTarget invoked with the right arguments');
//do any further assertions
stub.restore(); //back to normal now.
Run Code Online (Sandbox Code Playgroud)

(更新)

也有.calledWith().calledWithMatch(),我只是发现了约.也可以证明对这些类型的测试非常有用.

如何为对象模拟一个方法:

"模拟具有内置的期望,可能会使您的测试失败.因此,它们会强制执行实现细节.经验法则是:如果您不为某些特定的调用添加断言,请不要嘲笑它.使用存根代替一般来说,在一次测试中,你不应该有一个以上的模拟(可能有几个期望)." - 来源

...所以对于上面提到的问题,模拟不是正确的选择,并且存根是合适的选择.话虽这么说,其中一个场景可以用mock轻松测试,这就是期望用一组特定的参数调用一个方法.

var mock = sinon.mock(object);
mock.expects("sourceAttackTarget").withArgs(1, "foo", "bar");
object.sourceAttackTarget(gameState, source, target);
mock.verify();
Run Code Online (Sandbox Code Playgroud)

  • 答案已经过时了。sinon stub 的正确使用方法变成了`stub(obj, 'meth').callsFake(fn)` (2认同)