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
This commit is contained in:
Jakub Zych
2026-11-01 19:17:42 +01:00
parent 764cb42894
commit b6d3389e46
11 changed files with 1670 additions and 5 deletions

256
tests/client.test.ts Normal file
View File

@@ -0,0 +1,256 @@
import { describe, expect, it, vi } from 'vitest'
import { ChatApiError, createChatClient, toError, userIdFromToken, type ChatFetch } from '../app/lib/client'
const bases = { chat: '/_chat/api/v1', channels: '/_chatchannels/api/v1', bots: '/_chatbots/api/v1', host: '/_acme/api/v1' }
const ctx = { type: 'acme', id: 1 }
function json(status: number, body: unknown): Response {
return new Response(body === undefined ? '' : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
}
function client(fetch: ChatFetch, auth: Parameters<typeof createChatClient>[0]['auth'] = { token: () => 'tok' }) {
return createChatClient({ bases, auth, fetch })
}
describe('createChatClient endpoints', () => {
// Every method: the URL and HTTP method it calls and the JSON body.
const cases: Array<{ name: string; call: (c: ReturnType<typeof client>) => Promise<unknown>; url: string; method: string; body?: unknown; answer?: unknown }> = [
{ name: 'bootstrap', call: (c) => c.bootstrap(), url: '/_acme/api/v1/chat', method: 'GET', answer: { member: false } },
{ name: 'members', call: (c) => c.members(), url: '/_acme/api/v1/chat/members', method: 'GET', answer: { members: [] } },
{ name: 'openConversation', call: (c) => c.openConversation('channel', 3), url: '/_chat/api/v1/contexts/channel/3/conversation', method: 'GET' },
{ name: 'messages', call: (c) => c.messages(7), url: '/_chat/api/v1/conversations/7/messages?limit=50', method: 'GET', answer: { data: [] } },
{ name: 'messages before', call: (c) => c.messages(7, { limit: 20, before: 99 }), url: '/_chat/api/v1/conversations/7/messages?limit=20&before=99', method: 'GET', answer: { data: [] } },
{ name: 'send', call: (c) => c.send(7, { content: 'hi' }), url: '/_chat/api/v1/conversations/7/messages', method: 'POST', body: { content: 'hi' } },
{ name: 'message', call: (c) => c.message(5), url: '/_chat/api/v1/messages/5', method: 'GET' },
{ name: 'markRead', call: (c) => c.markRead(7), url: '/_chat/api/v1/conversations/7/read', method: 'POST' },
{ name: 'typing', call: (c) => c.typing(7), url: '/_chat/api/v1/conversations/7/typing', method: 'POST' },
{ name: 'startDm', call: (c) => c.startDm(ctx, 4), url: '/_chat/api/v1/contexts/acme/1/dm', method: 'POST', body: { user_id: 4 } },
{ name: 'joinChannel', call: (c) => c.joinChannel(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/join', method: 'POST' },
{ name: 'leaveChannel', call: (c) => c.leaveChannel(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/leave', method: 'POST' },
{ name: 'pins', call: (c) => c.pins(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins', method: 'GET', answer: { pins: [5] } },
{ name: 'pin', call: (c) => c.pin(ctx, 2, 5), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins', method: 'POST', body: { message_id: 5 } },
{ name: 'unpin', call: (c) => c.unpin(ctx, 2, 5), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins/5', method: 'DELETE' },
{ name: 'edit', call: (c) => c.edit(5, 'new'), url: '/_chat/api/v1/messages/5', method: 'PUT', body: { content: 'new' } },
{ name: 'remove', call: (c) => c.remove(5), url: '/_chat/api/v1/messages/5', method: 'DELETE' },
{ name: 'reactions', call: (c) => c.reactions(), url: '/_chat/api/v1/reactions', method: 'GET', answer: { data: ['👍'] } },
{ name: 'addReaction', call: (c) => c.addReaction(5, '👍'), url: '/_chat/api/v1/messages/5/reactions', method: 'POST', body: { key: '👍' } },
{ name: 'removeReaction', call: (c) => c.removeReaction(5, '👍'), url: `/_chat/api/v1/messages/5/reactions/${encodeURIComponent('👍')}`, method: 'DELETE' },
{ name: 'replies', call: (c) => c.replies(5), url: '/_chat/api/v1/messages/5/replies', method: 'GET', answer: { data: [] } },
{ name: 'reply', call: (c) => c.reply(5, { content: 'r' }), url: '/_chat/api/v1/messages/5/replies', method: 'POST', body: { content: 'r' } },
{ name: 'muteThread', call: (c) => c.muteThread(5, true), url: '/_chat/api/v1/threads/5/mute', method: 'PUT', body: { muted: true } },
{ name: 'commands', call: (c) => c.commands(), url: '/_chatbots/api/v1/commands', method: 'GET', answer: { commands: [] } },
{ name: 'dispatch', call: (c) => c.dispatch('/demo'), url: '/_chatbots/api/v1/dispatch', method: 'POST', body: { input: '/demo' } },
]
for (const tc of cases) {
it(`${tc.name}: ${tc.method} ${tc.url}`, async () => {
const fetch = vi.fn<ChatFetch>(async () => json(200, tc.answer ?? { id: 1 }))
await tc.call(client(fetch))
expect(fetch).toHaveBeenCalledTimes(1)
const [url, init] = fetch.mock.calls[0]
expect(url).toBe(tc.url)
expect(init.method).toBe(tc.method)
expect(init.headers.Authorization).toBe('Bearer tok')
expect(init.headers.Accept).toBe('application/json')
if (tc.body === undefined) {
expect(init.body).toBeUndefined()
} else {
expect(init.headers['Content-Type']).toBe('application/json')
expect(JSON.parse(init.body as string)).toEqual(tc.body)
}
})
}
it('unwraps data, members and pins and tolerates their absence', async () => {
const answers: Record<string, unknown> = {
'/_chat/api/v1/conversations/1/messages?limit=50': { data: [{ id: 1 }] },
'/_acme/api/v1/chat/members': [{ id: 2 }],
'/_chatchannels/api/v1/contexts/acme/1/channels/2/pins': {},
'/_chatbots/api/v1/commands': { other: true },
}
const c = client(async (url) => json(200, answers[url]))
await expect(c.messages(1)).resolves.toEqual([{ id: 1 }])
await expect(c.members()).resolves.toEqual([{ id: 2 }])
await expect(c.pins(ctx, 2)).resolves.toEqual([])
await expect(c.commands()).resolves.toEqual([])
})
it('sends no Authorization header without a token, and a throwing token getter counts as none', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(200, {}))
await client(fetch, { token: () => null }).message(1)
await client(fetch, {
token: () => {
throw new Error('no cookie')
},
}).message(1)
for (const call of fetch.mock.calls) expect(call[1].headers.Authorization).toBeUndefined()
})
it('refuses the host routes without a host base', async () => {
const fetch = vi.fn<ChatFetch>()
const c = createChatClient({ bases: { ...bases, host: '' }, auth: { token: () => 'tok' }, fetch })
expect(() => c.bootstrap()).toThrow(ChatApiError)
expect(fetch).not.toHaveBeenCalled()
})
it('downloads attachment bytes with the bearer token', async () => {
const fetch = vi.fn<ChatFetch>(async () => new Response('bytes', { status: 200 }))
const blob = await client(fetch).download(5, 9)
expect(await blob.text()).toBe('bytes')
expect(fetch.mock.calls[0][0]).toBe('/_chat/api/v1/attachments/5/9')
expect(fetch.mock.calls[0][1].headers.Authorization).toBe('Bearer tok')
expect(fetch.mock.calls[0][1].headers.Accept).toBe('*/*')
})
})
describe('createChatClient auth', () => {
it('refreshes once on 401 and retries with the new token', async () => {
let current = 'old'
const refresh = vi.fn(async () => (current = 'new'))
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>().mockResolvedValueOnce(json(401, { error: 'Token expired' })).mockResolvedValueOnce(json(200, { id: 3 }))
const m = await client(fetch, { token: () => current, refresh, unauthorized }).message(3)
expect(m).toEqual({ id: 3 })
expect(refresh).toHaveBeenCalledTimes(1)
expect(unauthorized).not.toHaveBeenCalled()
expect(fetch.mock.calls.map((c) => c[1].headers.Authorization)).toEqual(['Bearer old', 'Bearer new'])
})
it('calls unauthorized after a failed refresh and throws the 401', async () => {
const refresh = vi.fn(async () => null)
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, { error: 'Unauthorized' }))
const err = await client(fetch, { token: () => 'old', refresh, unauthorized }).message(3).catch((e) => e)
expect(err).toBeInstanceOf(ChatApiError)
expect(err.status).toBe(401)
expect(refresh).toHaveBeenCalledTimes(1)
expect(unauthorized).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledTimes(1)
})
it('calls unauthorized when the retry is still 401', async () => {
let current = 'old'
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, {}))
await expect(client(fetch, { token: () => current, refresh: async () => (current = 'new'), unauthorized }).message(1)).rejects.toMatchObject({ status: 401 })
expect(fetch).toHaveBeenCalledTimes(2)
expect(unauthorized).toHaveBeenCalledTimes(1)
})
it('does not refresh a request that carried no token', async () => {
const refresh = vi.fn(async () => 'new')
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, {}))
await expect(client(fetch, { token: () => null, refresh, unauthorized }).message(1)).rejects.toMatchObject({ status: 401 })
expect(refresh).not.toHaveBeenCalled()
expect(unauthorized).not.toHaveBeenCalled()
})
it('shares one refresh between concurrent 401s', async () => {
let current = 'old'
let release!: () => void
const gate = new Promise<void>((r) => (release = r))
const refresh = vi.fn(async () => {
await gate
current = 'new'
return current
})
const fetch = vi.fn<ChatFetch>(async (_url, init) => (init.headers.Authorization === 'Bearer new' ? json(200, { ok: true }) : json(401, {})))
const c = client(fetch, { token: () => current, refresh })
const both = Promise.all([c.message(1), c.message(2)])
await new Promise((r) => setTimeout(r, 0))
release()
await expect(both).resolves.toEqual([{ ok: true }, { ok: true }])
expect(refresh).toHaveBeenCalledTimes(1)
})
it('maps a network failure to status 0', async () => {
const fetch = vi.fn<ChatFetch>(async () => {
throw new TypeError('fetch failed')
})
await expect(client(fetch).message(1)).rejects.toMatchObject({ status: 0, message: 'network error' })
})
})
describe('errors', () => {
it('maps a 422 envelope to field errors', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(422, { error: 'Validation failed', errors: { content: ['The text contains a word that is not allowed.'] } }))
const err = (await client(fetch).send(1, { content: 'x' }).catch((e) => e)) as ChatApiError
expect(err).toBeInstanceOf(ChatApiError)
expect(err.status).toBe(422)
expect(err.message).toBe('Validation failed')
expect(err.field('content')).toBe('The text contains a word that is not allowed.')
expect(err.field('other')).toBe('')
})
it('toError reads error, then message, else the status, and normalizes errors', () => {
expect(toError(404, { error: 'Not found' }).message).toBe('Not found')
expect(toError(500, { message: 'boom' }).message).toBe('boom')
expect(toError(503, null).message).toBe('HTTP 503')
expect(toError(503, 'text').message).toBe('HTTP 503')
expect(toError(422, { errors: { a: 'one', b: ['x', 2, 'y'], c: 5 } }).errors).toEqual({ a: ['one'], b: ['x', 'y'] })
expect(toError(422, { errors: ['x'] }).errors).toEqual({})
})
it('throws on a non-JSON error body with the status', async () => {
const fetch = vi.fn<ChatFetch>(async () => new Response('<html>bad gateway</html>', { status: 502 }))
await expect(client(fetch).message(1)).rejects.toMatchObject({ status: 502, message: 'HTTP 502' })
})
})
describe('upload', () => {
it('posts the file as multipart field file and answers its id, name and size', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(201, { id: 12, filename: 'a.png', size: 3 }))
const file = new File(['abc'], 'a.png', { type: 'image/png' })
await expect(client(fetch).upload(file)).resolves.toEqual({ id: 12, filename: 'a.png', size: 3 })
const [url, init] = fetch.mock.calls[0]
expect(url).toBe('/_chat/api/v1/attachments')
expect(init.method).toBe('POST')
expect(init.headers.Authorization).toBe('Bearer tok')
expect(init.headers['Content-Type']).toBeUndefined()
const form = init.body as FormData
expect(form).toBeInstanceOf(FormData)
expect((form.get('file') as File).name).toBe('a.png')
})
it('fills a missing name and size from the file', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(201, { data: { id: 4 } }))
await expect(client(fetch).upload(new File(['abcd'], 'b.txt'))).resolves.toEqual({ id: 4, filename: 'b.txt', size: 4 })
})
it('maps a refused upload to its field error', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(422, { error: 'Validation failed', errors: { file: ['too large'] } }))
const err = (await client(fetch).upload(new File(['x'], 'x.bin')).catch((e) => e)) as ChatApiError
expect(err.status).toBe(422)
expect(err.field('file')).toBe('too large')
})
it('refreshes once on 401 and uploads again', async () => {
let current = 'old'
const fetch = vi.fn<ChatFetch>().mockResolvedValueOnce(json(401, {})).mockResolvedValueOnce(json(201, { id: 8, filename: 'c', size: 1 }))
const onProgress = vi.fn()
const answer = await client(fetch, { token: () => current, refresh: async () => (current = 'new') }).upload(new File(['c'], 'c'), onProgress)
expect(answer.id).toBe(8)
expect(fetch.mock.calls.map((c) => c[1].headers.Authorization)).toEqual(['Bearer old', 'Bearer new'])
expect(onProgress).toHaveBeenCalledWith(0)
})
it('calls unauthorized when the upload cannot be renewed', async () => {
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, {}))
await expect(client(fetch, { token: () => 'old', refresh: async () => null, unauthorized }).upload(new File(['c'], 'c'))).rejects.toMatchObject({ status: 401 })
expect(unauthorized).toHaveBeenCalledTimes(1)
})
})
describe('userIdFromToken', () => {
const token = (claims: unknown) => `h.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.s`
it('reads a numeric sub, as a number or a string', () => {
expect(userIdFromToken(token({ sub: 42 }))).toBe(42)
expect(userIdFromToken(token({ sub: ' 7 ' }))).toBe(7)
})
it('answers null for anything else', () => {
for (const t of [null, undefined, '', 'x', 'a.b.c', token({}), token({ sub: 'ada' }), token({ sub: 0 }), token({ sub: -3 }), token({ sub: 1.5 })]) {
expect(userIdFromToken(t)).toBeNull()
}
})
})

