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

192
Vistas
Asynchronous tests using jest and only callbacks

I'm trying to implement some asynchronous tests using jest and only callbacks. I managed to make this code, which I hope is right (it passes the test):

test('Test the then() clause', function (done) {
    expect.assertions(1);
    const result = generate();
    new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(result);
        }, 100);
    }).then((data) => {
        expect(data).toBe(result);
        done();
    });
});

But I'm stuck trying to create a test when I expect to catch an error, just like so:

test('Test unhandled promise rejection', function (done) {
    expect.assertions(1);
    try {
        new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
        });
    } catch (error) {
        console.log(error);
        done();
    }
});

What I am doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

EDIT: If you want to do this with a callback then simply get rid of the try/catch

test('Test unhandled promise rejection', function (done) {
    new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
    }).catch(() => {
      console.log(error);
      done();
    });
});

You need to await the promise, otherwise it doesn't throw

test('Test unhandled promise rejection', async function (done) {
    expect.assertions(1);
    try {
        await new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
        });
    } catch (error) {
        console.log(error);
        done();
    }
});

So it's just plain easier (IMO) to skip the callbacks and use resolves/rejects

test('Test unhandled promise rejection', async () => {
    await expect(new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
    }).rejects.toMatch('errorrrrr')
});
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