javascript - 开玩笑地嘲笑温斯顿记录器
问题描述
我正在考虑如何模拟运输。文件(来自 winston 节点模块)。我正在使用 jest,所以__mocks__/winston.ts
是自动加载的。我认为我不能嘲笑它,因为有new
// LoggerFactory.ts
import { transports, TransportInstance } from "winston";
...
const transportList: TransportInstance[] = [
new transports.File({
name: `${tag}-error`,
filename: `${dirname}${filename}.error.log`,
json: false,
level: "error",
zippedArchive: false,
maxFiles: 14,
maxsize: 100000000
}),
new transports.File({
name: `${tag}-info`,
filename: `${dirname}${filename}.log`,
json: false,
level: "info",
maxFiles: 10,
zippedArchive: false,
maxsize: 100000000
})
];
...
// __mocks__/winston.ts
const winston = {
????
};
export default winston;
错误:TypeError:无法读取未定义的属性“文件”
解决方案
对于我们的 winston 测试模拟__mocks__/winston.js
,我们这样做:
const logger = {
format: {
printf: jest.fn(),
timestamp: jest.fn(),
simple: jest.fn(),
colorize: jest.fn(),
combine: jest.fn()
},
transports: {
Console: jest.fn(),
File: jest.fn()
},
createLogger: jest.fn().mockImplementation(function(creationOpts) {
return {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn()
};
})
};
module.exports = logger;
然后我们可以使用jest.fn()
调用捕获器来测试记录器。通常我们不关心日志,所以这只是用来在测试期间不生成日志文件。
推荐阅读
- python - 是否可以为数据框的每一列创建一个额外的 pct_change 列?
- shell - 从第一天的午夜开始查找并列出最近 3 天的文件
- terraform - AWS EKS 从头开始 - terraform 还是 eksctl?
- javascript - 当多台服务器访问数据库时,如何使用 mongodb 只允许一个条目?
- html - 如何有一个非矩形的 div?
- javascript - 仅为给定域设置 cookie
- xaml - Sharpnado.Tabs 用于在 Xamarin.Forms 中设计此 Screenshort Ui
- vba - 如何将公式的结果保存在字符串而不是公式本身中
- javascript - 检查类是否存在
- oracle - 当查询执行时间不到一秒时,为什么使用 HQL 执行批处理时出现 ORA-01013 错误