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

87
Visualizações
Verify async function throws non-error object using jest

Using the jest framework, how can I verify that my async function throws something other than an Error?

In my examples below, the first one works as expected, as the function being tested throws an Error. The second example, where the function throws a string, doesnt work - jest doesnt verify that the function throws.

// Works as expected
test('verify error thrown', async () => {
    const expected = new Error('actual-error');
    const fn = async () => { throw expected; };
    await expect(fn()).rejects.toThrow(expected);
});

// Fails with: Received function did not throw
test('verify non-error thrown', async () => {
    const expected = 'non-error';
    const fn = async () => { throw expected; };
    await expect(fn()).rejects.toThrow(expected);
});
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I don't think you need 'rejects' in either case. According to the docs it's not clear if the toThrow method expects results to be derived from Error. There is a regex form which might validate against a string.

rejects says that it unwraps the rejection so it can be matched, and that might give you the error message string from Error, or a string if the result was a string.

about 4 years ago · Juan Pablo Isaza Relatório

0

Dave's point was absolutely right; using rejects.toThrow was not the right way to go here.

Instead, I'm managed to verify the expected behaviour by simply catching the error and verifying it's value.


test('verify non-error thrown', async () => {
    const expected = 'non-error';
    const fn = async () => { throw expected; };
    await fn().catch(error => expect(error).toStrictEqual(expected));
    expect.assertions(1);
});

Note that expect.assertions(1) is important here. Without this, if the code being tested was updated to not throw, the test would still pass.

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