Files
vue-chat-layer/app/lib/realtime.test.ts
Jakub Zych b6d3389e46 test: the SPA's chat tests on the port, client, store and link embeds
- vitest runs app/**/*.test.ts and tests/**/*.test.ts; the SPA's
  chatEvents, chatFormat, chatText, chatUnread and realtime tests sit next
  to their ports with only import paths changed
- linkEmbeds: escaping, http(s) only, rel and target, registry order
- client: every endpoint, refresh-and-retry, unauthorized, 422, upload
- store: bootstrap, anonymous and non-member starts, lazy joins, DMs,
  live messages and unread, threads, pins, reactions, slash commands,
  polling without realtime, onUserEvent, DM-only actions
2026-11-01 19:17:42 +01:00

288 lines
10 KiB
TypeScript

// bm's src/lib/realtime.test.ts against the layer's port (./realtime), as
// the demo site runs it through its re-export. The client fetches its
// connection token from /api/realtime/token itself, so the token route is a stubbed fetch that
// answers what hoisted.request resolves (200) or the status of the ApiError
// it rejects with, instead of a mocked API client; a refusal surfaces as the
// layer's RealtimeTokenError with that status.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from '@/api/http'
type Listener = (ctx: unknown) => void
interface FakeSub {
channel: string
state: string
subscribeCalls: number
unsubscribed: boolean
presence: ReturnType<typeof vi.fn>
emit(event: string, ctx?: unknown): void
}
interface FakeClient {
connectCalls: number
disconnectCalls: number
subs: Map<string, FakeSub>
newSubscriptionCalls: number
emit(event: string, ctx?: unknown): void
}
const hoisted = vi.hoisted(() => {
class FakeUnauthorizedError extends Error {}
return {
request: vi.fn(),
getToken: null as null | (() => Promise<string>),
FakeUnauthorizedError,
created: [] as unknown[],
presenceFn: () => vi.fn(async () => ({ clients: {} as Record<string, unknown> })),
}
})
async function tokenRoute(path: string): Promise<Response> {
try {
const body = await hoisted.request(path)
return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } })
} catch (e) {
return new Response(JSON.stringify({ error: String((e as Error).message) }), { status: e instanceof ApiError ? e.status : 500 })
}
}
vi.mock('centrifuge', () => {
class Emitter {
listeners = new Map<string, Listener[]>()
on(event: string, fn: Listener) {
this.listeners.set(event, [...(this.listeners.get(event) ?? []), fn])
return this
}
emit(event: string, ctx: unknown = {}) {
for (const fn of this.listeners.get(event) ?? []) fn(ctx)
}
removeAllListeners() {
this.listeners.clear()
}
}
class Subscription extends Emitter {
state = 'unsubscribed'
subscribeCalls = 0
unsubscribed = false
presence = hoisted.presenceFn()
constructor(public channel: string) {
super()
}
subscribe() {
this.subscribeCalls++
}
unsubscribe() {
this.unsubscribed = true
}
}
class Centrifuge extends Emitter {
subs = new Map<string, Subscription>()
connectCalls = 0
disconnectCalls = 0
newSubscriptionCalls = 0
constructor(_url: string, opts: { getToken: () => Promise<string> }) {
super()
hoisted.getToken = opts.getToken
hoisted.created.push(this)
}
newSubscription(channel: string) {
this.newSubscriptionCalls++
const s = new Subscription(channel)
this.subs.set(channel, s)
return s
}
getSubscription(channel: string) {
return this.subs.get(channel) ?? null
}
removeSubscription(s: Subscription | null) {
if (s) this.subs.delete(s.channel)
}
connect() {
this.connectCalls++
this.emit('state', { newState: 'connecting' })
}
disconnect() {
this.disconnectCalls++
this.emit('state', { newState: 'disconnected' })
}
}
return { Centrifuge, UnauthorizedError: hoisted.FakeUnauthorizedError }
})
import * as rt from './realtime'
function clients(): FakeClient[] {
return hoisted.created as FakeClient[]
}
function lastClient(): FakeClient {
const c = clients().at(-1)
if (!c) throw new Error('no client was created')
return c
}
function sub(channel: string): FakeSub {
const s = lastClient().subs.get(channel)
if (!s) throw new Error(`no subscription for ${channel}`)
return s
}
beforeEach(() => {
vi.stubGlobal('window', { location: { protocol: 'https:', host: 'bm.example' } })
vi.stubGlobal('fetch', (path: string) => tokenRoute(path))
hoisted.request.mockReset()
hoisted.getToken = null
hoisted.created.length = 0
})
afterEach(() => {
rt.disconnect()
vi.unstubAllGlobals()
})
describe('tokenFailureIsFinal', () => {
it('stops only on 401, 403 and 404', () => {
expect(rt.tokenFailureIsFinal(401)).toBe(true)
expect(rt.tokenFailureIsFinal(403)).toBe(true)
expect(rt.tokenFailureIsFinal(404)).toBe(true)
expect(rt.tokenFailureIsFinal(503)).toBe(false)
expect(rt.tokenFailureIsFinal(500)).toBe(false)
expect(rt.tokenFailureIsFinal(429)).toBe(false)
})
})
describe('openChannel getToken', () => {
async function tokenFn(onUnavailable: () => void) {
await rt.openChannel('presentations:remote:1.abc', { onPublication() {}, onUnavailable })
if (!hoisted.getToken) throw new Error('getToken was not passed to the client')
return hoisted.getToken
}
it('retries a 503 instead of giving up', async () => {
const onUnavailable = vi.fn()
const getToken = await tokenFn(onUnavailable)
hoisted.request.mockRejectedValueOnce(new ApiError(503, 'Service unavailable'))
const err = await getToken().catch((e: unknown) => e)
expect(err).toMatchObject({ status: 503 })
expect(err).not.toBeInstanceOf(hoisted.FakeUnauthorizedError)
expect(onUnavailable).not.toHaveBeenCalled()
hoisted.request.mockResolvedValueOnce({ token: 'tok' })
await expect(getToken()).resolves.toBe('tok')
})
it('gives up for good on a 403', async () => {
const onUnavailable = vi.fn()
const getToken = await tokenFn(onUnavailable)
hoisted.request.mockRejectedValueOnce(new ApiError(403, 'Forbidden'))
await expect(getToken()).rejects.toBeInstanceOf(hoisted.FakeUnauthorizedError)
expect(onUnavailable).toHaveBeenCalledOnce()
})
it('tells a listener added after the refusal at once', async () => {
const getToken = await tokenFn(() => {})
hoisted.request.mockRejectedValueOnce(new ApiError(404, 'Not found'))
await getToken().catch(() => {})
const late = vi.fn()
rt.onUnavailable(late)
await Promise.resolve()
expect(late).toHaveBeenCalledOnce()
})
})
describe('the shared client', () => {
it('uses one client for two channels and disconnects with the last handle', async () => {
const a = await rt.subscribe('user:1', {})
const b = await rt.subscribe('chat:conversation:10', {})
expect(clients()).toHaveLength(1)
expect(lastClient().subs.size).toBe(2)
a.close()
expect(lastClient().disconnectCalls).toBe(0)
expect(lastClient().subs.has('user:1')).toBe(false)
b.close()
expect(lastClient().disconnectCalls).toBe(1)
// The next subscribe reconnects the same client.
await rt.subscribe('user:1', {})
expect(clients()).toHaveLength(1)
expect(lastClient().connectCalls).toBe(2)
})
it('shares one Subscription per channel and fans events out to every handle', async () => {
const first = { onPublication: vi.fn(), onSubscribed: vi.fn(), onDenied: vi.fn() }
const second = { onPublication: vi.fn() }
const h1 = await rt.subscribe('chat:conversation:10', first)
const h2 = await rt.subscribe('chat:conversation:10', second)
expect(lastClient().newSubscriptionCalls).toBe(1)
const s = sub('chat:conversation:10')
expect(s.subscribeCalls).toBe(1)
s.emit('publication', { data: { event: 'x' } })
expect(first.onPublication).toHaveBeenCalledWith({ event: 'x' })
expect(second.onPublication).toHaveBeenCalledWith({ event: 'x' })
s.emit('subscribed')
expect(first.onSubscribed).toHaveBeenCalledOnce()
s.emit('unsubscribed', { code: 403 })
s.emit('unsubscribed', { code: 0 })
expect(first.onDenied).toHaveBeenCalledExactlyOnceWith(403)
h1.close()
s.emit('publication', { data: 2 })
expect(first.onPublication).toHaveBeenCalledTimes(1)
expect(second.onPublication).toHaveBeenCalledTimes(2)
expect(s.unsubscribed).toBe(false)
h2.close()
expect(s.unsubscribed).toBe(true)
})
it('hands a later handle its own subscribed on a live channel', async () => {
await rt.subscribe('chat:conversation:10', {})
sub('chat:conversation:10').state = 'subscribed'
const onSubscribed = vi.fn()
await rt.subscribe('chat:conversation:10', { onSubscribed })
await Promise.resolve()
expect(onSubscribed).toHaveBeenCalledOnce()
})
it('reports presence, joins and leaves with numeric user ids', async () => {
const onJoin = vi.fn()
const onLeave = vi.fn()
await rt.subscribe('chat:conversation:10', { onJoin, onLeave })
const s = sub('chat:conversation:10')
s.presence.mockResolvedValueOnce({ clients: { c1: { client: 'c1', user: '1' }, c2: { client: 'c2', user: '7' }, x: { client: 'x', user: '' } } })
await expect(rt.presence('chat:conversation:10')).resolves.toEqual([
{ client: 'c1', user: 1 },
{ client: 'c2', user: 7 },
])
s.emit('join', { info: { client: 'c3', user: '8' } })
s.emit('leave', { info: { client: 'c2', user: '7' } })
expect(onJoin).toHaveBeenCalledWith({ client: 'c3', user: 8 })
expect(onLeave).toHaveBeenCalledWith({ client: 'c2', user: 7 })
s.presence.mockRejectedValueOnce(new Error('not available'))
await expect(rt.presence('chat:conversation:10')).resolves.toBeNull()
await expect(rt.presence('chat:conversation:99')).resolves.toBeNull()
})
it('openChannel keeps close and resubscribe and rides the chat socket', async () => {
const chat = await rt.subscribe('user:1', {})
lastClient().emit('state', { newState: 'connected' })
const onConnection = vi.fn()
const remote = await rt.openChannel('presentations:remote:1.abc', { onPublication() {}, onConnection })
expect(clients()).toHaveLength(1)
expect(onConnection).toHaveBeenCalledWith('connected')
remote.resubscribe()
expect(sub('presentations:remote:1.abc').subscribeCalls).toBe(2)
remote.close()
expect(lastClient().disconnectCalls).toBe(0)
lastClient().emit('state', { newState: 'connecting' })
expect(onConnection).toHaveBeenCalledTimes(1)
chat.close()
expect(lastClient().disconnectCalls).toBe(1)
})
it('disconnect forgets the client so the next session gets a new one', async () => {
const h = await rt.subscribe('user:1', {})
rt.disconnect()
expect(clients()[0]?.disconnectCalls).toBe(1)
h.close()
await rt.subscribe('user:2', {})
expect(clients()).toHaveLength(2)
})
})