18

如果我创建了一个实例 var a = sinon.createStubInstance(MyContructor)

如何替换其中一个存根函数,例如var stub = sinon.stub(object, "method", func);.

我这样做的主要原因是想要实现上述提到的多个回调解决方法

4

4 回答 4

20

您提到的方法 ( sinon.stub(object, "method", func)) 是1.x版本中可用的方法,并根据文档执行了以下操作:

替换object.methodfunc, 包裹在一个间谍中。像往常一样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"; });
于 2015-10-13T10:28:37.290 回答
14

sinon.createStubInstance(MyConstructor)在使用or存根整个对象后,sinon.stub(obj)您只能通过为属性分配新存根(如 @g00glen00b 所述)或在重新存根之前恢复存根来替换存根。

var a = sinon.createStubInstance(MyConstructor);
a.method.restore();
sinon.stub(object, "method", func);

这样做的好处是您a.method.restore()之后仍然可以使用预期的行为进行调用。

.call(func)如果 Stub API 有一种方法可以在事后覆盖由 stub 调用的函数,那会更方便。

于 2016-10-30T11:54:25.137 回答
3

不需要覆盖a.method,我们可以直接callsFake使用a.method

const a = sinon.createStubInstance(MyContructor);
a.method.callsFake(func);
于 2018-10-09T21:59:08.443 回答
0

从 2.0 + 存根方法的另一种方法

sinon.stub(object, "method").callsFake(func);

object.method.restore()

于 2018-04-02T19:41:07.437 回答