Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 1.7 KiBRawPermalink
1import { Readable } from "stream";
2import { streamSse } from "./stream";
3
4function createMockResponse(sseLines: string[]): Response {
5 // Create a Readable stream that emits the SSE lines
6 const stream = new Readable({
7 read() {
8 for (const line of sseLines) {
9 this.push(line + "\n\n");
10 }
11 this.push(null); // End of stream
12 }
13 }) as any;
14
15 // Minimal Response mock
16 return {
17 status: 200,
18 body: stream,
19 text: async () => "",
20 } as unknown as Response;
21}
22
23describe("streamSse", () => {
24 it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
25 const sseLines = [
26 'data: {"foo": "bar"}',
27 'data: {"baz": 42}',
28 'data:[DONE]'
29 ];
30 const response = createMockResponse(sseLines);
31
32 const results = [];
33 for await (const data of streamSse(response)) {
34 results.push(data);
35 }
36
37 expect(results).toEqual([
38 { foo: "bar" },
39 { baz: 42 }
40 ]);
41 });
42
43 it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
44 const sseLines = [
45 'data: {"foo": "bar"}',
46 'data: {"baz": 42}',
47 'data: [DONE]'
48 ];
49 const response = createMockResponse(sseLines);
50
51 const results = [];
52 for await (const data of streamSse(response)) {
53 results.push(data);
54 }
55
56 expect(results).toEqual([
57 { foo: "bar" },
58 { baz: 42 }
59 ]);
60 });
61
62 it("throws on malformed JSON", async () => {
63 const sseLines = [
64 'data: {"foo": "bar"',
65 'data:[DONE]'
66 ];
67 const response = createMockResponse(sseLines);
68
69 const iterator = streamSse(response)[Symbol.asyncIterator]();
70 await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
71 });
72});