Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

251
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda