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

问题描述 投票:2回答:1

以下“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不是一个函数。

javascript sinon
1个回答
1
投票

你很亲密

你只需要在spy上创建Bar.prototype.set

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
})
© www.soinside.com 2019 - 2024. All rights reserved.