I am coding a Discord bot and I want to test some code. With the discord.js library, we have to use a client to connect to the Discord API. At the beginning the client receives an event when it's ready:
In my index.js
client.on('ready', () => {})
But in my test I need information (a guild) coming from the cache of the client:
beforeAll(() => {
client.on('ready', () => {
// => guild that I need for test
guildToTest = client.guilds.cache.get('912785389704609832');
});
});
describe('setCounterForRoles testing', () => {
test('Unit test', async () => {
// => Here guildToTest is null
const guilds = await setCounterForRoles(guildToTest);
});
});
I need the guild for the test but this test is processed before the event ready is coming so the guild is null.
How can I make sure that the ready event is fired before running the tests?
I read some things in the docs on jest.spyOn() but I don't know if it's the solution.
If you want to run tests on a live Discord server, you can connect to the Discord server and get the guild inside beforeAll(). Your problem is that client.on is asynchronous, so you need to tell Jest that you're connected to the server and got the guild.
If the function passed to beforeAll()returns a promise, Jest waits for that promise to resolve before running your tests. So, you can return a promise here and resolve it inside your callback function.
Also, make sure you terminate the connection to Discord using the destroy() method inside your afterAll(). If you don't do this, Jest will complain that it "did not exit one second after the test run has completed".
let guildID = '912785389704609832';
let guild;
beforeAll(() => {
return new Promise((resolve) => {
client.on('ready', async () => {
guild = await client.guilds.fetch(guildID);
resolve();
});
});
});
afterAll(() => {
client.destroy();
});
describe('Connect to Discord', () => {
test('get the guild by its ID', async () => {
expect(guild.id).toBe(guildID);
});
});