logos-storage-js/src/fetch-safe/fetch-safe.test.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-09-13 19:45:59 +02:00
import { afterEach, assert, describe, it, vi } from "vitest";
2024-08-15 12:08:45 +02:00
import { Fetch } from "../fetch-safe/fetch-safe";
2024-09-27 17:35:50 +02:00
import { CodexError } from "../async";
2024-08-15 12:08:15 +02:00
2024-08-15 12:08:51 +02:00
describe.only("fetch", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("returns an error when the http call failed", async () => {
2024-09-13 20:01:05 +02:00
const mockResponse = {
ok: false,
status: 500,
text: async () => "error",
} as Response;
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
2024-08-15 12:08:15 +02:00
2024-08-15 12:08:51 +02:00
const result = await Fetch.safeJson("http://localhost:3000/some-url", {
2024-08-15 12:08:45 +02:00
method: "GET",
2024-08-15 12:08:15 +02:00
});
2024-08-15 12:08:51 +02:00
2024-09-27 17:35:50 +02:00
const error = new CodexError("error", {
2024-08-15 12:08:51 +02:00
code: 500,
2024-09-27 17:35:50 +02:00
});
2024-08-15 12:08:45 +02:00
assert.deepStrictEqual(result, { error: true, data: error });
});
it.only("returns an error when the json parsing failed", async () => {
2024-09-13 20:01:05 +02:00
const mockResponse = {
ok: true,
status: 200,
json: async () => {
return JSON.parse("{error");
},
} as any;
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
2024-08-15 12:08:45 +02:00
2024-08-15 12:08:51 +02:00
const result = await Fetch.safeJson("http://localhost:3000/some-url", {
2024-08-15 12:08:45 +02:00
method: "GET",
2024-08-15 12:08:15 +02:00
});
2024-08-15 12:08:45 +02:00
2024-08-15 12:08:51 +02:00
assert.ok(result.error);
2024-08-15 12:08:45 +02:00
});
it("returns the data when the fetch succeed", async () => {
2024-09-13 20:01:05 +02:00
const mockResponse = {
ok: true,
status: 200,
json: async () => ({
hello: "world",
}),
} as Response;
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse);
2024-08-15 12:08:45 +02:00
2024-08-15 12:08:51 +02:00
const result = await Fetch.safeJson("http://localhost:3000/some-url", {
2024-08-15 12:08:45 +02:00
method: "GET",
});
assert.deepStrictEqual(result, { error: false, data: { hello: "world" } });
});
2024-08-15 12:08:15 +02:00
});