Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(dashboard): make the socket double record what the page sends
Yudhi Armyndharis068efe3b1350
diff --git a/dashboard/src/hooks/useWebSocket.test.ts b/dashboard/src/hooks/useWebSocket.test.tsnew file mode 100644index 000000000..23ae45a6d--- /dev/null+++ b/dashboard/src/hooks/useWebSocket.test.ts@@ -0,0 +1,92 @@+// The live feed's socket: what the page sends to open it and to join a room, and how it learns that the+// connection is gone for good. The client is the socket.io double (see vite-shim-hooks.mjs), which records+// what the hook sends and lets a test deliver the client's own events.+import '../test-helpers/register-hooks.ts';+import { test, before, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { holdConnect, lastIoCall, lastSocket, resetSocketDouble } from '../test-helpers/socket-io-double.ts';+import type { useWebSocket as useWebSocketFn } from './useWebSocket.ts';++type RTL = typeof import('@testing-library/react');++let rtl: RTL;+let useWebSocket: typeof useWebSocketFn;++before(async () => {+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');+ await installJsdomGlobals();+ // The hook opens no socket without a key.+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ rtl = await import('@testing-library/react');+ ({ useWebSocket } = await import('./useWebSocket.ts'));+});++afterEach(() => {+ rtl.cleanup();+ resetSocketDouble();+});++test('the handshake carries the API key in auth and in a header, never in the URL', () => {+ rtl.renderHook(() => useWebSocket());++ const call = lastIoCall();+ assert.ok(call, 'expected the hook to open a socket');+ assert.ok(call.url.endsWith('/events'), `the socket was opened on ${call.url}`);+ assert.equal(call.url.includes('test-key'), false, 'the key is in the handshake URL');+ assert.equal(call.options.query, undefined, 'the key is in the handshake query');+ assert.deepEqual(call.options.auth, { apiKey: 'test-key' });+ assert.deepEqual(call.options.extraHeaders, { 'X-API-Key': 'test-key' });+});++test('no socket is opened without a key', () => {+ window.sessionStorage.removeItem('openwa_api_key');+ try {+ rtl.renderHook(() => useWebSocket());+ assert.equal(lastIoCall(), null);+ } finally {+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ }+});++test('a room is joined and left with frames of its own, and only once the handshake is done', () => {+ holdConnect();+ const { result } = rtl.renderHook(() => useWebSocket());+ const socket = lastSocket();+ assert.ok(socket, 'expected the hook to open a socket');++ result.current.subscribe('s1', ['message.received']);+ assert.deepEqual(socket.emitted, [], 'a frame went out before the connection was open');++ rtl.act(() => socket.receive('connect'));+ result.current.subscribe('s1', ['message.received']);+ result.current.unsubscribe('s1');+ assert.deepEqual(socket.emitted, [+ { event: 'message', args: [{ type: 'subscribe', sessionId: 's1', events: ['message.received'] }] },+ { event: 'message', args: [{ type: 'unsubscribe', sessionId: 's1' }] },+ ]);+});++test('the connection counts as failed once the client gives up reconnecting, and recovers on a redial', () => {+ holdConnect();+ const { result } = rtl.renderHook(() => useWebSocket());+ const socket = lastSocket();+ assert.ok(socket, 'expected the hook to open a socket');+ rtl.act(() => socket.receive('connect'));+ assert.equal(result.current.isConnected, true);++ // A dropped connection is the client's to retry: nothing is failed yet.+ rtl.act(() => socket.receive('disconnect', 'transport close'));+ assert.equal(result.current.isConnected, false);+ assert.equal(result.current.connectionFailed, false);++ // The attempts run out: only the client's manager says so, never the socket.+ rtl.act(() => socket.io.receive('reconnect_failed'));+ assert.equal(result.current.connectionFailed, true);++ rtl.act(() => result.current.reconnect());+ const redialed = lastSocket();+ assert.ok(redialed && redialed !== socket, 'expected the retry to open a fresh socket');+ rtl.act(() => redialed.receive('connect'));+ assert.equal(result.current.connectionFailed, false);+ assert.equal(result.current.isConnected, true);+});diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 427a1e222..3cfe7a7fd 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -3386,3 +3386,42 @@ test('a message sent from the page scrolls the thread to it, whatever the readerrestoreGeometry();}});++// ── Live feed subscription ───────────────────────────────────────────────────++const MESSAGE_FEED_EVENTS = [+ 'message.received',+ 'message.sent',+ 'message.ack',+ 'message.reaction',+ 'message.revoked',+ 'message.edited',+ 'status.received',+];++/** The payload of every frame the page sent over the socket. */+const feedFrames = (): unknown[] => (lastSocket()?.emitted ?? []).map(frame => frame.args[0]);++test("the page joins the open session's message events once connected, and moves to the next session on a switch", async () => {+ const { screen, fireEvent, waitFor } = rtl;+ twoSessions = true;+ try {+ const { container } = renderChats();+ await screen.findByText('Main (15551234567)');+ await waitFor(() =>+ assert.deepEqual(feedFrames(), [{ type: 'subscribe', sessionId: SESSION.id, events: MESSAGE_FEED_EVENTS }]),+ );++ fireEvent.change(container.querySelector('select.session-selector') as HTMLSelectElement, {+ target: { value: SESSION_2.id },+ });+ await waitFor(() =>+ assert.deepEqual(feedFrames().slice(1), [+ { type: 'unsubscribe', sessionId: SESSION.id },+ { type: 'subscribe', sessionId: SESSION_2.id, events: MESSAGE_FEED_EVENTS },+ ]),+ );+ } finally {+ twoSessions = false;+ }+});diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex 9edc11d56..b564f9385 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -20,6 +20,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { Session } from '../services/api';import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';import { holdConnect, lastSocket, resetSocketDouble } from '../test-helpers/socket-io-double.ts';+import { SESSION_FEED_EVENTS } from '../utils/sessionFeedSubscription.ts';// ── Fixtures + fetch stub ────────────────────────────────────────────────────@@ -2153,3 +2154,45 @@ test('Sessions.css aligns text to the text direction, not a physical side', () =const css = readFileSync(new URL('./Sessions.css', import.meta.url), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');assert.doesNotMatch(css, /text-align\s*:\s*(left|right)\b/, 'text is aligned to a physical side');});++// ── Live feed subscription ───────────────────────────────────────────────────++/** The payload of every frame the page sent over the socket. */+const feedFrames = (): unknown[] => (lastSocket()?.emitted ?? []).map(frame => frame.args[0]);++test('the page joins the live session feed once connected, with the events it renders', async () => {+ const { screen, waitFor } = rtl;+ resetFetchCalls();+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ renderSessions();++ await screen.findByText('new-device');+ await waitFor(() =>+ assert.deepEqual(feedFrames(), [{ type: 'subscribe', sessionId: '*', events: [...SESSION_FEED_EVENTS] }]),+ );+});++test('a key refused the wildcard room joins each listed session instead', async () => {+ const { screen, waitFor, act } = rtl;+ resetFetchCalls();+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ renderSessions();++ await screen.findByText('new-device');+ await waitFor(() => assert.equal(feedFrames().length, 1));+ const socket = lastSocket();+ assert.ok(socket, 'expected the page to have opened a socket');+ act(() =>+ socket.receive('message', { type: 'error', code: 'FORBIDDEN_SESSION', message: 'Scoped keys cannot join *' }),+ );++ const joined = (): string[] =>+ feedFrames()+ .slice(1)+ .map(frame => (frame as { sessionId: string }).sessionId)+ .sort();+ await waitFor(() => assert.deepEqual(joined(), SESSIONS.map(session => session.id).sort()));+ for (const frame of feedFrames().slice(1)) {+ assert.deepEqual((frame as { events: string[] }).events, [...SESSION_FEED_EVENTS]);+ }+});diff --git a/dashboard/src/test-helpers/socket-io-double.ts b/dashboard/src/test-helpers/socket-io-double.tsindex e5600ec37..f3007a951 100644--- a/dashboard/src/test-helpers/socket-io-double.ts+++ b/dashboard/src/test-helpers/socket-io-double.ts@@ -7,25 +7,28 @@* which is how a chat cache read as the wrong shape reached review with green CI. This double never* dials; it records listeners and lets a test deliver an envelope with `lastSocket().receive(...)`.*+ * It keeps what the page sends as well, so a test can fail when the page stops sending it: the arguments+ * of `io()` (`lastIoCall()`, which carries the handshake's API key) and every `emit` of the socket+ * (`lastSocket().emitted`, the subscribe and unsubscribe frames). The manager (`socket.io`) takes+ * listeners too and delivers its own events, as in `lastSocket().io.receive('reconnect_failed')`.+ *+ * Like the real client, a socket is not connected until 'connect' is delivered to it, and is not after+ * 'disconnect' is.+ ** Tests that do not set `sessionStorage['openwa_api_key']` never reach `io()` at all (useWebSocket* bails first), so aliasing this in changes nothing for them.*/type Listener = (...args: unknown[]) => void;-class FakeSocket {- connected = true;+/** The listeners of one emitter, and the delivery of an event to them. */+class Emitter {private listeners = new Map<string, Set<Listener>>();- /** The manager namespace (`socket.io.on('reconnect_failed', …)`). */- readonly io = { on: (): void => undefined };on(event: string, listener: Listener): this {const set = this.listeners.get(event) ?? new Set<Listener>();set.add(listener);this.listeners.set(event, set);- // The real client fires 'connect' asynchronously after the handshake; do it on registration so- // a page that gates its subscribe on connection reaches the same state.- if (event === 'connect' && autoConnect) queueMicrotask(() => listener());return this;}@@ -35,7 +38,42 @@ class FakeSocket {return this;}- emit(): this {+ /** Deliver a frame to whatever the page registered for `event`. */+ receive(event: string, ...args: unknown[]): void {+ for (const listener of this.listeners.get(event) ?? []) listener(...args);+ }+}++/** Where the client's reconnection events (`reconnect_failed` and the like) are delivered. */+class FakeManager extends Emitter {}++class FakeSocket extends Emitter {+ connected = false;+ readonly io = new FakeManager();+ /** Every frame the page sent with `emit`, in order. */+ readonly emitted: Array<{ event: string; args: unknown[] }> = [];++ override on(event: string, listener: Listener): this {+ super.on(event, listener);+ // The real client fires 'connect' asynchronously after the handshake; do it on registration so+ // a page that gates its subscribe on connection reaches the same state.+ if (event === 'connect' && autoConnect) {+ queueMicrotask(() => {+ this.connected = true;+ listener();+ });+ }+ return this;+ }++ override receive(event: string, ...args: unknown[]): void {+ if (event === 'connect') this.connected = true;+ if (event === 'disconnect') this.connected = false;+ super.receive(event, ...args);+ }++ emit(event: string, ...args: unknown[]): this {+ this.emitted.push({ event, args });return this;}@@ -43,18 +81,15 @@ class FakeSocket {this.connected = false;return this;}-- /** Deliver a server frame to whatever the page registered for `event`. */- receive(event: string, ...args: unknown[]): void {- for (const listener of this.listeners.get(event) ?? []) listener(...args);- }}let last: FakeSocket | null = null;+let lastCall: { url: string; options: Record<string, unknown> } | null = null;let autoConnect = true;-export function io(): FakeSocket {+export function io(url = '', options: Record<string, unknown> = {}): FakeSocket {last = new FakeSocket();+ lastCall = { url, options };return last;}@@ -63,6 +98,11 @@ export function lastSocket(): FakeSocket | null {return last;}+/** What the page passed to its most recent `io()`, or null if it never dialled. */+export function lastIoCall(): { url: string; options: Record<string, unknown> } | null {+ return lastCall;+}+/*** Stop sockets from firing 'connect' on registration, so a test can deliver it with* `receive('connect')` in the same batch as the frames a real server sends alongside it.@@ -73,6 +113,7 @@ export function holdConnect(): void {export function resetSocketDouble(): void {last = null;+ lastCall = null;autoConnect = true;}