模拟工厂在打字稿中使用笑话

时间:2019-11-22 19:43:22

标签: typescript unit-testing jestjs winston

我想使用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实例?

预先感谢

1 个答案:

答案 0 :(得分:0)

我设法通过修改here

提出的问题来解决此问题

通过这样:

jest.mock("winston", () => ({
  createLogger: jest.fn().mockReturnValue({
    debug: jest.fn(),
    warning: jest.fn()
  })
}));

在测试的顶部createLogger,我现在可以跟踪logger.warning被调用了多少次