stream.test.ts77 lines, 2.2 KB
| 1 | import { afterEach, expect, test, vi } from 'vitest' |
| 2 | import { listen, parser, type LiveEvent } from './stream' |
| 3 | |
| 4 | test.each([ |
| 5 | [ |
| 6 | 'one event', |
| 7 | ['id: 7\nevent: like\ndata: {"a":1}\n\n'], |
| 8 | ['7 like {"a":1}'], |
| 9 | ], |
| 10 | [ |
| 11 | 'split anywhere', |
| 12 | ['id: 7\nevent: li', 'ke\ndata: {"a"', ':1}\n', '\n'], |
| 13 | ['7 like {"a":1}'], |
| 14 | ], |
| 15 | ['comments are not events', [': connected\n\n: still here\n\n'], []], |
| 16 | ['no id', ['event: post\ndata: {}\n\n'], [' post {}']], |
| 17 | [ |
| 18 | 'two at once', |
| 19 | ['data: a\n\ndata: b\n\n'], |
| 20 | [' message a', ' message b'], |
| 21 | ], |
| 22 | ['CRLF', ['event: post\r\ndata: x\r\n\r\n'], [' post x']], |
| 23 | ['not finished yet', ['data: a\n'], []], |
| 24 | ])('parser: %s', (_name, chunks, want) => { |
| 25 | const got: string[] = [] |
| 26 | const parse = parser((e) => got.push(`${e.id} ${e.event} ${e.data}`)) |
| 27 | chunks.forEach(parse) |
| 28 | expect(got).toEqual(want) |
| 29 | }) |
| 30 | |
| 31 | afterEach(() => { |
| 32 | vi.unstubAllGlobals() |
| 33 | vi.useRealTimers() |
| 34 | }) |
| 35 | |
| 36 | // A response whose body is these chunks, and then the end. |
| 37 | const stream = (...chunks: string[]) => |
| 38 | new Response( |
| 39 | new ReadableStream({ |
| 40 | start(c) { |
| 41 | chunks.forEach((s) => c.enqueue(new TextEncoder().encode(s))) |
| 42 | c.close() |
| 43 | }, |
| 44 | }), |
| 45 | ) |
| 46 | |
| 47 | test('listen comes back after a break, with Last-Event-ID', async () => { |
| 48 | vi.useFakeTimers() |
| 49 | const answers = [ |
| 50 | stream('id: 41\nevent: like\ndata: {}\n\n'), |
| 51 | new Response(null, { status: 502 }), |
| 52 | stream('id: 42\nevent: like\ndata: {}\n\n'), |
| 53 | ] |
| 54 | const sent: (string | undefined)[] = [] |
| 55 | const fetch = vi.fn(async (_url: string, init: RequestInit) => { |
| 56 | sent.push((init.headers as Record<string, string>)['Last-Event-ID']) |
| 57 | return answers.shift() ?? stream() |
| 58 | }) |
| 59 | vi.stubGlobal('fetch', fetch) |
| 60 | const events: LiveEvent[] = [] |
| 61 | const statuses: string[] = [] |
| 62 | const stop = new AbortController() |
| 63 | |
| 64 | listen( |
| 65 | 't', |
| 66 | (e) => events.push(e), |
| 67 | (s) => statuses.push(s), |
| 68 | stop.signal, |
| 69 | ) |
| 70 | await vi.advanceTimersByTimeAsync(1500) // the first wait: 1 s |
| 71 | await vi.advanceTimersByTimeAsync(2500) // after a failure: 2 s |
| 72 | stop.abort() |
| 73 | |
| 74 | expect(events.map((e) => e.id)).toEqual(['41', '42']) |
| 75 | expect(statuses).toEqual(['live', 'away', 'away', 'live', 'away']) |
| 76 | expect(sent.slice(0, 3)).toEqual([undefined, '41', '41']) |
| 77 | }) |