| 1 | // The parseDataLine function is not exported, so we need to import it |
| 2 | // indirectly by re-exporting it for testing purposes |
| 3 | import { parseDataLine } from "./stream.js"; |
| 4 | |
| 5 | describe("parseDataLine", () => { |
| 6 | test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => { |
| 7 | const line = 'data: {"message":"hello","status":"ok"}'; |
| 8 | const result = parseDataLine(line); |
| 9 | expect(result).toEqual({ message: "hello", status: "ok" }); |
| 10 | }); |
| 11 | |
| 12 | test("parseDataLine should parse valid JSON data with 'data:' prefix (no space)", () => { |
| 13 | const line = 'data:{"message":"hello","status":"ok"}'; |
| 14 | const result = parseDataLine(line); |
| 15 | expect(result).toEqual({ message: "hello", status: "ok" }); |
| 16 | }); |
| 17 | |
| 18 | test("parseDataLine should throw error for malformed JSON", () => { |
| 19 | const line = "data: {invalid json}"; |
| 20 | expect(() => parseDataLine(line)).toThrow( |
| 21 | "Malformed JSON sent from server", |
| 22 | ); |
| 23 | }); |
| 24 | |
| 25 | test("parseDataLine should throw error when data contains error field", () => { |
| 26 | const line = 'data: {"error":"something went wrong"}'; |
| 27 | expect(() => parseDataLine(line)).toThrow( |
| 28 | "Error streaming response: something went wrong", |
| 29 | ); |
| 30 | }); |
| 31 | |
| 32 | test("parseDataLine should handle empty objects", () => { |
| 33 | const line = "data: {}"; |
| 34 | const result = parseDataLine(line); |
| 35 | expect(result).toEqual({}); |
| 36 | }); |
| 37 | |
| 38 | test("parseDataLine should handle arrays", () => { |
| 39 | const line = "data: [1,2,3]"; |
| 40 | const result = parseDataLine(line); |
| 41 | expect(result).toEqual([1, 2, 3]); |
| 42 | }); |
| 43 | |
| 44 | test("parseDataLine should handle nested objects", () => { |
| 45 | const line = 'data: {"user":{"name":"John","age":30}}'; |
| 46 | const result = parseDataLine(line); |
| 47 | expect(result).toEqual({ user: { name: "John", age: 30 } }); |
| 48 | }); |
| 49 | }); |