简体   繁体   中英

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

I'm trying to mock the Discord.JS module. The module has a Client class, which I am extending in my "Bot" 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. Tried finding something on the jest docs and on Google but the Google results just linked to the docs. I keep getting this issue 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

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

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

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:

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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