运行单元测试时,如何抑制来自node.js应用程序的应用程序日志消息? [英] How to suppress application logging messages from a node.js application when running unit tests?

查看:70
本文介绍了运行单元测试时,如何抑制来自node.js应用程序的应用程序日志消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用mocha和supertest对我的node.js应用程序(基本上是REST后端)进行单元测试时,我只需要屏幕上特定于测试的消息,但标准输出中也充满了应用程序日志消息.

While unit-testing my node.js application (which is basically a REST backend) using mocha and supertest, I need only the test-specific message on the screen, but the stdout is also cluttered with application log messages.

我通过以下方式开始单元测试:

I start the unit test with:

mocha -R spec .

...并获得此输出(这是不应的结果):

... and get this output (this is what it should not be):

[App] Listening on port 3000 ...
[App] Starting app, hooray!

  Project API
    GET /projects
[App] entering "projects" module ...
      √ should return an array of projects (317ms)

我用[App]标记了应用程序日志消息.我真正想要的是单元测试的输出:

I marked the application log message with [App]. What I really want would be this output from the unit test:

  Project API
    GET /projects
      √ should return an array of projects (317ms)

我如何抑制应用程序插入Mocha的报告程序输出的console.log/warn/error输出?

How can I suppress console.log/warn/error output by the application interspersed with Mocha's reporter output?

解决方案:

按照dankohn的方法,我最终像这样,解决了我的问题(使用 winston 进行记录):

Following dankohn's approach, I ended up like this, which solves my issue (using winston for logging):

(在节点的主"服务器文件中,server.js:)

(in node's "main" server file, server.js:)

if (process.env.NODE_ENV !== 'test') {
    logger = new (winston.Logger)({
        transports: [
            new (winston.transports.Console)(),
            new (winston.transports.File)({ filename: 'foo.log' })
        ]
    });
} else {
    // while testing, log only to file, leaving stdout free for unit test status messages
    logger = new (winston.Logger)({
        transports: [
            new (winston.transports.File)({ filename: 'foo.log' })
        ]
    });
}

...并设置env变量,每个单元测试文件均以:

... and to set the env variable, each unit test file starts with:

process.env.NODE_ENV = 'test';

推荐答案

在您的app.js中:

In your app.js:

if (process.env.NODE_ENV !== 'test') {
  app.use(express.logger());
}

每个mocha文件的顶部:

At the top of each of your mocha files:

process.env.NODE_ENV = 'test';

更新:

我们在导入代码中使用此功能:

We use this function in our import code:

function logExceptOnTest(string) {
  if (process.env.NODE_ENV !== 'test') {
    console.log(string);
  }
}

然后,将所有console.log('it worked')替换为logExceptOnTest('it worked').基本技巧是将环境变量用作所需日志级别的全局标志.

Then, replace all your console.log('it worked') with logExceptOnTest('it worked'). The basic trick is to use environment variables as a global flag as to the level of logging you want.

这篇关于运行单元测试时,如何抑制来自node.js应用程序的应用程序日志消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