如何在mocha测试函数与console.log语句?

Mr.*_*hen 4 javascript mocha.js

比方说,我有一个功能:

function consoleOutput(param) {
  var newParam = param * param;  
  console.log(newParam);
}
Run Code Online (Sandbox Code Playgroud)

如何在Mocha中测试,此功能将正常工作(param将乘以2并输出到控制台).谢谢.

rob*_*lep 24

适用于这些类型测试的优秀库是Sinon.它可用于"挂钩"现有函数并跟踪这些函数的调用方式.

例如:

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();
});
Run Code Online (Sandbox Code Playgroud)

这样做的好处是您不需要更改原始功能(在这种情况下,这不是一个大问题,但在大型项目中可能并不总是可行).

  • 是的,我通过将`spy.restore()`替换为`console.log.restore()`来解决了。 (2认同)