|
| 1 | +import { describe, expect, test, beforeEach, jest } from "@jest/globals"; |
| 2 | + |
| 3 | +import { loadResource } from "./resource-loader"; |
| 4 | +import type { ResourceRequest } from "./schema/resources"; |
| 5 | + |
| 6 | +// Mock the fetch function |
| 7 | + |
| 8 | +describe("loadResource", () => { |
| 9 | + let mockFetch: jest.Mock<typeof fetch>; |
| 10 | + |
| 11 | + beforeEach(() => { |
| 12 | + mockFetch = jest.fn(); |
| 13 | + jest.clearAllMocks(); |
| 14 | + }); |
| 15 | + |
| 16 | + test("should successfully fetch a resource and return a JSON response", async () => { |
| 17 | + const mockResponse = new Response(JSON.stringify({ key: "value" }), { |
| 18 | + status: 200, |
| 19 | + }); |
| 20 | + mockFetch.mockResolvedValue(mockResponse); |
| 21 | + |
| 22 | + const resourceRequest: ResourceRequest = { |
| 23 | + id: "1", |
| 24 | + name: "resource", |
| 25 | + url: "https://example.com/resource", |
| 26 | + method: "get", |
| 27 | + headers: [], |
| 28 | + body: undefined, |
| 29 | + }; |
| 30 | + |
| 31 | + const result = await loadResource(mockFetch, resourceRequest); |
| 32 | + |
| 33 | + expect(mockFetch).toHaveBeenCalledWith("https://example.com/resource", { |
| 34 | + method: "get", |
| 35 | + headers: new Headers(), |
| 36 | + }); |
| 37 | + |
| 38 | + expect(result).toEqual({ |
| 39 | + data: { |
| 40 | + key: "value", |
| 41 | + }, |
| 42 | + ok: true, |
| 43 | + status: 200, |
| 44 | + statusText: "", |
| 45 | + }); |
| 46 | + }); |
| 47 | + |
| 48 | + test("should fetch resource successfully with non-JSON response", async () => { |
| 49 | + const mockResponse = new Response("nonjson", { |
| 50 | + status: 200, |
| 51 | + }); |
| 52 | + mockFetch.mockResolvedValue(mockResponse); |
| 53 | + |
| 54 | + const resourceRequest: ResourceRequest = { |
| 55 | + id: "1", |
| 56 | + name: "resource", |
| 57 | + url: "https://example.com/resource", |
| 58 | + method: "get", |
| 59 | + headers: [], |
| 60 | + body: undefined, |
| 61 | + }; |
| 62 | + |
| 63 | + const result = await loadResource(mockFetch, resourceRequest); |
| 64 | + |
| 65 | + expect(mockFetch).toHaveBeenCalledWith("https://example.com/resource", { |
| 66 | + method: "get", |
| 67 | + headers: new Headers(), |
| 68 | + }); |
| 69 | + |
| 70 | + expect(result).toEqual({ |
| 71 | + data: "nonjson", |
| 72 | + ok: true, |
| 73 | + status: 200, |
| 74 | + statusText: "", |
| 75 | + }); |
| 76 | + }); |
| 77 | +}); |
0 commit comments