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

120
Visualizações
testing an exception in jest that returns a promise immediately resolved

I have an error handling function that wraps fetch calls and allows me to handle errors without so many try / catch blocks.

    const errorHandler = (promise) =>
        promise
            .then((data) => ({ ok: true, data }))
            .catch((error) => Promise.resolve({ ok: false, error }));

I am trying to add a test to this function with jest, I have service workers that intercept the fetch requests and generate a mock response that are working fine but it seems that with jest I am not understanding how to test it because the function captures the catch but returns a new promise immediately resolved.

this is the way i'm trying to test:

test("It should return result.ok === false", async () => {
    // this function works correctly with the msw library
    server.use(
      rest.get("http://localhost:3001/categories", (req, res, ctx) => {
        return res(ctx.status(500));
      })
    );

    return await expect(
      errorHandler((await fetch("http://localhost:3001/categories")).json())
    ).rejects.toEqual({"error": "[SyntaxError: Unexpected end of JSON input]", "ok": false});
  });
});

I have tried to test with toEqual(value) and .toMatchObject(object) but the test does not pass and this is the output.

    ● Tests in errorHandler() › It should return result.ok === false
                                                                                                                               
        expect(received).rejects.toEqual()                                                                                         
                                                                                                                               
        Received promise resolved instead of rejected                                                                              
        Resolved to value: {"error": [SyntaxError: Unexpected end of JSON input], "ok": false}  

thanks in advance.

about 4 years ago · Santiago Gelvez
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