如果我通过 var a = sinon.createStubInstance(MyContructor)
创建了一个实例。
如何替换 var stub = sinon.stub(object, "method", func); 之类的 stub 函数之一;
.
我这样做的主要原因是想要实现多个回调解决方法,如 this mentioned
最佳答案
您提到的方法 (sinon.stub(object, "method", func)
) 是版本 1.x 中可用的方法,并且做了根据文档:
Replaces
object.method
with afunc
, wrapped in a spy. As usual,object.method.restore()
; can be used to restore the original method.
但是,如果您使用的是 sinon.createStubInstance()
,则所有方法都已被 stub 。这意味着您已经可以对 stub 实例执行某些操作。例如:
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()
函数更容易替换 stub 函数:
p.getName.callsFake(function() { return "Alex Smith"; });
关于node.js - 使用 Sinon 时,如何替换 stub 实例中的 stub 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33099863/