|
| 1 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest' |
| 2 | +import { registerWorker } from '../src/iii' |
| 3 | +import type { IIIConnectionState } from '../src/iii-constants' |
| 4 | +import type { ISdk } from '../src/types' |
| 5 | +import { MockEngine } from './mock-websocket' |
| 6 | + |
| 7 | +describe('addConnectionStateListener', () => { |
| 8 | + let engine: MockEngine |
| 9 | + let sdk: ISdk |
| 10 | + |
| 11 | + beforeEach(() => { |
| 12 | + engine = new MockEngine() |
| 13 | + engine.install() |
| 14 | + sdk = registerWorker('ws://test:49135') |
| 15 | + }) |
| 16 | + |
| 17 | + afterEach(async () => { |
| 18 | + await sdk.shutdown() |
| 19 | + engine.uninstall() |
| 20 | + }) |
| 21 | + |
| 22 | + it('returns an unsubscribe function', () => { |
| 23 | + const unsub = sdk.addConnectionStateListener(() => {}) |
| 24 | + expect(typeof unsub).toBe('function') |
| 25 | + }) |
| 26 | + |
| 27 | + it('fires immediately with the current state on subscribe', () => { |
| 28 | + const states: IIIConnectionState[] = [] |
| 29 | + sdk.addConnectionStateListener((s) => states.push(s)) |
| 30 | + expect(states.length).toBeGreaterThanOrEqual(1) |
| 31 | + expect(['connecting', 'connected', 'disconnected', 'reconnecting', 'failed']).toContain(states[0]) |
| 32 | + }) |
| 33 | + |
| 34 | + it('multiple listeners receive same events', async () => { |
| 35 | + const a: IIIConnectionState[] = [] |
| 36 | + const b: IIIConnectionState[] = [] |
| 37 | + sdk.addConnectionStateListener((s) => a.push(s)) |
| 38 | + sdk.addConnectionStateListener((s) => b.push(s)) |
| 39 | + |
| 40 | + // Trigger a transition by waiting for the open event the engine schedules. |
| 41 | + await engine.waitForOpen() |
| 42 | + |
| 43 | + expect(a.length).toBe(b.length) |
| 44 | + expect(a[0]).toBe(b[0]) |
| 45 | + if (a.length > 1) { |
| 46 | + expect(a).toEqual(b) |
| 47 | + } |
| 48 | + }) |
| 49 | + |
| 50 | + it('unsubscribe stops further calls', async () => { |
| 51 | + const calls: IIIConnectionState[] = [] |
| 52 | + const unsub = sdk.addConnectionStateListener((s) => calls.push(s)) |
| 53 | + |
| 54 | + await engine.waitForOpen() |
| 55 | + const beforeUnsub = calls.length |
| 56 | + |
| 57 | + unsub() |
| 58 | + |
| 59 | + // Trigger another transition (close should drive a state change). |
| 60 | + engine.socket.simulateClose() |
| 61 | + |
| 62 | + expect(calls.length).toBe(beforeUnsub) |
| 63 | + }) |
| 64 | + |
| 65 | + it('emits transitions through connecting -> connected', async () => { |
| 66 | + const states: IIIConnectionState[] = [] |
| 67 | + sdk.addConnectionStateListener((s) => states.push(s)) |
| 68 | + |
| 69 | + await engine.waitForOpen() |
| 70 | + |
| 71 | + // Should have observed at minimum the initial state and a transition to connected. |
| 72 | + expect(states).toContain('connected') |
| 73 | + }) |
| 74 | +}) |
0 commit comments