首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在nodejs上使用mocha对控制台输出进行单元测试?

如何在nodejs上使用mocha对控制台输出进行单元测试?
EN

Stack Overflow用户
提问于 2015-06-04 00:12:19
回答 1查看 52.6K关注 0票数 41

请考虑以下示例Javascript代码:

代码语言:javascript
复制
function privateFunction (time) {
  if (time < 12) { console.log('Good morning'); }
  if (time >= 12 && time <19) { console.log('Good afternoon'); }
  else { console.log('Good night!'); }
};

我应该如何在nodejs上使用mocha (可能还有sinonjs)进行单元测试,注意到这是一个在模块内部调用的私有函数?我需要传入参数并检查函数是否将正确的内容记录到控制台。

我可以对console.warnconsole.error执行相同的操作吗

EN

回答 1

Stack Overflow用户

发布于 2015-06-04 00:45:11

我更喜欢mocha-sinon而不是“普通的”sinon,因为它与Mocha很好地集成在一起。

示例:

代码语言:javascript
复制
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;
  });

});

一个潜在的问题:一些Mocha记者也使用console.log,所以存根它的测试可能不会产生任何输出。

有一个变通方法,但它也不是很理想,因为它会将Mocha输出与privateFunction()的输出混杂在一起。如果这不是问题,请用下面的代码替换beforeEach()

代码语言:javascript
复制
beforeEach(function() {
  var log = console.log;
  this.sinon.stub(console, 'log', function() {
    return log.apply(log, arguments);
  });
});
票数 44
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30625404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档