How to mock Pino with destination

4.1k Views Asked by At

History. I am using Pino for logging my nodejs Express application. My logger setup was as follows

'use strict';

const pino = require('pino');

const logger = pino({
  level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
  prettyPrint: process.env.NODE_ENV === 'production' ? false : true,
  timestamp: true,
  redact: {
    paths: ['hostname', 'pid'], remove: true
  },
  dest
});

module.exports = logger;

In jestSetup.js I have

jest.mock('pino', () => () => {
  return {
    info: jest.fn(),
    error: jest.fn(),
    warn: jest.fn(),
    debug: jest.fn()
  };
});

This handles the common uses of pino such as log.info, log.error etc.

I wanted to add in the async option so that pino does not block execution.

New `logger.js'

'use strict';

const pino = require('pino');

//   NEW CODE BELOW
const dest = pino.destination({
  minLength: 4096, // Buffer before writing
  sync: false
}); // logs to stdout with no args
// NEW CODE ABOVE

const logger = pino({
  level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
  prettyPrint: process.env.NODE_ENV === 'production' ? false : true,
  timestamp: true,
  redact: {
    paths: ['hostname', 'pid'], remove: true
  },
  dest
});

module.exports = logger;

Tests now fail as pino.destination is not a function

How do I modify the jestSetup.js file to add the mock function for pino.destination?

1

There are 1 best solutions below

0
On

The solution is to mock the pino module, and to remove the entry from jestSetup.js

in __mocks\pino.js

const fakePino = {
  info: jest.fn(),
  error: jest.fn(),
  warn: jest.fn(),
  debug: jest.fn()
};

const fakePinoFunc = () => {
  return fakePino;
};
fakePinoFunc.destination = jest.fn();

jest.doMock('pino', () =>  { return fakePinoFunc; });
const pino = require('pino');

module.exports = pino;