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

时间:2014-07-24 02:14:31

标签: javascript coffeescript qunit sinon

我的命名空间中有一个方法我想mock,但我更喜欢所有其他方法正常工作。是否可以让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

我想模仿sourceAttackTarget并验证其参数是否为特定值。

2 个答案:

答案 0 :(得分: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.

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

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

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

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.

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

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.

(更新)

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

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

"模拟具有可能无法通过测试的内置期望。因此,他们执行实施细节。经验法则是:如果您不为某个特定的调用添加断言,请不要嘲笑它。改为使用存根。一般来说,你不应该在一次测试中有多个模拟(可能有几个期望)。" - source

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

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

答案 1 :(得分:0)

从sinon@3.0.0开始,

var stub = sinon.stub(object, "method", func);

已被删除。一个人应该使用:

stub(object, "method").callsFake(func)
stub.callsFake(fakeFunction);
Makes the stub call the provided fakeFunction when invoked.

var myObj = {};
myObj.prop = function propFn() {
    return 'foo';
};

sinon.stub(myObj, 'prop').callsFake(function fakeFn() {
    return 'bar';
});

myObj.prop(); // 'bar'

来源:sinonjs docs

相关问题