【问题标题】:Mocking a Class from NPM Module with Jest, giving me a Constructor issue用 Jest 从 NPM 模块模拟一个类,给我一个构造函数问题
【发布时间】:2020-07-27 01:41:50
【问题描述】:

我正在尝试模拟 Discord.JS 模块。该模块有一个客户端类,我在我的“Bot”类中扩展它。我想模拟模块,这样我就可以模拟其他类的一些方法,例如“消息”和“频道”,但我不知道如何模拟特定的类来自一个 NPM 模块。尝试在 jest docs 和 Google 上找到一些东西,但 Google 结果只是链接到了这些文档。我不断收到这个问题class extends value of undefined is not a constructor or null。这就是我的测试文件中的内容,

jest.mock('discord.js', () => ({

}));

我知道我需要手动模拟其他类(客户端、消息、通道等是 discord.js 模块的类),但我不确定如何正确地这样做

消息对象有一个名为channel的属性,它是一个通道对象,而通道对象有一个.send()方法,所以我尝试了这个

jest.mock('discord.js', () => ({
  Client: jest.fn(),
  Message: jest.fn().mockImplementation(() => ({
    channel: jest.fn().mockImplementation(() => ({
      send: jest.fn((x) => 'Hello World'),
    })),
  })),
}));

但它一直说 msg.channel.send 不是方法

describe('should test all commands', () => {

  let info: BaseCommand;
  let bot: Bot;
  let msg: Message;
  beforeAll(() => {
    info = new InfoCommand();
    bot = new Bot({});
    msg = new Message(bot, null, null);
    jest.spyOn(bot, 'addCommand');
  });

  test('should check if command arguments are invoked correctly', () => {
    msg.channel.send('x');
  });
});

【问题讨论】:

    标签: javascript node.js reactjs testing jestjs


    【解决方案1】:

    这是因为您将 Message 定义为函数而不是对象:

       jest.mock('discord.js', () => ({
          Client: jest.fn(),
          Message: {
            channel: {
              send: jest.fn()
            }
          }
        }));
    

    如果您需要模拟 Message 对象的整个行为,您可以创建一个模拟类并以这种方式模拟其行为

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      相关资源
      最近更新 更多