简体   繁体   English

Mocking 来自 NPM 模块的 Class 带有 Jest,给我一个构造函数问题

[英]Mocking a Class from NPM Module with Jest, giving me a Constructor issue

I'm trying to mock the Discord.JS module.我正在尝试模拟 Discord.JS 模块。 The module has a Client class, which I am extending in my "Bot" class.该模块有一个客户端 class,我在我的“机器人”class 中扩展它。 I want to mock the module so I can mock some of the methods on the other classes, such as "Message" and "Channel", but I can't figure out how to mock a particular class from an NPM module.我想模拟模块,以便可以模拟其他类的一些方法,例如“消息”和“通道”,但我不知道如何NPM 模块模拟特定的 class。 Tried finding something on the jest docs and on Google but the Google results just linked to the docs.试图在 jest docs 和 Google 上找到一些东西,但 Google 结果只是链接到了这些文档。 I keep getting this issue class extends value of undefined is not a constructor or null .我不断收到这个问题class extends value of undefined is not a constructor or null This is what I have in my test file,这就是我的测试文件中的内容,

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

}));

and I know I need to manually mock the other classes (Client, Message, Channel, etc. are classes of the discord.js module) but I'm not sure how to properly do so我知道我需要手动模拟其他类(客户端、消息、通道等是 discord.js 模块的类),但我不知道如何正确地这样做

The message object has a property called channel which is a channel object, and the channel object has a.send() method so I tried this消息 object 有一个名为 channel 的属性,它是一个通道 object,通道 object 有一个.send() 方法所以我试过这个

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

but it keeps saying msg.channel.send is not a method但它一直说 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');
  });
});

It's because you define Message as a function instead of as an object:这是因为您将 Message 定义为 function 而不是 object:

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

If you need to mock the whole behaviour of the Message object, you could create a mock Class and mock its behaviour that way如果您需要模拟消息 object 的整个行为,您可以创建一个模拟 Class 并以这种方式模拟其行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM