How to suppress application logging messages from a node.js application when running unit tests?

前端 未结 4 2099
春和景丽
春和景丽 2020-12-13 08:37

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

4条回答
  •  没有蜡笔的小新
    2020-12-13 09:02

    In your app.js:

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

    At the top of each of your mocha files:

    process.env.NODE_ENV = 'test';
    

    Update:

    We use this function in our import code:

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

    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.

提交回复
热议问题