假设我有一个函数:
function consoleOutput(param) {
var newParam = param * param;
console.log(newParam);
}
我如何在 Mocha 中测试该函数是否正常工作(参数将乘以 2 并输出到控制台)。谢谢。
对于这些类型的测试来说,一个很棒的库是Sinon http://sinonjs.org/。它可用于“挂钩”现有函数并跟踪这些函数如何被调用。
例如:
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();
});
这样做的优点是您不需要更改原始函数(在这种情况下,这不是什么大问题,但在较大的项目中可能并不总是可行)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)