|
| 1 | +import { |
| 2 | + describe, |
| 3 | + it, |
| 4 | + vi, |
| 5 | + expect, |
| 6 | + beforeEach, |
| 7 | + afterEach, |
| 8 | + type Mock, |
| 9 | +} from "vitest"; |
| 10 | +import { fetchContributions } from "./fetchContributions"; |
| 11 | + |
| 12 | +describe("fetchContributions", () => { |
| 13 | + beforeEach(() => { |
| 14 | + // Mock the global fetch function |
| 15 | + globalThis.fetch = vi.fn(); |
| 16 | + }); |
| 17 | + |
| 18 | + afterEach(() => { |
| 19 | + // Restore the original fetch implementation |
| 20 | + vi.restoreAllMocks(); |
| 21 | + }); |
| 22 | + |
| 23 | + it("should return expected data on success", async () => { |
| 24 | + // Define a mock response |
| 25 | + const expectedResult = { |
| 26 | + extensions: [{ name: "e0", version: "1", contributes: ["panels"] }], |
| 27 | + contributions: { |
| 28 | + panels: [{ name: "p0", extension: "e0", layout: {} }], |
| 29 | + }, |
| 30 | + }; |
| 31 | + const mockResponse = { |
| 32 | + ok: true, |
| 33 | + status: 200, |
| 34 | + statusText: "ok", |
| 35 | + json: vi.fn().mockResolvedValue({ |
| 36 | + result: expectedResult, |
| 37 | + }), |
| 38 | + }; |
| 39 | + |
| 40 | + // Mock fetch to resolve with the mock response |
| 41 | + (globalThis.fetch as Mock).mockResolvedValue(mockResponse); |
| 42 | + |
| 43 | + // Call fetch |
| 44 | + const response = await fetchContributions({ |
| 45 | + serverUrl: "https://chartlets-test", |
| 46 | + endpointName: "api", |
| 47 | + }); |
| 48 | + |
| 49 | + // Assertions |
| 50 | + expect(fetch).toHaveBeenCalledOnce(); |
| 51 | + expect(response).toEqual({ |
| 52 | + status: "ok", |
| 53 | + data: { |
| 54 | + extensions: [{ name: "e0", version: "1", contributes: ["panels"] }], |
| 55 | + contributions: { |
| 56 | + panels: [ |
| 57 | + { |
| 58 | + name: "p0", |
| 59 | + extension: "e0", |
| 60 | + layout: { inputs: [], outputs: [] }, |
| 61 | + callbacks: [], |
| 62 | + }, |
| 63 | + ], |
| 64 | + }, |
| 65 | + }, |
| 66 | + }); |
| 67 | + }); |
| 68 | + |
| 69 | + it("should return error for bad responses", async () => { |
| 70 | + // Define a mock response |
| 71 | + const mockResponse = { |
| 72 | + ok: true, |
| 73 | + status: 200, |
| 74 | + statusText: "ok", |
| 75 | + json: vi.fn().mockResolvedValue({ message: "Hello, world!" }), |
| 76 | + }; |
| 77 | + |
| 78 | + // Mock fetch to resolve with the mock response |
| 79 | + (globalThis.fetch as Mock).mockResolvedValue(mockResponse); |
| 80 | + |
| 81 | + // Call fetch |
| 82 | + const response = await fetchContributions({ |
| 83 | + serverUrl: "https://chartlets-test", |
| 84 | + endpointName: "api", |
| 85 | + }); |
| 86 | + // Assertions |
| 87 | + expect(fetch).toHaveBeenCalledOnce(); |
| 88 | + expect(response).toEqual({ |
| 89 | + status: "failed", |
| 90 | + error: { |
| 91 | + message: |
| 92 | + "unexpected response from https://chartlets-test/api/contributions", |
| 93 | + }, |
| 94 | + }); |
| 95 | + }); |
| 96 | +}); |
0 commit comments