单元测试 MOCHA SINON CHAI(检查调用嵌套函数)
Unit testing MOCHA SINON CHAI (check call nested functions)
如果有人了解测试,请告诉我如何对两件事进行测试:
1) 当 makeRing 函数启动时,调用了 obj.newRing 方法。
2)传递给函数makeRing(num)的参数'num'是否与传入对象obj.newRing的属性相匹配({ 人数:人数}).
function makeRing (num) {
currRing = obj.newRing ({number: num});
}
也许有人会知道如何在这种情况下使用 sinon 或其他方式,我会很高兴提供任何信息。苦了好久。。。万分感谢!
如果您在测试中有权访问 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()
。
如果有人了解测试,请告诉我如何对两件事进行测试:
1) 当 makeRing 函数启动时,调用了 obj.newRing 方法。 2)传递给函数makeRing(num)的参数'num'是否与传入对象obj.newRing的属性相匹配({ 人数:人数}).
function makeRing (num) {
currRing = obj.newRing ({number: num});
}
也许有人会知道如何在这种情况下使用 sinon 或其他方式,我会很高兴提供任何信息。苦了好久。。。万分感谢!
如果您在测试中有权访问 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()
。