使用 sinon 在包装器中调用对象时如何进行单元测试?

How to unit test when object is called within a wrapper using sinon?

下面的"set"方法需要使用sinon进行测试,不知如何进行。

// foo is just a wrapper
function Foo() {
  this.bar = new Bar();
}

Foo.prototype.set = function(x) {
   this.bar.set(x);
}

这是对其进行单元测试的尝试:

var foo = new Foo();
it("can called set method", function() {
  foo.set(x);
  foo.bar.set.calledOnceWith(x);
});

foo.bar.set.calledOnceWith 不是函数。

你很接近。

您只需在 Bar.prototype.set 上创建 spy:

import * as sinon from 'sinon';

function Bar() { }
Bar.prototype.set = function(x) {
  console.log(`Bar.prototype.set() called with ${x}`);
}

function Foo() {
  this.bar = new Bar();
}
Foo.prototype.set = function(x) {
  this.bar.set(x);
}

it('calls set on its instance of Bar', () => {
  const spy = sinon.spy(Bar.prototype, 'set');  // spy on Bar.prototype.set
  const foo = new Foo();
  foo.set(5);
  sinon.assert.calledWithExactly(spy, 5);  // SUCCESS
})