Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/modules/chat/client/chatTokenProvider.test.ts
T

42 lines
2.0 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { buildChatWebSocketUrl, createChatTokenProvider } from "./chatTokenProvider";
describe("chatTokenProvider", () => {
it("builds the gateway URL from the configured API host with the fixed chat path", () => {
expect(buildChatWebSocketUrl({ protocol: "https", apiHost: "api.example.test" })).toBe("wss://api.example.test/ws/chat");
expect(buildChatWebSocketUrl({ protocol: "http", apiHost: "api.localhost:3000" })).toBe("ws://api.localhost:3000/ws/chat");
expect(() => buildChatWebSocketUrl({ protocol: "https", apiHost: "api.example.test/not-allowed" })).toThrow();
});
it("requests a same-origin no-store token with header-only CSRF", async () => {
const fetchImpl = vi.fn(async () => Response.json({ ok: true, data: { token: "header.payload.signature", expiresIn: 300, refreshAfter: 240 } }));
const provider = createChatTokenProvider({ tenantSlug: "hivegrid demo", csrfToken: "csrf-token", fetchImpl });
await expect(provider({ reconnectAttempt: 2 })).resolves.toBe("header.payload.signature");
expect(fetchImpl).toHaveBeenCalledWith("/hivegrid%20demo/chat/token", {
method: "POST",
headers: { accept: "application/json", "x-csrf-token": "csrf-token" },
credentials: "same-origin",
cache: "no-store",
redirect: "error",
});
});
it("rejects failed and malformed token responses without exposing their bodies", async () => {
const failed = createChatTokenProvider({
tenantSlug: "tenant",
csrfToken: "csrf",
fetchImpl: async () => new Response("secret upstream detail", { status: 503 }),
});
await expect(failed({ reconnectAttempt: 0 })).rejects.toThrow("Chat gateway token could not be loaded.");
const malformed = createChatTokenProvider({
tenantSlug: "tenant",
csrfToken: "csrf",
fetchImpl: async () => Response.json({ ok: true, data: { token: " padded " } }),
});
await expect(malformed({ reconnectAttempt: 0 })).rejects.toThrow("Chat gateway token response was invalid.");
});
});