Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
Jest : waiting for an event to process test

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
  });
});

enter image description here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!