javascript - 如何模拟“粉笔”库的所有方法?
问题描述
我正在使用粉笔来设置终端文本的样式,并编写了一些辅助函数来返回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 };
为了测试上述功能,我使用Jest编写了我的测试套件:
/* 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");
});
});
});
上面的测试套件通过没有问题。
但是,为了测试它chalk.red.underline
并chalk.green.underline
正确调用,我需要chalk
使用jest.mock()
以下代码进行模拟:
jest.mock("chalk", () => ({
green: {
underline: jest.fn(),
},
red: {
underline: jest.fn(),
},
}))
是否有更紧凑的语法jest.mock()
可以模拟所有 chalk
实例方法成为jest.fn()
?
我尝试使用以下模拟方法:
jest.mock("chalk");
但是,第一个测试将失败:
TypeError: Cannot read property 'underline' of undefined
2 |
3 | function redUnderline(text) {
> 4 | return chalk.red.underline(text);
| ^
5 | }
解决方案
推荐阅读
- r - How to automatically fill in a blank column
- python - PynamoDB query() 返回 0 值,而 scan() 确实
- typo3 - TYPO3 10.4 - 手动安装后端语言
- node.js - 执行任何类型函数的函数
- c++ - 如何在 UML 类图中表示 C++ 程序的静态结构?
- reactjs - Solana React TypeError:this.wallet.signTransaction 不是函数
- python - ValueError at / 视图 Leads.views.home_page 未返回 HttpResponse 对象。它返回 None 而不是 python django 模板错误如何修复
- qt - qRubberBand 在某些情况下不连续绘制
- visual-studio-code - VS 代码集成终端损坏
- c# - 由于 SHA256 MD5,我无法连接 posgresql db