简体   繁体   中英

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. 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 }).

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. I suffer for a long time ... All thanks!

If you have access to obj in your test, you can do the following:

// 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).

In case you do not have access to obj , it might be the best strategy to change your production code to something like this:

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

Then you can easily pass the stubbed obj to makeRing() in your test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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