import { test } from "node:test"; import assert from "node:assert/strict"; import { connectionAfterError, openStream, } from "../src/ui/stream/connection.ts"; test("connectionAfterError: the browser still retrying is reconnecting", () => { assert.equal(connectionAfterError(0), "reconnecting"); }); test("connectionAfterError: a given-up stream is closed", () => { assert.equal(connectionAfterError(2), "closed"); }); test("connectionAfterError: an open readyState on error is also closed", () => { assert.equal(connectionAfterError(1), "closed"); }); // A fake event source the test drives by hand. function fakeStream() { const source = { onopen: null, onmessage: null, onerror: null, readyState: 0, closed: false, close() { this.closed = true; }, }; const seen = { states: [], opened: 0, messages: [], gaveUp: 0, urls: [] }; const close = openStream({ url: "/s", makeSource: (url) => { seen.urls.push(url); return source; }, onState: (s) => seen.states.push(s), onOpen: () => seen.opened++, onMessage: (d) => seen.messages.push(d), onGaveUp: () => seen.gaveUp++, }); return { source, seen, close }; } test("openStream: opens the url, and open reports the state and runs onOpen", () => { const { source, seen } = fakeStream(); assert.deepEqual(seen.urls, ["/s"]); source.onopen(); assert.deepEqual(seen.states, ["open"]); assert.equal(seen.opened, 1); }); test("openStream: a message reaches onMessage as its text", () => { const { source, seen } = fakeStream(); source.onmessage({ data: '{"a":1}' }); assert.deepEqual(seen.messages, ['{"a":1}']); }); test("openStream: an error while the browser retries is reconnecting and not given up", () => { const { source, seen } = fakeStream(); source.readyState = 0; source.onerror(); assert.deepEqual(seen.states, ["reconnecting"]); assert.equal(seen.gaveUp, 0); }); test("openStream: an error after the browser gave up is closed and runs onGaveUp", () => { const { source, seen } = fakeStream(); source.readyState = 2; source.onerror(); assert.deepEqual(seen.states, ["closed"]); assert.equal(seen.gaveUp, 1); }); test("openStream: the returned function closes the source", () => { const { source, close } = fakeStream(); close(); assert.equal(source.closed, true); });