Reputation: 105
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');
});
});
Upvotes: 3
Views: 1330
Reputation: 78
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
Upvotes: 4