0

如果有人了解测试,请告诉我如何为两件事实施测试:

1) makeRing 函数启动时是否调用了 obj.newRing 方法。2) 参数'num'是否传递给函数makeRing( num )是否与obj.newRing({ number:num })中传递的对象的属性相匹配。

function makeRing (num) {
currRing = obj.newRing ({number: num});
 }

也许有人会对如何使用 sinon 有一些想法,否则在这种情况下,我会很高兴任何信息。我受苦了很长时间......谢谢!

4

1 回答 1

0

如果您在测试中有权访问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});
}

然后,您可以轻松地将存根传递objmakeRing()您的测试。

于 2016-05-18T20:45:46.463 回答