gpt4 book ai didi

node.js - 如何在 Node js 中使用 mocha 对控制台输出进行单元测试?

转载 作者:IT老高 更新时间:2023-10-28 22:03:44 25 4
gpt4 key购买 nike

考虑以下示例 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!'); }
};

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

我可以对 console.warnconsole.error 做同样的事情吗?

最佳答案

我更喜欢 mocha-sinon优于“普通”的 sinon,因为它与 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;
});

});

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

有一种解决方法,但也不是很理想,因为它会将 Mocha 输出与来自 privateFunction() 的输出穿插。如果这不是问题,请将 beforeEach() 替换为:

beforeEach(function() {
var log = console.log;
this.sinon.stub(console, 'log', function() {
return log.apply(log, arguments);
});
});

关于node.js - 如何在 Node js 中使用 mocha 对控制台输出进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30625404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com