【问题标题】:spying on bunyan log - NodeJS监视 bunyan 日志 - NodeJS
【发布时间】:2018-06-29 12:53:31
【问题描述】:

有什么方法可以监视 bunyan 日志以确保打印出我期望的内容?

MyFile.js

const bunyan = require('bunyan');
const log = bunyan.createLogger({name: 'FailureAuditService'});

class someClass {
   someFunct() {
     if(x) {
        log.warn('something happened');
     }
   }
}

测试

const service = require(../MyFile);

describe('test something', () => {
    it('Will test the bunyan log', res => {
       let consoleLog = sinon.spy(log, 'createLogger');
       let x = true;

       service.someClass(x).then(res => {
          let expected = 'something happened';
          consoleLog.should.equal(expected);
       });
    });
})

【问题讨论】:

    标签: javascript node.js testing sinon bunyan


    【解决方案1】:

    是的,Jest 非常简单:

    let spyLogWarn = jest.spyOn(require('bunyan').prototype, 'warn')
    // ...
    expect(spyLogWarn).toHaveBeenCalled()
    

    【讨论】:

    • 感谢@jonas 的建议。由于当前的堆栈,我一直在使用 sinon-chai,但我会记住这一点以备后用:-)
    【解决方案2】:

    我通过以下方式解决了这个问题:

    const mockReq = require('mock-require);
    
    ...
    
    let infoStub = sinon.stub();
    let warnStub = sinon.stub();
    
    logStubs = {
       info: infoStub,
       warn: warnStub
       // any other log methods you wish to use
    };
    
    mockReq('bunyan', {
       createLogger() {
          return logStubs;
       }
    });
    
    ...
    

    我后来使用 mockReq.reRequire() 函数来重置我想要模拟的服务的缓存。

    断言日志的实际内容:

    let infoLog = infoStub.firstCall.args[0];
    let warnLog = warnStub.firstCall.args[0];
    

    有了这个,我可以断言它们等于我所期望的。

    【讨论】:

      【解决方案3】:

      对于Sinon,你可以这样写:

      const bunyan = require('bunyan');
      
      
      sinon.stub(bunyan.prototype);
      // or
      sinon.stub(bunyan.prototype, 'fatal');
      // or
      sinon.stub(bunyan.prototype, 'fatal').callThrough();
      
      

      在断言中

      sinon.assert.calledOnce(bunyan.prototype.fatal);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-18
        • 2015-05-23
        • 2014-09-26
        • 2012-09-01
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2010-12-11
        相关资源
        最近更新 更多