我想使用Jest创建一个模拟的winston记录器实例。
这是为了让我可以使用依赖项注入来监视logger.warning()
的调用次数以及错误消息。
但是,由于Winston使用工厂方法createLogger()
,因此在jest.mock("winston")
上进行自动模拟时,它将使我对createLogger()
的调用返回未定义的状态。
这是我的代码:
import { VoiceChannelDisconnect } from "./../../src/PeriodicTask/VoiceChannelDisconnect";
import { Logger, createLogger } from "winston";
import { VoiceChannel, GuildMember, Collection } from "discord.js";
jest.mock("winston");
jest.mock("discord.js");
const MockedVoiceChannel = VoiceChannel as jest.Mock<VoiceChannel>;
let voiceChannel = new MockedVoiceChannel();
let logger = createLogger();
let voiceChannelDisconnect = new VoiceChannelDisconnect(voiceChannel, logger);
it("returns true when no one is left in channel", () => {
voiceChannel = new MockedVoiceChannel();
voiceChannel.members = new Collection<string, GuildMember>();
logger = createLogger();
logger.warning = jest.fn();
voiceChannelDisconnect = new VoiceChannelDisconnect(voiceChannel, logger);
expect(voiceChannelDisconnect.execute()).toBe(true);
expect(logger.warning).toBeCalledTimes(1);
});
运行测试会得出结果:
TypeError: Cannot set property 'warning' of undefined
15 |
16 | logger = createLogger();
> 17 | logger.warning = jest.fn();
如何创建仍然满足Typescript类型检查的模拟Logger
实例?
预先感谢
答案 0 :(得分:0)
我设法通过修改here
提出的问题来解决此问题通过这样:
jest.mock("winston", () => ({
createLogger: jest.fn().mockReturnValue({
debug: jest.fn(),
warning: jest.fn()
})
}));
在测试的顶部createLogger
,我现在可以跟踪logger.warning
被调用了多少次