[英]Mocking winston logger in jest
I'm thinking how to mock transports.我正在考虑如何模拟运输。 File (from winston node module).
文件(来自 winston 节点模块)。 I'm using jest so
__mocks__/winston.ts
is auto-loaded.我正在使用 jest,所以
__mocks__/winston.ts
是自动加载的。 I think that I can't mock it becouse there is new
我认为我不能嘲笑它,因为有
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;
error: TypeError: Cannot read property 'File' of undefined错误:TypeError:无法读取未定义的属性“文件”
For our winston test mocks in __mocks__/winston.js
, we do:对于
__mocks__/winston.js
中的 winston 测试模拟,我们执行以下操作:
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;
We can then use the jest.fn()
call catchers to test for the logger.然后我们可以使用
jest.fn()
调用捕获器来测试记录器。 Generally we don't care about logging so this is just used not to generate log files during tests.通常我们不关心日志,所以这只是用来在测试期间不生成日志文件。
In your test file, type the following at the top:在您的测试文件中,在顶部键入以下内容:
const mockWinstonLog = jest.fn()
jest.mock('winston', () => ({
createLogger: jest.fn(() => ({
log: mockWinstonLog,
})),
transports: {
Console: jest.fn(),
},
format: {
json: jest.fn(),
},
}))
You can then in your test cases check for:然后,您可以在测试用例中检查:
expect(mockWinstonLog).toHaveBeenCalled()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.