Files
kuber/tests/lib/api-stream.test.ts
T

68 lines
2.2 KiB
TypeScript

import { afterEach, expect, test } from "bun:test";
import { apiStreamEvents, ApiStreamUnsupportedError } from "../../lib/api";
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
test("parses split UTF-8 SSE frames, comments and ids with authenticated request", async () => {
let headers: Headers | undefined;
const versions: Array<string | null> = [];
globalThis.fetch = (async (
_url: string | URL | Request,
init?: RequestInit,
) => {
headers = new Headers(init?.headers);
const bytes = new TextEncoder().encode(
': ping\r\nid: 3\r\nevent: log\r\ndata: {"type":"log","message":"hé"}\r\n\r\nevent: status\ndata: {"type":"status"}\n\n',
);
return new Response(
new ReadableStream({
start(controller) {
for (let i = 0; i < bytes.length; i += 2)
controller.enqueue(bytes.slice(i, i + 2));
controller.close();
},
}),
{
headers: {
"content-type": "text/event-stream",
"x-kuber-version": "2.6.1-rc5",
},
},
);
}) as unknown as typeof fetch;
const events = [];
for await (const event of apiStreamEvents("/builds/a/events", 2, undefined, {
baseUrl: "https://test",
session: { token: "secret" } as never,
onServerVersion: (value) => versions.push(value),
}))
events.push(event);
expect(headers?.get("authorization")).toBe("Bearer secret");
expect(headers?.get("last-event-id")).toBe("2");
expect(versions).toEqual(["2.6.1-rc5"]);
expect(events).toEqual([
{ id: 3, event: { type: "log", message: "hé" } },
{ id: undefined, event: { type: "status" } },
]);
});
test("identifies existing JSON-only servers without parsing their response as SSE", async () => {
globalThis.fetch = (async () =>
new Response("[]", {
headers: { "content-type": "application/json" },
})) as unknown as typeof fetch;
await expect(
(async () => {
for await (const _ of apiStreamEvents("/builds/a/events", 0, undefined, {
baseUrl: "https://test",
session: { token: "secret" } as never,
})) {
/* consume */
}
})(),
).rejects.toBeInstanceOf(ApiStreamUnsupportedError);
});