9

Let's say, I have a function:

function consoleOutput(param) {
 var newParam = param * param; 
 console.log(newParam);
}

How can I test in Mocha, that this function will be working correctly (param will be multiplied by two and output to the console). Thanks.

robertklep
205k38 gold badges419 silver badges412 bronze badges
asked May 8, 2016 at 6:39

1 Answer 1

32

A great library for these types of tests is Sinon. It can be used to "hook" existing functions and track how those functions get called.

For example:

const sinon = require('sinon');
const assert = require('assert');
// the function to test
function consoleOutput(param) {
 var newParam = param * param; 
 console.log(newParam);
}
it('should log the correct value to console', () => {
 // "spy" on `console.log()`
 let spy = sinon.spy(console, 'log');
 // call the function that needs to be tested
 consoleOutput(5);
 // assert that it was called with the correct value
 assert(spy.calledWith(25));
 // restore the original function
 spy.restore();
});

The advantage of this is that you don't need to change the original function (which, in this case, isn't a big deal, but may not always be possible in larger projects).

answered May 8, 2016 at 8:22
Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting TypeError: Attempted to wrap log which is already wrapped on the sinon.spy line?
@srynznfyra are you sure you're calling .restore() on the spy after every test?
Yes, I fixed it by replacing spy.restore() with console.log.restore().

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.