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.