53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { proxyToBackend } from "../src/proxy";
|
|
|
|
describe("proxyToBackend", () => {
|
|
const MOCK_BASE_URL = "http://localhost:3000";
|
|
const MOCK_API_KEY = "test-key";
|
|
|
|
beforeEach(() => {
|
|
vi.resetAllMocks();
|
|
});
|
|
|
|
it("should make a POST request with correct headers and body", async () => {
|
|
const mockResponse = { success: true, data: "test" };
|
|
globalThis.fetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => mockResponse,
|
|
});
|
|
|
|
const payload = { test: 123 };
|
|
const result = await proxyToBackend("/api/test", payload, MOCK_BASE_URL, MOCK_API_KEY);
|
|
|
|
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
|
|
expect(globalThis.fetch).toHaveBeenCalledWith("http://localhost:3000/api/test", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: "Bearer test-key",
|
|
},
|
|
body: JSON.stringify(payload),
|
|
});
|
|
|
|
expect(result).toEqual(mockResponse);
|
|
});
|
|
|
|
it("should throw an error if API_BASE_URL is not provided", async () => {
|
|
await expect(proxyToBackend("/api/test", {}, "", MOCK_API_KEY)).rejects.toThrow(
|
|
"API_BASE_URL is not configured."
|
|
);
|
|
});
|
|
|
|
it("should throw an error if response is not ok", async () => {
|
|
globalThis.fetch = vi.fn().mockResolvedValue({
|
|
ok: false,
|
|
status: 500,
|
|
text: async () => "Internal Server Error",
|
|
});
|
|
|
|
await expect(
|
|
proxyToBackend("/api/test", {}, MOCK_BASE_URL, MOCK_API_KEY)
|
|
).rejects.toThrow("Backend error (500): Internal Server Error");
|
|
});
|
|
});
|