How in Mocha test function with console.log statem

2019-06-27 10:19发布

问题:

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.

回答1:

Please take a look on the below code, you will get an idea on mocha test case

var assert = require('chai').assert;

// Function to be Tested
function consoleOutput(param) {
  var newParam = param * param;  
  console.log(newParam);
  return newParam;
}

// Mocha Test Case
describe('Mocha Test Case', function() {
    it('Square Root', function(done) {
        var sqrt = consoleOutput(5);
        assert.equal(sqrt, 25);
        done();
    });
});

Update (25-Mar-2017):

Check out the below answers for best paratice



回答2:

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