4

Is there any way in which I can spy on the bunyan log to ensure I print out what I expect?

MyFile.js

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

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

Test

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);
       });
    });
})
physicsboy
  • 5,656
  • 17
  • 70
  • 119

3 Answers3

8

Yes, with Jest it's quite easy:

let spyLogWarn = jest.spyOn(require('bunyan').prototype, 'warn')
// ...
expect(spyLogWarn).toHaveBeenCalled()
jonas
  • 185
  • 8
  • Thanks for the advice @jonas. I was in a bind of using sinon-chai due to the current stack, but I will keep this in mind for later :-) – physicsboy Jul 06 '18 at 09:26
1

I worked around this with the following:

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;
   }
});

...

I then used to mockReq.reRequire() function later on to reset the cache of the service I was wanting to mock.

To assert the actual content of the logs:

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

With this, I could assert them to equal whatever I expected.

physicsboy
  • 5,656
  • 17
  • 70
  • 119
0

For Sinon you may write something like:

const bunyan = require('bunyan');


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

And in asserting

sinon.assert.calledOnce(bunyan.prototype.fatal);
Mina Luke
  • 2,056
  • 1
  • 20
  • 22