Files
auth-remote-react/src/shared/utils/helpers/callApi/callApi.spec.ts

41 lines
1.2 KiB
TypeScript

import { HTTPError } from "ky";
import { callApi } from "./callApi";
function makeHttpError(status: number, body: object) {
const response = new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
return new HTTPError(response, new Request("http://test.com"), {});
}
describe("callApi", () => {
describe("happy path", () => {
it("returns [data, null] when the fn resolves", async () => {
const [data, error] = await callApi(() => Promise.resolve({ id: 1 }));
expect(data).toEqual({ id: 1 });
expect(error).toBeNull();
});
});
describe("error cases", () => {
it("returns [null, ApiError] on HTTPError", async () => {
const [data, error] = await callApi(() =>
Promise.reject(makeHttpError(401, { message: "Unauthorized" })),
);
expect(data).toBeNull();
expect(error).toEqual({ status: 401, message: "Unauthorized" });
});
it("re-throws non-HTTP errors", async () => {
const unexpected = new TypeError("Network failure");
await expect(
callApi(() => Promise.reject(unexpected)),
).rejects.toThrow("Network failure");
});
});
});