如何使用console.log语句在Mocha中测试函数

How in Mocha test function with console.log statement?

本文关键字:Mocha 测试 函数 语句 何使用 console log      更新时间:2023-09-26

比方说,我有一个函数:

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

我如何在Mocha中测试这个函数是否正常工作(param将乘以2并输出到控制台)。谢谢

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();
});

这样做的好处是,您不需要更改原始功能(在这种情况下,这不是什么大不了的事情,但在较大的项目中可能并不总是可能的)。