npm package chalk is not working with Cypress

231 Views Asked by At

I want to use https://www.npmjs.com/package/chalk for console logs.

Now if I use with console.log it works

console.log(chalk.blue("Hello World"))

but when I run it with cy.task it doesn't give any error but doesn't show any coloring

cy.task('log', chalk.blue("Hello World")); it prints Hello World but not in blue color

What am I doing wrong?

1

There are 1 best solutions below

9
On

The Cypress cy.task() command is an interprocess communication (browser to nodejs) and it must serialize it's parameters.

I guess, from the result of your test, that means the ansi chars used to color the log entry might be stripped away.

One way to get around that is to invoke chalk inside the task.

import { defineConfig } from 'cypress'
import chalk from 'chalk';

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        log({message, attributes}) {
          const fn = attributes.reduce((chalk, attr) => chalk[attr], chalk)
          console.log(fn(message))
          return null;
        },
      });

      return config;
    },
  },
});

Since chalk v5 is pure ESM, I had to convert the cypress.config.js to the ESM format given for typescript on this page Configuration File and add "type": "module", to the package.json, although the docs say you could also use the mjs extension.

This is the test

it('logs to terminal using chalk', () => {
  cy.task('log', {message: 'hello chalk', attributes: ['underline', 'bgBlue', 'bold', 'green']})
})

This is the output

enter image description here