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
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
Fela Maslen
I'm getting
TypeError: Attempted to wrap log which is already wrapped on the sinon.spy line?robertklep
@srynznfyra are you sure you're calling
.restore() on the spy after every test?Fela Maslen
Yes, I fixed it by replacing
spy.restore() with console.log.restore().lang-js