39 lines
1.5 KiB
TypeScript
39 lines
1.5 KiB
TypeScript
import { test, expect } from "bun:test";
|
|
import { streamResponse, sse } from "../src/index.ts";
|
|
|
|
test("streamResponse streams a sync iterable of strings as HTML", async () => {
|
|
const res = streamResponse(["<h1>", "Hello", "</h1>"]);
|
|
expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");
|
|
expect(await res.text()).toBe("<h1>Hello</h1>");
|
|
});
|
|
|
|
test("streamResponse streams an async generator (streaming SSR shell + body)", async () => {
|
|
async function* page() {
|
|
yield '<!doctype html><body><div id="app">';
|
|
yield "<p>content</p>";
|
|
yield "</div></body>";
|
|
}
|
|
const res = streamResponse(page(), { status: 200 });
|
|
const text = await res.text();
|
|
expect(text).toContain('<div id="app">');
|
|
expect(text).toContain("<p>content</p>");
|
|
});
|
|
|
|
test("streamResponse honours custom content-type and status", async () => {
|
|
const res = streamResponse(["plain"], { contentType: "text/plain", status: 201 });
|
|
expect(res.status).toBe(201);
|
|
expect(res.headers.get("content-type")).toBe("text/plain");
|
|
});
|
|
|
|
test("sse formats Server-Sent Events frames", async () => {
|
|
async function* events() {
|
|
yield { data: "hello", event: "greeting", id: "1" };
|
|
yield { data: "line1\nline2", retry: 3000 };
|
|
}
|
|
const res = sse(events());
|
|
expect(res.headers.get("content-type")).toBe("text/event-stream");
|
|
const text = await res.text();
|
|
expect(text).toContain("event: greeting\nid: 1\ndata: hello\n\n");
|
|
expect(text).toContain("retry: 3000\ndata: line1\ndata: line2\n\n");
|
|
});
|