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

95
Visualizações
Jest test for async promise with async/await

I have this function that returns a promise and fails when is called:

export const mockAsync = () => {
  return new Promise((_, reject) => {
    setTimeout(() => reject(new Error('Error')), 50);
  });
};

And I have this test, which is passing:

describe('mockAsync', () => {
  test('it should throw if we ask for it', async () => {
    const result = mockAsync();

    await expect(result).rejects.toThrow('Error');
  });
});

But I find it weird, I would expect it to call await before the function call:

describe('mockAsync', () => {
  test('it should throw if we ask for it', async () => {
    const result = await mockAsync();

    expect(result).rejects.toThrow('Error');
  });
});

This last one is not passing, and I cant understand why. Is not the correct syntax?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For the test the work you want the promise to be rejected within the context of the expect. for that reason we usually write it like this:

await expect(/*sync function call*/).rejects.toThrow('someError')

And in your particular example:

describe('mockAsync', () => {
    test('it should throw if we ask for it', async () => {

        await expect(mockAsync()).rejects.toThrow('Error')
    })
})

If you want to use the Try/Catch approach simply catch the error and make sure the error is the expected one:

describe('mockAsync', () => {
    test('it should throw if we ask for it', async () => {

        try{
            await mockAsync()
        }
        catch(err){
            expect(err.message).toEqual('Error')
        }
    })
})
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