69 lines
2.2 KiB
TypeScript
69 lines
2.2 KiB
TypeScript
import { describe, expect, it } from "@suaveplan/testing/runner";
|
|
import { SSE_BUN_CODES, SseBunError } from "../error-codes/error-codes.js";
|
|
import {
|
|
encodeComment,
|
|
encodeSseEvent,
|
|
encodeStreamPrologue,
|
|
} from "./sse-stream.js";
|
|
|
|
const dec = (bytes: Uint8Array): string => new TextDecoder().decode(bytes);
|
|
|
|
describe("stream.encodeSseEvent", () => {
|
|
it("emits id, event, data lines for a basic event", () => {
|
|
const out = dec(
|
|
encodeSseEvent(
|
|
{ id: "1", event: "ping", data: "hello" },
|
|
{ maxEventBytes: 1024 }
|
|
)
|
|
);
|
|
expect(out).toBe("id: 1\nevent: ping\ndata: hello\n\n");
|
|
}, 5000);
|
|
|
|
it("omits event line when undefined and includes retry when supplied", () => {
|
|
const out = dec(
|
|
encodeSseEvent(
|
|
{ id: "2", data: "x", retry: 5000 },
|
|
{ maxEventBytes: 1024 }
|
|
)
|
|
);
|
|
expect(out).toBe("id: 2\nretry: 5000\ndata: x\n\n");
|
|
}, 5000);
|
|
|
|
it("splits multi-line data into one data: line per chunk", () => {
|
|
const out = dec(
|
|
encodeSseEvent(
|
|
{ id: "3", data: "a\nb\nc" },
|
|
{ maxEventBytes: 1024 }
|
|
)
|
|
);
|
|
expect(out).toBe("id: 3\ndata: a\ndata: b\ndata: c\n\n");
|
|
}, 5000);
|
|
|
|
it("throws EVENT_TOO_LARGE when encoded bytes exceed cap", () => {
|
|
try {
|
|
encodeSseEvent(
|
|
{ id: "4", data: "x".repeat(1000) },
|
|
{ maxEventBytes: 100 }
|
|
);
|
|
expect.fail("expected throw");
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(SseBunError);
|
|
expect((err as SseBunError).code).toBe(
|
|
SSE_BUN_CODES.EVENT_TOO_LARGE
|
|
);
|
|
}
|
|
}, 5000);
|
|
});
|
|
|
|
describe("stream.encodeStreamPrologue", () => {
|
|
it("emits retry directive then blank line", () => {
|
|
expect(dec(encodeStreamPrologue(3000))).toBe("retry: 3000\n\n");
|
|
}, 5000);
|
|
});
|
|
|
|
describe("stream.encodeComment", () => {
|
|
it("emits a colon-prefixed comment terminated by a blank line", () => {
|
|
expect(dec(encodeComment("keepalive"))).toBe(":keepalive\n\n");
|
|
}, 5000);
|
|
});
|