525
tests/store.test.ts Normal file
View File

@@ -0,0 +1,525 @@
// The chat store (useChat) outside Nuxt: the auto-imported composables
// (useState, useNuxtApp, useChatApi, useChatAuth, useChatConfig,
// useChatNotice) are stubbed globals over a fresh state per test, the API
// client is a fake and the realtime client is the layer's module with the
// network parts replaced (subscribe, connection and unavailable listeners,
// presence); onUserEvent and dispatchUserEvent stay real. The scenarios
// follow the SPA store's tests (bm's stores/chat.test.ts) for the
// multi-channel store.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ref } from 'vue'
import { ChatApiError } from '../app/lib/client'
import { dmActionsTarget } from '../app/lib/slots'
import type { ChatChannel, ChatConversationRow, ChatMessage } from '../app/lib/types'
const rt = vi.hoisted(() => ({
subs: new Map<string, { onPublication?: (d: unknown) => void; onSubscribed?: () => void; closed: boolean }>(),
connection: [] as Array<(s: string) => void>,
unavailable: [] as Array<() => void>,
}))
vi.mock('../app/lib/realtime', async (importOriginal) => {
const real = await importOriginal<typeof import('../app/lib/realtime')>()
return {
...real,
setRealtimeAuth: vi.fn(),
hasRealtimeAuth: () => true,
disconnect: vi.fn(),
presence: vi.fn(async () => []),
onConnection: (fn: (s: string) => void) => {
rt.connection.push(fn)
return () => {}
},
onUnavailable: (fn: () => void) => {
rt.unavailable.push(fn)
return () => {}
},
subscribe: vi.fn(async (channel: string, hooks: { onPublication?: (d: unknown) => void; onSubscribed?: () => void }) => {
const entry = { ...hooks, closed: false }
rt.subs.set(channel, entry)
return { close: () => (entry.closed = true) }
}),
}
})
const { useChat, POLL_ACTIVE_MS, POLL_COUNTS_MS } = await import('../app/composables/useChat')
const { useChatNotice } = await import('../app/composables/useChatNotice')
const { onUserEvent } = await import('../app/lib/realtime')
const ME = 7
const CONTEXT = { type: 'acme', id: 1 }
function channel(id: number, conv: number, over: Partial<ChatChannel> = {}): ChatChannel {
return { id, slug: `c${id}`, name: `c${id}`, conversation_id: conv, joined: true, unread: 0, mentions: 0, ...over }
}
function dm(id: number, other: number, over: Partial<ChatConversationRow> = {}): ChatConversationRow {
return { id, type: 'dm', other_user_id: other, unread: 0, last_message: null, ...over }
}
function msg(id: number, conv: number, over: Partial<ChatMessage> = {}): ChatMessage {
return {
id,
conversation_id: conv,
sender_id: 9,
sender_name: 'Ada',
sender_avatar: null,
content: `message ${id}`,
type: 'text',
attachments: [],
created_at: new Date(Date.UTC(2026, 10, 1, 12, 0, id)).toISOString(),
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: false,
root_id: null,
reactions: [],
...over,
}
}
function bootstrapAnswer(left: Set<number> = new Set([2])) {
return {
member: true,
moderator: false,
context: CONTEXT,
channels: [channel(1, 100), channel(2, 200), channel(3, 300, { unread: 2, mentions: 1 })].map((c) => ({ ...c, joined: !left.has(c.id) })),
conversations: [dm(400, 9, { unread: 1 })],
limits: { max_files: 5, max_bytes: 5242880, max_embeds: 3 },
}
}
/** The fake server remembers the channels the caller left (channel 2 at first). */
function fakeApi() {
const left = new Set([2])
return {
bootstrap: vi.fn(async () => bootstrapAnswer(left) as unknown),
members: vi.fn(async () => [{ id: 9, name: 'Ada', surname: 'Hart', handle: 'ada', is_bot: false }]),
reactions: vi.fn(async () => ['👍', '❤️']),
messages: vi.fn(async (conv: number) => [msg(conv + 1, conv), msg(conv + 2, conv)]),
openConversation: vi.fn(async (_t: string, id: number) => ({ id: id * 100, type: 'group' })),
joinChannel: vi.fn(async (_ctx: unknown, id: number) => (left.delete(id), {})),
leaveChannel: vi.fn(async (_ctx: unknown, id: number) => (left.add(id), {})),
send: vi.fn(async (conv: number, body: { content: string }) => msg(999, conv, { sender_id: ME, content: body.content, is_mine: true })),
message: vi.fn(async (id: number) => msg(id, 100)),
markRead: vi.fn(async () => ({})),
typing: vi.fn(async () => ({})),
startDm: vi.fn(async () => ({ id: 500, type: 'dm' })),
replies: vi.fn(async (root: number) => [msg(root + 50, 100, { root_id: root })]),
reply: vi.fn(async (root: number, body: { content: string }) => msg(888, 100, { root_id: root, sender_id: ME, content: body.content })),
muteThread: vi.fn(async (_root: number, muted: boolean) => ({ root_id: _root, is_muted: muted })),
pins: vi.fn(async () => [101]),
pin: vi.fn(async () => ({})),
unpin: vi.fn(async () => ({})),
addReaction: vi.fn(async () => ({ reactions: [{ key: '👍', count: 1, user_ids: [ME] }] })),
removeReaction: vi.fn(async () => ({ reactions: [] })),
commands: vi.fn(async () => [{ trigger: 'demo', description: 'What this demo shows' }]),
dispatch: vi.fn(async (input: string) => ({ mode: 'ephemeral', payload: { content: `answer to ${input}` } })),
edit: vi.fn(),
remove: vi.fn(),
upload: vi.fn(),
download: vi.fn(),
}
}
let api: ReturnType<typeof fakeApi>
let config: { apiBase: string; channelsApiBase: string; botsApiBase: string; hostApiBase: string }
beforeEach(() => {
const state = new Map<string, ReturnType<typeof ref>>()
const nuxtApp = {}
api = fakeApi()
config = { apiBase: '/_chat/api/v1', channelsApiBase: '/_chatchannels/api/v1', botsApiBase: '/_chatbots/api/v1', hostApiBase: '/_acme/api/v1' }
rt.subs.clear()
rt.connection.length = 0
rt.unavailable.length = 0
vi.stubGlobal('useState', (key: string, init?: () => unknown) => {
if (!state.has(key)) state.set(key, ref(init ? init() : undefined))
return state.get(key)
})
vi.stubGlobal('useNuxtApp', () => nuxtApp)
vi.stubGlobal('useChatApi', () => api)
vi.stubGlobal('useChatAuth', () => ({ token: () => 'jwt', userId: () => ME }))
vi.stubGlobal('useChatConfig', () => config)
vi.stubGlobal('useChatNotice', useChatNotice)
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
/** Lets pending promise chains settle. */
async function flush() {
for (let i = 0; i < 10; i++) await Promise.resolve()
}
async function started() {
const chat = useChat()
await chat.start()
await flush()
return chat
}
/** Publishes data on a subscribed channel. */
function publish(channel: string, data: unknown) {
const sub = rt.subs.get(channel)
if (!sub?.onPublication) throw new Error(`no subscription on ${channel}`)
sub.onPublication(data)
}
describe('start and bootstrap', () => {
it('fills channels, DMs, limits and members, and subscribes user:{me}', async () => {
const chat = await started()
expect(api.bootstrap).toHaveBeenCalledTimes(1)
expect(chat.member).toBe(true)
expect(chat.userId).toBe(ME)
expect(chat.context).toEqual(CONTEXT)
expect(chat.channels.map((c) => c.id)).toEqual([1, 2, 3])
expect(chat.joinedChannels.map((c) => c.id)).toEqual([1, 3])
expect(chat.conversations.map((c) => c.id)).toEqual([400])
expect(chat.limits?.max_embeds).toBe(3)
expect(chat.members.get(9)?.handle).toBe('ada')
expect(chat.dmUnread).toBe(1)
expect(chat.channelUnread).toBe(2)
expect(chat.attention).toBe(2)
expect(rt.subs.has(`user:${ME}`)).toBe(true)
expect(chat.connection).toBe('connecting')
})
it('starts nothing without a host API base', async () => {
config.hostApiBase = ''
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const chat = await started()
expect(api.bootstrap).not.toHaveBeenCalled()
expect(rt.subs.size).toBe(0)
expect(chat.member).toBeUndefined()
expect(error).toHaveBeenCalledWith(expect.stringContaining('hostApiBase'))
error.mockRestore()
})
it('starts nothing for a non-member bootstrap', async () => {
api.bootstrap.mockResolvedValueOnce({ member: false })
const chat = await started()
expect(chat.member).toBe(false)
expect(chat.channels).toEqual([])
expect(api.members).not.toHaveBeenCalled()
expect(rt.subs.size).toBe(0)
expect(chat.attention).toBe(0)
})
it('starts nothing without a user', async () => {
vi.stubGlobal('useChatAuth', () => ({ token: () => null }))
const chat = await started()
expect(api.bootstrap).not.toHaveBeenCalled()
expect(chat.userId).toBeNull()
})
})
describe('channels and DMs', () => {
it('opening a joined channel runs its conversation route once a session and loads its page', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
expect(api.joinChannel).not.toHaveBeenCalled()
expect(api.openConversation).toHaveBeenCalledWith('channel', 1)
expect(api.messages).toHaveBeenCalledWith(100, { limit: 50 })
expect(chat.activeId).toBe(100)
expect(chat.kind).toBe('channel')
expect(chat.activeChannel?.id).toBe(1)
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102])
expect(rt.subs.has('chat:conversation:100')).toBe(true)
await chat.openChannel(chat.channels[0])
expect(api.openConversation).toHaveBeenCalledTimes(1)
expect(api.messages).toHaveBeenCalledTimes(1)
})
it('opening a left channel joins it first (lazy join)', async () => {
const chat = await started()
await chat.openChannel(chat.channels[1])
expect(api.joinChannel).toHaveBeenCalledWith(CONTEXT, 2)
expect(api.openConversation).toHaveBeenCalledWith('channel', 2)
expect(chat.channels[1].joined).toBe(true)
expect(chat.activeId).toBe(200)
})
it('leaving the open channel closes it and keeps it listed', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
await chat.leaveChannel(chat.channels[0])
await flush()
expect(api.leaveChannel).toHaveBeenCalledWith(CONTEXT, 1)
expect(chat.channels.map((c) => c.id)).toEqual([1, 2, 3])
expect(chat.channels[0].joined).toBe(false)
expect(chat.joinedChannels.map((c) => c.id)).toEqual([3])
expect(chat.activeId).toBeNull()
expect(rt.subs.get('chat:conversation:100')?.closed).toBe(true)
})
it('a refused channel open shows a notice and opens nothing', async () => {
api.openConversation.mockRejectedValueOnce(new ChatApiError(404, 'Not found'))
const chat = await started()
expect(await chat.openChannel(chat.channels[0])).toBe(false)
expect(chat.activeId).toBeNull()
expect(useChatNotice().current.value?.key).toBe('error.openChannel')
})
it('opens an existing DM, or creates one with a member', async () => {
const chat = await started()
expect(await chat.startDm(9)).toBe(400)
expect(api.startDm).not.toHaveBeenCalled()
expect(chat.kind).toBe('dm')
expect(await chat.startDm(11)).toBe(500)
expect(api.startDm).toHaveBeenCalledWith(CONTEXT, 11)
expect(chat.conversations[0]).toMatchObject({ id: 500, type: 'dm', other_user_id: 11 })
api.startDm.mockRejectedValueOnce(new ChatApiError(429, 'Too many'))
expect(await chat.startDm(12)).toBeNull()
expect(chat.dmError).toBe('error.tooManyDms')
})
it('the conversation-actions slot is for DMs only', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
expect(chat.activeDm).toBeNull()
expect(dmActionsTarget(chat.activeDm)).toBeNull()
await chat.openDm(400)
expect(chat.activeChannel).toBeNull()
expect(dmActionsTarget(chat.activeDm)?.id).toBe(400)
expect(dmActionsTarget({ ...dm(1, 2), type: 'group' })).toBeNull()
expect(dmActionsTarget(undefined)).toBeNull()
})
})
describe('realtime', () => {
it('a message from someone else counts as unread elsewhere and appends in the open conversation', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.panelVisible = true
// In another channel: unread +1, nothing loaded there.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 300, message: msg(301, 300) } })
expect(chat.channels[2].unread).toBe(3)
// In the open, visible channel: appended, no unread.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(150, 100) } })
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102, 150])
expect(chat.channels[0].unread).toBe(0)
// In a DM: the row's count and preview.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 400, message: msg(401, 400, { content: 'hi there' }) } })
expect(chat.conversations.find((c) => c.id === 400)).toMatchObject({ unread: 2, last_message: { id: 401, content: 'hi there' } })
// The same message twice is not listed twice.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(150, 100) } })
expect(chat.messages[100].filter((m) => m.id === 150)).toHaveLength(1)
})
it('a hidden open conversation still counts the message as unread', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(160, 100) } })
expect(chat.channels[0].unread).toBe(1)
expect(chat.messages[100].at(-1)?.id).toBe(160)
})
it('a content-free created event fetches the message of a loaded conversation', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.message.mockResolvedValueOnce(msg(170, 100))
publish('chat:conversation:100', { event: 'created.chat.message', payload: { id: 170, conversation_id: 100, sender_id: 9 } })
await flush()
expect(api.message).toHaveBeenCalledWith(170)
expect(chat.messages[100].at(-1)?.id).toBe(170)
})
it('typing, reactions, edits and deletions patch the open conversation', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
rt.connection.forEach((fn) => fn('connected'))
publish('chat:conversation:100', { event: 'typing.chat.message', payload: { action: 'typing-start', conversation_id: 100, user_id: 9 } })
expect(chat.typingIn(100)).toEqual([9])
publish('chat:conversation:100', { event: 'reacted.chat.message', payload: { id: 101, conversation_id: 100, user_id: 9, key: '👍', action: 'added' } })
expect(chat.findMessage(100, 101)?.reactions?.[0]).toMatchObject({ key: '👍', user_ids: [9] })
publish('chat:conversation:100', { event: 'deleted.chat.message', payload: { id: 102, conversation_id: 100 } })
expect(chat.findMessage(100, 102)).toMatchObject({ content: null })
expect(chat.findMessage(100, 102)?.deleted_at).toBeTruthy()
api.message.mockResolvedValueOnce(msg(101, 100, { content: 'edited', edited_at: new Date().toISOString() }))
publish('chat:conversation:100', { event: 'updated.chat.message', payload: { id: 101, conversation_id: 100 } })
await flush()
expect(chat.findMessage(100, 101)?.content).toBe('edited')
})
it('hands events it does not handle on user:{me} to onUserEvent', async () => {
const seen: unknown[] = []
const off = onUserEvent((d) => seen.push(d))
await started()
const call = { event: 'video:call:incoming', payload: { session_id: 5, conversation_id: 400, caller_id: 9 } }
publish(`user:${ME}`, call)
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 400, message: msg(402, 400) } })
off()
expect(seen).toEqual([call])
})
it('polls the open conversation and the counts when realtime is unavailable', async () => {
vi.useFakeTimers()
const chat = useChat()
await chat.start()
await vi.advanceTimersByTimeAsync(0)
await chat.openChannel(chat.channels[0])
expect(api.messages).toHaveBeenCalledTimes(1)
rt.unavailable.forEach((fn) => fn())
expect(chat.connection).toBe('unavailable')
expect(chat.typingIn(100)).toEqual([])
await vi.advanceTimersByTimeAsync(POLL_ACTIVE_MS)
expect(api.messages).toHaveBeenCalledTimes(2)
const boots = api.bootstrap.mock.calls.length
await vi.advanceTimersByTimeAsync(POLL_COUNTS_MS - POLL_ACTIVE_MS)
expect(api.bootstrap.mock.calls.length).toBeGreaterThan(boots)
chat.reset()
})
it('reset forgets the session and closes the subscriptions', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.reset()
expect(chat.member).toBeUndefined()
expect(chat.channels).toEqual([])
expect(chat.messages).toEqual({})
expect(rt.subs.get(`user:${ME}`)?.closed).toBe(true)
expect(rt.subs.get('chat:conversation:100')?.closed).toBe(true)
})
})
describe('sending', () => {
it('posts the trimmed draft and appends the answer', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.setDraftText(100, ' hello ')
expect(chat.canSend(100)).toBe(true)
expect(await chat.send()).toBe(true)
expect(api.send).toHaveBeenCalledWith(100, { content: 'hello' })
expect(chat.draft(100).text).toBe('')
expect(chat.messages[100].at(-1)?.id).toBe(999)
})
it('keeps the draft with the refusal of a 422', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.send.mockRejectedValueOnce(new ChatApiError(422, 'Validation failed', { content: ['The text contains a word that is not allowed.'] }))
chat.setDraftText(100, 'blocked')
expect(await chat.send()).toBe(false)
expect(chat.draft(100)).toMatchObject({ text: 'blocked', error: 'error.refused', detail: 'The text contains a word that is not allowed.' })
})
it('dispatches a slash command instead of posting it; the answer stays local', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.setDraftText(100, '/demo')
expect(await chat.send()).toBe(true)
expect(api.dispatch).toHaveBeenCalledWith('/demo')
expect(api.send).not.toHaveBeenCalled()
expect(chat.ephemeral[100]).toEqual([{ id: expect.any(Number), input: '/demo', text: 'answer to /demo', error: '' }])
expect(chat.draft(100).text).toBe('')
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102])
chat.dismissEphemeral(100, chat.ephemeral[100][0].id)
expect(chat.ephemeral[100]).toEqual([])
})
it('an unknown command becomes an error row', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.dispatch.mockRejectedValueOnce(new ChatApiError(422, 'Validation failed', { input: ['Unknown command /nope'] }))
chat.setDraftText(100, '/nope')
expect(await chat.send()).toBe(true)
expect(chat.ephemeral[100][0]).toMatchObject({ input: '/nope', text: '', error: 'Unknown command /nope' })
expect(api.send).not.toHaveBeenCalled()
})
it('loads the command catalog once a session', async () => {
const chat = await started()
await Promise.all([chat.loadCommands(), chat.loadCommands()])
await chat.loadCommands()
expect(api.commands).toHaveBeenCalledTimes(1)
expect(chat.commands?.map((c) => c.trigger)).toEqual(['demo'])
})
})
describe('threads', () => {
it('loads replies, posts a reply and counts it on the root once', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
const root = chat.findMessage(100, 101)!
await chat.openThread(root)
expect(api.replies).toHaveBeenCalledWith(101)
expect(chat.thread).toEqual({ rootId: 101, conversationId: 100 })
expect(chat.replies[101].map((m) => m.id)).toEqual([151])
chat.setThreadDraftText(101, ' my reply ')
expect(await chat.sendReply(101)).toBe(true)
expect(api.reply).toHaveBeenCalledWith(101, { content: 'my reply' })
expect(chat.replies[101].map((m) => m.id)).toEqual([151, 888])
expect(chat.findMessage(100, 101)?.thread_summary?.reply_count).toBe(1)
// The reply's own realtime echo is not counted again.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(888, 100, { root_id: 101, sender_id: ME }) } })
expect(chat.findMessage(100, 101)?.thread_summary?.reply_count).toBe(1)
// Someone else's reply counts and lands in the open thread.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(889, 100, { root_id: 101 }) } })
expect(chat.findMessage(100, 101)?.thread_summary).toMatchObject({ reply_count: 2, participant_ids: [ME, 9] })
expect(chat.replies[101].map((m) => m.id)).toEqual([151, 888, 889])
// Replies stay out of the main list.
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102])
chat.closeThread()
expect(chat.thread).toBeNull()
})
it('mutes a thread with the server answer', async () => {
const chat = await started()
expect(await chat.setThreadMute(101, true)).toBe(true)
expect(chat.threadMuted[101]).toBe(true)
api.muteThread.mockRejectedValueOnce(new ChatApiError(500, 'boom'))
expect(await chat.setThreadMute(101, false)).toBe(false)
expect(chat.threadMuted[101]).toBe(true)
})
})
describe('pins and reactions', () => {
it('loads a channel\'s pins and pins or unpins a message', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
await chat.loadPins(chat.channels[0])
expect(api.pins).toHaveBeenCalledWith(CONTEXT, 1)
expect(chat.pinIds[1]).toEqual([101])
expect(chat.pinMessages[1].map((m) => m.id)).toEqual([101])
expect(chat.isPinned(chat.findMessage(100, 101)!)).toBe(true)
expect(chat.isPinned(chat.findMessage(100, 102)!)).toBe(false)
api.pins.mockResolvedValueOnce([101, 102])
expect(await chat.togglePin(chat.findMessage(100, 102)!)).toBe(true)
expect(api.pin).toHaveBeenCalledWith(CONTEXT, 1, 102)
expect(chat.pinIds[1]).toEqual([101, 102])
api.pins.mockResolvedValueOnce([102])
await chat.togglePin(chat.findMessage(100, 101)!)
expect(api.unpin).toHaveBeenCalledWith(CONTEXT, 1, 101)
})
it('a refused pin hides the action for the session', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.pin.mockRejectedValueOnce(new ChatApiError(403, 'Forbidden'))
expect(await chat.togglePin(chat.findMessage(100, 102)!)).toBe(false)
expect(chat.pinAllowed).toBe(false)
})
it('toggles the user\'s reaction and takes the server\'s chips', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
await chat.toggleReaction({ id: 101, conversation_id: 100 }, '👍')
expect(api.addReaction).toHaveBeenCalledWith(101, '👍')
expect(chat.findMessage(100, 101)?.reactions).toEqual([{ key: '👍', count: 1, user_ids: [ME] }])
await chat.toggleReaction({ id: 101, conversation_id: 100 }, '👍')
expect(api.removeReaction).toHaveBeenCalledWith(101, '👍')
expect(chat.findMessage(100, 101)?.reactions).toEqual([])
})
it('rolls a failed reaction back', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.addReaction.mockRejectedValueOnce(new ChatApiError(500, 'boom'))
await chat.toggleReaction({ id: 101, conversation_id: 100 }, '❤️')
expect(chat.findMessage(100, 101)?.reactions ?? []).toEqual([])
expect(useChatNotice().current.value?.key).toBe('error.reactionAdd')
})
})

12
tests/support/http.ts Normal file
View File

@@ -0,0 +1,12 @@
// bm's ApiError (src/api/http.ts), for the ported realtime test: it rejects
// the stubbed token route with one, and the route answers its status.
export class ApiError extends Error {
status: number
errors: Record<string, string[]>
constructor(status: number, message: string, errors: Record<string, string[]> = {}) {
super(message)
this.name = 'ApiError'
this.status = status
this.errors = errors
}
}