如何在Node.js上使用Mocha进行单元测试控制台输出? [英] How to unit test console output with mocha on nodejs?
问题描述
请考虑以下以下示例Javascript代码:
Take into account the following example Javascript code below:
function privateFunction (time) {
if (time < 12) { console.log('Good morning'); }
if (time >= 12 && time <19) { console.log('Good afternoon'); }
else { console.log('Good night!'); }
};
我应该如何使用mocha(可能还有sinonjs)在nodejs上进行单元测试,注意这是在模块内部调用的私有函数?我需要传递参数,并检查函数是否将正确的内容记录到控制台.
How should I unit test that on nodejs using mocha (and possibly sinonjs), noticing that this is a private function called inside a module? I need to pass in the argument and check if the function is logging the right thing to the console.
我可以对console.warn
和console.error
做同样的事情吗?
Can I do the same with console.warn
and console.error
?
推荐答案
与普通"相比,我更喜欢 mocha-sinon
sinon,因为它与Mocha很好地集成了.
I prefer mocha-sinon
over "plain" sinon because it integrates nicely with Mocha.
示例:
var expect = require('chai').expect;
require('mocha-sinon');
// Function to test, can also be in another file and as long as it's
// being called through some public interface it should be testable.
// If it's not in any way exposed/exported, testing will be problematic.
function privateFunction (time) {
if (time < 12) { console.log('Good morning'); }
if (time >= 12 && time <19) { console.log('Good afternoon'); }
else { console.log('Good night!'); }
}
describe('privateFunction()', function() {
beforeEach(function() {
this.sinon.stub(console, 'log');
});
it('should log "Good morning" for hours < 12', function() {
privateFunction(5);
expect( console.log.calledOnce ).to.be.true;
expect( console.log.calledWith('Good morning') ).to.be.true;
});
it('should log "Good afternoon" for hours >= 12 and < 19', function() {
privateFunction(15);
expect( console.log.calledOnce ).to.be.true;
expect( console.log.calledWith('Good afternoon') ).to.be.true;
});
it('should log "Good night!" for hours >= 19', function() {
privateFunction(20);
expect( console.log.calledOnce ).to.be.true;
expect( console.log.calledWith('Good night!') ).to.be.true;
});
});
一个潜在的问题:一些摩卡记者也使用console.log
,因此将其存根的测试可能不会产生任何输出.
One potential issue: some Mocha reporters use console.log
as well, so the tests that stub it may not yield any output.
有一种解决方法,但也不理想,因为它将Mocha输出与privateFunction()
输出混杂在一起.如果这不是问题,请用以下内容替换beforeEach()
:
There's a workaround, but it's not ideal either because it will intersperse Mocha output with the output from privateFunction()
. If that's not a problem, replace beforeEach()
with this:
beforeEach(function() {
var log = console.log;
this.sinon.stub(console, 'log', function() {
return log.apply(log, arguments);
});
});
这篇关于如何在Node.js上使用Mocha进行单元测试控制台输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!