Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
How to mock all methods of the "chalk" library?

I'm using chalk to style terminal text and I wrote some helper functions to return chalk instances:

/* colorUtils.js */
const chalk = require("chalk");

function redUnderline(text) {
  return chalk.red.underline(text);
}
function greenUnderline(text) {
  return chalk.green.underline(text);
}

module.exports = { redUnderline, greenUnderline };

To test the above functions, I used Jest to write my test suite:

/* colorUtils.test.js */
const chalk = require("chalk");
const { redUnderline, greenUnderline } = require("./colorUtils");

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}));

describe("colorUtils", () => {
  describe("redUnderline", () => {
    it("should return a red, underlined string", () => {
      const result = redUnderline("foo");
      expect(chalk.red.underline).toHaveBeenCalledWith("foo");
    });
  });
  describe("greenUnderline", () => {
    it("should return a green, underlined string", () => {
      const result = greenUnderline("foo");
      expect(chalk.green.underline).toHaveBeenCalledWith("foo");
    });
  });
});

The above test suite passes without problems.

However, in order to test that chalk.red.underline and chalk.green.underline is called properly, I need to mock chalk using jest.mock() with the following code:

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}))

Is there a more compact syntax of jest.mock() such that it mocks all chalk instance methods to become jest.fn()?

I tried using the following mock method:

jest.mock("chalk");

However, the first test will fail:

    TypeError: Cannot read property 'underline' of undefined

      2 |
      3 | function redUnderline(text) {
    > 4 |   return chalk.red.underline(text);
        |                    ^
      5 | }
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda