【发布时间】:2015-10-13 10:07:12
【问题描述】:
如果我通过var a = sinon.createStubInstance(MyContructor) 创建了一个实例。
如何替换 var stub = sinon.stub(object, "method", func); 等存根函数之一。
我这样做的主要原因是想实现多个回调解决方法,如this mentioned
【问题讨论】:
标签: node.js mocha.js sinon nodeunit
如果我通过var a = sinon.createStubInstance(MyContructor) 创建了一个实例。
如何替换 var stub = sinon.stub(object, "method", func); 等存根函数之一。
我这样做的主要原因是想实现多个回调解决方法,如this mentioned
【问题讨论】:
标签: node.js mocha.js sinon nodeunit
你提到的方法(sinon.stub(object, "method", func))是1.x版本中提供的方法,根据文档做了如下操作:
将
object.method替换为func,包裹在一个间谍中。像往常一样,object.method.restore();可以用来恢复原来的方法。
但是,如果您使用的是sinon.createStubInstance(),则所有方法都已被存根。这意味着您已经可以对存根实例执行某些操作。例如:
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
Person.prototype.getName = function() {
return this.firstname + " " + this.lastname;
}
const p = sinon.createStubInstance(Person);
p.getName.returns("Alex Smith");
console.log(p.getName()); // "Alex Smith"
如果您真的想用另一个 spy 或 stub 替换 stub,您可以将该属性分配给一个新的 stub 或 spy:
const p = sinon.createStubInstance(Person);
p.getName = sinon.spy(function() { return "Alex Smith"; }); // Using a spy
p.getName = sinon.stub(); // OR using a stub
使用 Sinon.js 2.x 及更高版本,使用 callsFake() 函数更容易替换存根函数:
p.getName.callsFake(function() { return "Alex Smith"; });
【讨论】:
sinon.stub(object, "method", fn) 已被弃用。我们现在可以使用sinon.stub(object, "method").callsFake(function() { // do stuff }); 查看here Edit: fixed url
sinon.stub(object, "method", fn),所以我想我不会在答案本身中包含这些信息。
使用sinon.createStubInstance(MyConstructor) 或sinon.stub(obj) 存根整个对象后,您只能通过为属性分配新存根(如@g00glen00b 所述)或在重新存根之前恢复存根来替换存根。
var a = sinon.createStubInstance(MyConstructor);
a.method.restore();
sinon.stub(object, "method", func);
这样做的好处是您仍然可以在之后调用a.method.restore() 并获得预期的行为。
如果 Stub API 有一个 .call(func) 方法来覆盖 stub 事后调用的函数会更方便。
【讨论】:
不需要覆盖a.method,我们可以直接在a.method上使用callsFake:
const a = sinon.createStubInstance(MyContructor);
a.method.callsFake(func);
【讨论】:
2.0 + 的另一种方法存根方法
sinon.stub(object, "method").callsFake(func);
object.method.restore()
【讨论】: