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

标签 javascript coffeescript qunit sinon

我想在我的命名空间中使用一个方法 mock ,但我希望所有其他人都能正常工作。是否可以让 sinon 模拟一个特定的方法,同时让其他方法保持不变?

我的理解是我不是在寻找 spy ,因为我想断言模拟是使用特定参数调用的。

这是我在 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 最常见的用例之一,但我相信您正在寻找的既不是模拟也不是 spy ,而是 stub 。

参见: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()

但是,从您的问题来看,空操作 stub 函数似乎不是您想要的,而是想用您自己的自定义函数覆盖它:

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

喂!


编辑:

如何对单个函数进行 stub :

以下 stub 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.

如何对函数进行 stub 以测试特定参数

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(),这是我刚刚发现的。也可以证明对这些类型的测试非常有用。

如何只模拟一个对象的一个​​方法:

“模拟带有内置期望,可能会导致您的测试失败。因此,它们强制执行实现细节。经验法则是:如果您不为某些特定调用添加断言,请不要模拟它。使用取而代之的是一个 stub 。一般来说,在一次测试中你不应该有超过一个模拟(可能有多个期望)。” - source

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

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

关于javascript - 如何使用 Sinon 仅模拟一种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24924052/

相关文章:

javascript - Q promises 在 lodash reduce 函数中不起作用

javascript - 通过javascript函数更新html图像

javascript - CoffeeScript - 如何在 ruby​​ on Rails 中使用 CoffeeScript?

javascript - 如何在输入字段上对事件监听器进行单元测试?

php - Flash/Actionscript 是 css 和 javascript 的替代品吗?

javascript - 来自 JavaScript 函数的 Ajax 异步和循环 PHP 请求

node.js - NodeJS 和 CoffeeScript(咖啡可执行文件)表现不一样?

javascript - MeteorJS : Error in Meteor. 调用

jquery - 控制 QUnit 测试顺序

jquery-ui - Qunit 中 jQuery 小部件的单元测试