Testing-Express-REST-API icon indicating copy to clipboard operation
Testing-Express-REST-API copied to clipboard

Pino's deprecated prettyPrint and its problem with Jest

Open TiE23 opened this issue 3 years ago • 0 comments

I have the solution to this issue, I just wanted to share it.

I noticed when working on the previous chapter of this tutorial that pino complains saying that prettyPrint is deprecated for the logger().

(node:54078) [PINODEP008] PinoWarning: prettyPrint is deprecated, look at https://github.com/pinojs/pino-pretty for alternatives.

So, I found that the preferred method is using a transport option, like so:

Before

const log = logger({
  prettyPrint: true,
  base: {
    pid: false,
  },
  timestamp: () => `,"time":"${dayjs().format()}"`,
});

After

const log = logger({
  transport: {
    target: "pino-pretty",
    options: {
      colorize: true,
    },
  },
  base: {
    pid: false,
  },
  timestamp: () => `,"time":"${dayjs().format()}"`,
});

But starting on this tutorial for testing I found a head-scratching error faced me when using --detectOpenHandles:

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  WORKER

      4 | const testMode = process.env.NODE_ENV === "test";
      5 |
    > 6 | const log = logger({
        |                   ^

After a short amount of Googling I found that the transport option was to blame. To check, I restored prettyPrint: true, removed transport: {...} and the error disappeared.

I don't know if this is perhaps the best method to fix it, but noticing that the env variable NODE_ENV was set when running jest (which is then utilized by config to switch to a different config file, test.js) I decided to take advantage of it and wrote this adjustment:

// NODE_ENV is set to "test" when jest is running.
const inTest = process.env.NODE_ENV === "test";

const log = logger({
  enabled: !inTest,
  transport: !inTest ? {
    target: "pino-pretty",
    options: {
      colorize: true,
    },
  } : undefined,
  base: {
    pid: false,
  },
  timestamp: () => `,"time":"${dayjs().format()}"`,
});

That solved it and I hope this is helpful.

TiE23 avatar Apr 14 '22 18:04 TiE23