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 | }