简体   繁体   English

单元测试MOCHA SINON CHAI(检查调用嵌套函数)

[英]Unit testing MOCHA SINON CHAI (check call nested functions)

If anyone understands the tests, please tell me how I can implement test for two things: 如果有人了解测试,请告诉我如何实现两件事的测试:

1) Was obj.newRing method called, when makeRing function starts. 1)在makeRing函数启动时调用了obj.newRing方法。 2) whether the parameter 'num' is passed to the function makeRing( num ) is Matches with the property of the object passed in obj.newRing ({ number: num }). 2)参数'num'是否传递给函数makeRing( num )是否与在obj.newRing({ number:num })中传递的对象的属性匹配。

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

Maybe someone will have some ideas how to use sinon or else in this situation, I will be glad of any information. 也许有人会对如何使用sinon有一些想法,否则在这种情况下,我将很高兴收到任何信息。 I suffer for a long time ... All thanks! 我受了很长时间...谢谢!

If you have access to obj in your test, you can do the following: 如果您可以在测试中访问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}]);

If you just want to know whether the function was called at all, then this is already covered with the second check (if the function was not called, newRingSpy.firstCall is null). 如果您只想知道是否完全调用了该函数,则第二项检查已将其覆盖(如果未调用该函数,则newRingSpy.firstCall为null)。

In case you do not have access to obj , it might be the best strategy to change your production code to something like this: 如果您无权访问obj ,那么将生产代码更改为以下内容可能是最好的策略:

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

Then you can easily pass the stubbed obj to makeRing() in your test. 然后,您可以在测试中轻松将存根的obj传递给makeRing()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM