Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!