|
| 1 | +/* sseStream.test.ts — coverage for the SSE-over-fetch consumer. |
| 2 | + * |
| 3 | + * Tests the parser by stubbing global.fetch with a ReadableStream of |
| 4 | + * encoded UTF-8 chunks, then asserting each onLine + onError + onClose |
| 5 | + * branch in turn. |
| 6 | + */ |
| 7 | +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' |
| 8 | +import { streamSSE, SSEStreamError } from './sseStream' |
| 9 | +import { setToken, clearToken } from '../api' |
| 10 | + |
| 11 | +function makeStream(chunks: string[]): ReadableStream<Uint8Array> { |
| 12 | + const enc = new TextEncoder() |
| 13 | + let i = 0 |
| 14 | + return new ReadableStream<Uint8Array>({ |
| 15 | + pull(controller) { |
| 16 | + if (i >= chunks.length) { |
| 17 | + controller.close() |
| 18 | + return |
| 19 | + } |
| 20 | + controller.enqueue(enc.encode(chunks[i++])) |
| 21 | + }, |
| 22 | + }) |
| 23 | +} |
| 24 | + |
| 25 | +function flush(): Promise<void> { |
| 26 | + return new Promise((r) => setTimeout(r, 0)) |
| 27 | +} |
| 28 | + |
| 29 | +describe('SSEStreamError', () => { |
| 30 | + it('carries the HTTP status', () => { |
| 31 | + const e = new SSEStreamError(404) |
| 32 | + expect(e.status).toBe(404) |
| 33 | + expect(e.name).toBe('SSEStreamError') |
| 34 | + expect(e.message).toBe('HTTP 404') |
| 35 | + }) |
| 36 | +}) |
| 37 | + |
| 38 | +describe('streamSSE', () => { |
| 39 | + beforeEach(() => { |
| 40 | + clearToken() |
| 41 | + }) |
| 42 | + afterEach(() => { |
| 43 | + vi.restoreAllMocks() |
| 44 | + }) |
| 45 | + |
| 46 | + it('emits onLine for each `data: <payload>` SSE line and calls onClose at end', async () => { |
| 47 | + const body = makeStream(['data: hello\n', 'data: world\n']) |
| 48 | + const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, body }) |
| 49 | + ;(globalThis as any).fetch = fetchMock |
| 50 | + |
| 51 | + const lines: string[] = [] |
| 52 | + const closed = new Promise<void>((resolve) => { |
| 53 | + streamSSE('/test', { |
| 54 | + onLine: (l) => lines.push(l), |
| 55 | + onClose: resolve, |
| 56 | + }) |
| 57 | + }) |
| 58 | + await closed |
| 59 | + expect(lines).toEqual(['hello', 'world']) |
| 60 | + expect(fetchMock).toHaveBeenCalledTimes(1) |
| 61 | + }) |
| 62 | + |
| 63 | + it('strips only ONE space after `data:` (spec-compliant)', async () => { |
| 64 | + const body = makeStream(['data:no-space\n', 'data: two-spaces\n']) |
| 65 | + ;(globalThis as any).fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, body }) |
| 66 | + |
| 67 | + const lines: string[] = [] |
| 68 | + await new Promise<void>((resolve) => { |
| 69 | + streamSSE('/x', { onLine: (l) => lines.push(l), onClose: resolve }) |
| 70 | + }) |
| 71 | + expect(lines).toEqual(['no-space', ' two-spaces']) |
| 72 | + }) |
| 73 | + |
| 74 | + it('ignores non-data lines (event:, id:, blank)', async () => { |
| 75 | + const body = makeStream([ |
| 76 | + 'event: ping\n', |
| 77 | + ': comment\n', |
| 78 | + '\n', |
| 79 | + 'data: keeper\n', |
| 80 | + ]) |
| 81 | + ;(globalThis as any).fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, body }) |
| 82 | + |
| 83 | + const lines: string[] = [] |
| 84 | + await new Promise<void>((resolve) => { |
| 85 | + streamSSE('/x', { onLine: (l) => lines.push(l), onClose: resolve }) |
| 86 | + }) |
| 87 | + expect(lines).toEqual(['keeper']) |
| 88 | + }) |
| 89 | + |
| 90 | + it('on non-OK response, calls onError with SSEStreamError + onClose', async () => { |
| 91 | + ;(globalThis as any).fetch = vi.fn().mockResolvedValue({ ok: false, status: 503, body: null }) |
| 92 | + |
| 93 | + let err: unknown = null |
| 94 | + let closed = false |
| 95 | + await new Promise<void>((resolve) => { |
| 96 | + streamSSE('/bad', { |
| 97 | + onLine: () => {}, |
| 98 | + onError: (e) => { err = e }, |
| 99 | + onClose: () => { closed = true; resolve() }, |
| 100 | + }) |
| 101 | + }) |
| 102 | + expect(err).toBeInstanceOf(SSEStreamError) |
| 103 | + expect((err as SSEStreamError).status).toBe(503) |
| 104 | + expect(closed).toBe(true) |
| 105 | + }) |
| 106 | + |
| 107 | + it('on 401 mid-open, still surfaces SSEStreamError(401)', async () => { |
| 108 | + ;(globalThis as any).fetch = vi.fn().mockResolvedValue({ ok: false, status: 401, body: null }) |
| 109 | + |
| 110 | + let err: unknown = null |
| 111 | + await new Promise<void>((resolve) => { |
| 112 | + streamSSE('/auth', { |
| 113 | + onLine: () => {}, |
| 114 | + onError: (e) => { err = e }, |
| 115 | + onClose: resolve, |
| 116 | + }) |
| 117 | + }) |
| 118 | + expect((err as SSEStreamError).status).toBe(401) |
| 119 | + }) |
| 120 | + |
| 121 | + it('on thrown fetch (e.g. network error), calls onError + onClose', async () => { |
| 122 | + ;(globalThis as any).fetch = vi.fn().mockRejectedValue(new Error('network down')) |
| 123 | + |
| 124 | + let err: unknown = null |
| 125 | + let closed = false |
| 126 | + await new Promise<void>((resolve) => { |
| 127 | + streamSSE('/x', { |
| 128 | + onLine: () => {}, |
| 129 | + onError: (e) => { err = e }, |
| 130 | + onClose: () => { closed = true; resolve() }, |
| 131 | + }) |
| 132 | + }) |
| 133 | + expect((err as Error).message).toBe('network down') |
| 134 | + expect(closed).toBe(true) |
| 135 | + }) |
| 136 | + |
| 137 | + it('suppresses AbortError so the caller does not see spurious errors', async () => { |
| 138 | + const ab = new Error('abort') |
| 139 | + ab.name = 'AbortError' |
| 140 | + ;(globalThis as any).fetch = vi.fn().mockRejectedValue(ab) |
| 141 | + |
| 142 | + const errors: unknown[] = [] |
| 143 | + let closed = false |
| 144 | + await new Promise<void>((resolve) => { |
| 145 | + streamSSE('/x', { |
| 146 | + onLine: () => {}, |
| 147 | + onError: (e) => errors.push(e), |
| 148 | + onClose: () => { closed = true; resolve() }, |
| 149 | + }) |
| 150 | + }) |
| 151 | + expect(errors).toEqual([]) |
| 152 | + expect(closed).toBe(true) |
| 153 | + }) |
| 154 | + |
| 155 | + it('attaches Authorization header when a token is set', async () => { |
| 156 | + setToken('test-bearer-123') |
| 157 | + const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, body: makeStream([]) }) |
| 158 | + ;(globalThis as any).fetch = fetchMock |
| 159 | + |
| 160 | + await new Promise<void>((resolve) => { |
| 161 | + streamSSE('/x', { onLine: () => {}, onClose: resolve }) |
| 162 | + }) |
| 163 | + const opts = fetchMock.mock.calls[0][1] |
| 164 | + expect(opts.headers.Authorization).toBe('Bearer test-bearer-123') |
| 165 | + expect(opts.headers.Accept).toBe('text/event-stream') |
| 166 | + clearToken() |
| 167 | + }) |
| 168 | + |
| 169 | + it('does NOT attach Authorization header when no token is set', async () => { |
| 170 | + clearToken() |
| 171 | + const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, body: makeStream([]) }) |
| 172 | + ;(globalThis as any).fetch = fetchMock |
| 173 | + |
| 174 | + await new Promise<void>((resolve) => { |
| 175 | + streamSSE('/x', { onLine: () => {}, onClose: resolve }) |
| 176 | + }) |
| 177 | + const opts = fetchMock.mock.calls[0][1] |
| 178 | + expect(opts.headers.Authorization).toBeUndefined() |
| 179 | + }) |
| 180 | + |
| 181 | + it('returns a cleanup function that aborts the AbortController', async () => { |
| 182 | + // No need to await — just verify the callable contract. |
| 183 | + ;(globalThis as any).fetch = vi.fn(() => new Promise(() => {})) |
| 184 | + const cleanup = streamSSE('/x', { onLine: () => {} }) |
| 185 | + expect(typeof cleanup).toBe('function') |
| 186 | + cleanup() // does not throw |
| 187 | + await flush() |
| 188 | + }) |
| 189 | + |
| 190 | + it('honors an external AbortSignal — aborting it aborts the compound', async () => { |
| 191 | + ;(globalThis as any).fetch = vi.fn(() => new Promise(() => {})) |
| 192 | + const ctl = new AbortController() |
| 193 | + const cleanup = streamSSE('/x', { onLine: () => {} }, ctl.signal) |
| 194 | + expect(typeof cleanup).toBe('function') |
| 195 | + ctl.abort() |
| 196 | + // Just verify no throw + cleanup still callable. |
| 197 | + cleanup() |
| 198 | + await flush() |
| 199 | + }) |
| 200 | +}) |
0 commit comments