我在我的命名空间中只有一个方法要模拟,但我希望其他所有方法都能正常工作。是否可以让sinon模拟一种特定的方法,而使其他方法保持不变?
我的理解是我不是在寻找间谍,因为我想断言该模拟是使用特定参数调用的。
这是我在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
并验证其参数是否为特定值。
是的,那是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()
,我只是发现了约。对于这类测试,也可能非常有用。
“模拟程序带有内置的期望,它们可能无法通过测试。因此,它们会强制执行实现细节。经验法则是:如果您不为某个特定的调用添加断言,请不要模拟它。使用存根代替通常,在一个测试中,您不应有一个以上的模拟(可能会有多个期望)。” -来源
...因此,对于上述问题,模拟不是正确的选择,而存根是适当的选择。话虽这么说,但是可以通过模拟轻松地测试其中一种情况,这是期望已使用一组特定的参数调用了一种方法。
var mock = sinon.mock(object);
mock.expects("sourceAttackTarget").withArgs(1, "foo", "bar");
object.sourceAttackTarget(gameState, source, target);
mock.verify();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句