Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How in Mocha test function with console.log statement?

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.

like image 649
Mr. Dzhen Avatar asked May 08 '16 06:05

Mr. Dzhen


People also ask

How do you check the output of a console log?

Steps to Open the Console Log in Google Chrome By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements". Now you can see the Console and any output that has been written to the Console log.

What does console log () do?

The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.


1 Answers

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

like image 63
robertklep Avatar answered Nov 15 '22 05:11

robertklep