如果您在测试中有权访问obj
,则可以执行以下操作:
// create a spy for your function:
const newRingSpy = sinon.spy();
// replace the real function with the spy:
sinon.stub(obj, 'newRing', newRingSpy);
// run the test:
makeRing(7);
// 1) validate that obj.newRing was called exactly once:
expect(newRingSpy.calledOnce).to.be(true);
// 2) and/or validate the arguments it was called with:
expect(newRingSpy.firstCall.args).to.eql([{number: 7}]);
如果您只是想知道函数是否被调用,那么这已经包含在第二次检查中(如果函数没有被调用,newRingSpy.firstCall
则为空)。
如果您无权访问obj
,将生产代码更改为以下内容可能是最佳策略:
function makeRing (num, obj) {
currRing = obj.newRing ({number: num});
}
然后,您可以轻松地将存根传递obj
给makeRing()
您的测试。