Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda