Estoy usando tiza para diseñar el texto del terminal y escribí algunas funciones auxiliares para devolver instancias de chalk :
/* 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 };Para probar las funciones anteriores, usé Jest para escribir mi conjunto de pruebas:
/* 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"); }); }); });El conjunto de pruebas anterior pasa sin problemas.
Sin embargo, para probar que chalk.red.underline y chalk.green.underline se llaman correctamente, necesito simular la chalk usando jest.mock() con el siguiente código:
jest.mock("chalk", () => ({ green: { underline: jest.fn(), }, red: { underline: jest.fn(), }, })) ¿Existe una sintaxis más compacta de jest.mock() de modo que se burle de todos los métodos de instancia de chalk para convertirse en jest.fn() ?
Intenté usar el siguiente método simulado:
jest.mock("chalk");Sin embargo, la primera prueba fallará:
TypeError: Cannot read property 'underline' of undefined 2 | 3 | function redUnderline(text) { > 4 | return chalk.red.underline(text); | ^ 5 | }