Debian Codegraph @

test/tests/ext/hx-ws.js

raw symbols SCIP
1 describe('hx-ws WebSocket extension', function() {
2
3 let extBackup;
4 let mockWebSocket;
5 let mockWebSocketInstances = [];
6
7 before(async () => {
8 extBackup = backupExtensions();
9 clearExtensions();
10
11 // Mock WebSocket
12 mockWebSocket = class MockWebSocket {
13 static CONNECTING = 0;
14 static OPEN = 1;
15 static CLOSING = 2;
16 static CLOSED = 3;
17
18 constructor(url) {
19 this.url = url;
20 this.readyState = MockWebSocket.CONNECTING;
21 this.listeners = {};
22 mockWebSocketInstances.push(this);
23
24 // Simulate connection after a short delay
25 setTimeout(() => {
26 this.readyState = MockWebSocket.OPEN;
27 this.triggerEvent('open', {});
28 }, 10);
29 }
30
31 addEventListener(event, handler) {
32 if (!this.listeners[event]) this.listeners[event] = [];
33 this.listeners[event].push(handler);
34 }
35
36 removeEventListener(event, handler) {
37 if (!this.listeners[event]) return;
38 this.listeners[event] = this.listeners[event].filter(h => h !== handler);
39 }
40
41 send(data) {
42 if (this.readyState !== MockWebSocket.OPEN) {
43 throw new Error('WebSocket is not open');
44 }
45 this.lastSent = data;
46 }
47
48 close(code = 1000, reason = '') {
49 this.readyState = MockWebSocket.CLOSED;
50 this.triggerEvent('close', { code, reason });
51 }
52
53 triggerEvent(event, data) {
54 if (this.listeners[event]) {
55 // Add target property to event object for proper event handling
56 const eventObj = { ...data, target: this };
57 this.listeners[event].forEach(handler => handler(eventObj));
58 }
59 }
60
61 // Helper to simulate receiving a message (JSON)
62 simulateMessage(data) {
63 this.triggerEvent('message', { data: JSON.stringify(data) });
64 }
65
66 // Helper to simulate receiving raw (non-JSON) message
67 simulateRawMessage(data) {
68 this.triggerEvent('message', { data: data });
69 }
70 };
71
72 window.WebSocket = mockWebSocket;
73
74 // CRITICAL: Approve extension BEFORE loading it
75 // Extension registration silently fails if not approved
76 htmx.config.extensions = 'ws';
77 htmx.__approvedExt = 'ws';
78
79 let script = document.createElement('script');
80 script.src = '../src/ext/hx-ws.js';
81 await new Promise(resolve => {
82 script.onload = resolve;
83 document.head.appendChild(script);
84 });
85
86 // Verify extension loaded and registered
87 if (!htmx.ext || !htmx.ext.ws) {
88 throw new Error('WebSocket extension failed to load');
89 }
90 if (!htmx.__registeredExt.has('ws')) {
91 throw new Error('WebSocket extension failed to register - check approval');
92 }
93 });
94
95 after(() => {
96 restoreExtensions(extBackup);
97 });
98
99 beforeEach(() => {
100 setupTest(this.currentTest);
101 mockWebSocketInstances = [];
102 // Reset global WS config to avoid test bleed
103 htmx.config.ws = {};
104 if (htmx.ext && htmx.ext.ws && htmx.ext.ws.getRegistry) {
105 htmx.ext.ws.getRegistry().clear();
106 }
107 });
108
109 afterEach(() => {
110 cleanupTest(this.currentTest);
111 // Close all mock WebSocket connections
112 mockWebSocketInstances.forEach(ws => {
113 if (ws.readyState === mockWebSocket.OPEN) {
114 ws.close();
115 }
116 });
117 });
118
119 // Helper to check if URL ends with expected path (accounts for URL normalization)
120 function urlEndsWith(url, expectedPath) {
121 return url.endsWith(expectedPath);
122 }
123
124 // Helper to get normalized URL for registry lookups
125 function getNormalizedUrl(path) {
126 // The extension normalizes /path to ws://host/path or wss://host/path
127 let protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
128 return protocol + '//' + window.location.host + path;
129 }
130
131 // ========================================
132 // 1. CONNECTION LIFECYCLE TESTS
133 // ========================================
134
135 describe('Connection Lifecycle', function() {
136
137 it('auto-connects on load by default', async function() {
138 let div = createProcessedHTML('<div hx-ws:connect="/ws/test"></div>');
139 await htmx.timeout(50);
140 assert.equal(mockWebSocketInstances.length, 1);
141 assert.isTrue(urlEndsWith(mockWebSocketInstances[0].url, '/ws/test'), 'URL should end with /ws/test');
142 });
143
144 it('connects on custom trigger event', async function() {
145 let div = createProcessedHTML('<div hx-ws:connect="/ws/test" hx-trigger="click"></div>');
146 await htmx.timeout(20);
147 assert.equal(mockWebSocketInstances.length, 0);
148
149 div.click();
150 await htmx.timeout(50);
151 assert.equal(mockWebSocketInstances.length, 1);
152 });
153
154 it('connects with delay modifier', async function() {
155 createProcessedHTML('<div hx-ws:connect="/ws/test" hx-trigger="load delay:100ms"></div>');
156 await htmx.timeout(20);
157 assert.equal(mockWebSocketInstances.length, 0, 'Should not connect before delay');
158 await htmx.timeout(120);
159 assert.equal(mockWebSocketInstances.length, 1, 'Should connect after delay');
160 });
161
162 it('connects on click once modifier', async function() {
163 let div = createProcessedHTML('<div hx-ws:connect="/ws/test" hx-trigger="click once"></div>');
164 await htmx.timeout(20);
165 assert.equal(mockWebSocketInstances.length, 0, 'Should not connect before click');
166
167 div.click();
168 await htmx.timeout(50);
169 assert.equal(mockWebSocketInstances.length, 1, 'Should connect on first click');
170
171 // Reset to check that second click doesn't create new connection attempt
172 // (once modifier removes the listener after first fire)
173 div._htmx.ws.url = null;
174 div._htmx.ws.initialized = false;
175 div.click();
176 await htmx.timeout(50);
177 assert.equal(mockWebSocketInstances.length, 1, 'Second click should not reconnect (once modifier)');
178 });
179
180 it('reuses connection for same URL', async function() {
181 let container = createProcessedHTML(`
182 <div>
183 <div id="div1" hx-ws:connect="/ws/shared"></div>
184 <div id="div2" hx-ws:connect="/ws/shared"></div>
185 </div>
186 `);
187 await htmx.timeout(50);
188 assert.equal(mockWebSocketInstances.length, 1, 'Should only create one WebSocket for shared URL');
189 });
190
191 it('creates separate connections for different URLs', async function() {
192 let container = createProcessedHTML(`
193 <div>
194 <div id="div1" hx-ws:connect="/ws/channel1"></div>
195 <div id="div2" hx-ws:connect="/ws/channel2"></div>
196 </div>
197 `);
198 await htmx.timeout(50);
199 assert.equal(mockWebSocketInstances.length, 2);
200 });
201
202 it('closes connection when last element is removed', async function() {
203 let container = createProcessedHTML(`
204 <div id="container">
205 <div id="div1" hx-ws:connect="/ws/test"></div>
206 </div>
207 `);
208 await htmx.timeout(50);
209 assert.equal(mockWebSocketInstances.length, 1);
210
211 let ws = mockWebSocketInstances[0];
212
213 await htmx.swap({
214 text: '',
215 target: document.getElementById('container'),
216 swap: 'innerHTML'
217 });
218 await htmx.timeout(50);
219
220 assert.equal(ws.readyState, mockWebSocket.CLOSED);
221 });
222
223 it('keeps connection open when one of multiple elements is removed', async function() {
224 let container = createProcessedHTML(`
225 <div id="container">
226 <div id="div1" hx-ws:connect="/ws/shared"></div>
227 <div id="div2" hx-ws:connect="/ws/shared"></div>
228 </div>
229 `);
230 await htmx.timeout(50);
231
232 let ws = mockWebSocketInstances[0];
233
234 await htmx.swap({
235 text: '',
236 target: document.getElementById('div1'),
237 swap: 'delete'
238 });
239 await htmx.timeout(50);
240
241 assert.equal(ws.readyState, mockWebSocket.OPEN);
242 });
243
244 it('fires error events on live element after original element is removed', async function() {
245 let container = createProcessedHTML(`
246 <div id="container">
247 <div id="div1" hx-ws:connect="/ws/shared"></div>
248 <div id="div2" hx-ws:connect="/ws/shared"></div>
249 </div>
250 `);
251 await htmx.timeout(50);
252
253 // Listen on div2 for error events
254 let errorOnDiv2 = false;
255 document.getElementById('div2').addEventListener('htmx:ws:error', () => {
256 errorOnDiv2 = true;
257 });
258
259 // Remove div1 (the element captured as firstElement in createWebSocket)
260 // but keep the connection alive via div2
261 await htmx.swap({
262 text: '',
263 target: document.getElementById('div1'),
264 swap: 'delete'
265 });
266 await htmx.timeout(50);
267
268 // Trigger an error on the still-open socket
269 let ws = mockWebSocketInstances[0];
270 ws.triggerEvent('error', { message: 'test error' });
271 await htmx.timeout(20);
272
273 // The error event should bubble from div2, not the removed div1
274 assert.isTrue(errorOnDiv2, 'Error event should fire on the remaining live element');
275 });
276 });
277
278 // ========================================
279 // 2. MESSAGE SENDING TESTS
280 // ========================================
281
282 describe('Message Sending', function() {
283
284 it('sends message on load trigger (waits for socket open)', async function() {
285 let div = createProcessedHTML(`
286 <div hx-ws:connect="/ws/test">
287 <div id="load-sender" hx-ws:send hx-trigger="load" hx-vals='{"test": "load"}'></div>
288 </div>
289 `);
290 await htmx.timeout(50);
291
292 let ws = mockWebSocketInstances[0];
293 assert.isDefined(ws.lastSent, 'Should have sent a message on load');
294 let sent = JSON.parse(ws.lastSent);
295 assert.equal(sent.body.test, 'load');
296 });
297
298 it('sends message with hx-ws:send on form submit', async function() {
299 let div = createProcessedHTML(`
300 <div hx-ws:connect="/ws/chat">
301 <form hx-ws:send hx-trigger="submit">
302 <input name="message" value="hello">
303 <button type="submit">Send</button>
304 </form>
305 </div>
306 `);
307 await htmx.timeout(50);
308
309 let form = div.querySelector('form');
310 form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
311 await htmx.timeout(20);
312
313 let ws = mockWebSocketInstances[0];
314 assert.isDefined(ws.lastSent);
315
316 let sent = JSON.parse(ws.lastSent);
317 assert.isDefined(sent.headers['HX-Request-ID']);
318 assert.equal(sent.body.message, 'hello');
319 assert.isDefined(sent.headers['HX-Source']);
320 assert.isDefined(sent.headers['HX-Current-URL']);
321 });
322
323 it('includes hx-vals in sent message', async function() {
324 let div = createProcessedHTML(`
325 <div hx-ws:connect="/ws/test">
326 <button hx-ws:send hx-vals='{"extra": "data"}' hx-trigger="click">Send</button>
327 </div>
328 `);
329 await htmx.timeout(50);
330
331 let button = div.querySelector('button');
332 button.click();
333 await htmx.timeout(20);
334
335 let ws = mockWebSocketInstances[0];
336 let sent = JSON.parse(ws.lastSent);
337 assert.equal(sent.body.extra, 'data');
338 });
339
340 it('preserves JS types (number, boolean) from hx-vals', async function() {
341 let div = createProcessedHTML(`
342 <div hx-ws:connect="/ws/test">
343 <button hx-ws:send hx-vals='{"count": 42, "active": true, "ratio": 1.5}' hx-trigger="click">Send</button>
344 </div>
345 `);
346 await htmx.timeout(50);
347
348 div.querySelector('button').click();
349 await htmx.timeout(20);
350
351 let sent = JSON.parse(mockWebSocketInstances[0].lastSent);
352 assert.strictEqual(sent.body.count, 42, 'number should not be coerced to string');
353 assert.strictEqual(sent.body.active, true, 'boolean should not be coerced to string');
354 assert.strictEqual(sent.body.ratio, 1.5, 'float should not be coerced to string');
355 });
356
357 it('hx-vals overrides form field with correct type', async function() {
358 let div = createProcessedHTML(`
359 <div hx-ws:connect="/ws/test">
360 <form hx-ws:send hx-vals='{"count": 99}' hx-trigger="submit">
361 <input name="count" value="1">
362 </form>
363 </div>
364 `);
365 await htmx.timeout(50);
366
367 div.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
368 await htmx.timeout(20);
369
370 let sent = JSON.parse(mockWebSocketInstances[0].lastSent);
371 assert.strictEqual(sent.body.count, 99, 'hx-vals number should win over form string value');
372 });
373
374 it('finds connection from nearest ancestor', async function() {
375 let div = createProcessedHTML(`
376 <div hx-ws:connect="/ws/outer">
377 <div>
378 <button id="btn" hx-ws:send hx-trigger="click">Send</button>
379 </div>
380 </div>
381 `);
382 await htmx.timeout(50);
383
384 document.getElementById('btn').click();
385 await htmx.timeout(20);
386
387 let ws = mockWebSocketInstances[0];
388 assert.isDefined(ws.lastSent);
389 });
390
391 it('creates own connection if hx-ws:send has path', async function() {
392 let button = createProcessedHTML('<button hx-ws:send="/ws/direct" hx-trigger="click">Send</button>');
393 button.click();
394 await htmx.timeout(50);
395
396 assert.equal(mockWebSocketInstances.length, 1);
397 assert.isTrue(urlEndsWith(mockWebSocketInstances[0].url, '/ws/direct'), 'URL should end with /ws/direct');
398 });
399
400 it('send respects delay modifier', async function() {
401 let div = createProcessedHTML(`
402 <div hx-ws:connect="/ws/test">
403 <button id="delayed-btn" hx-ws:send hx-trigger="click delay:100ms">Send</button>
404 </div>
405 `);
406 await htmx.timeout(50);
407 let ws = mockWebSocketInstances[0];
408
409 document.getElementById('delayed-btn').click();
410 await htmx.timeout(20);
411 assert.isUndefined(ws.lastSent, 'Should not send before delay');
412
413 await htmx.timeout(120);
414 assert.isDefined(ws.lastSent, 'Should send after delay');
415 });
416
417 it('includes HX-Source with tag#id format', async function() {
418 let div = createProcessedHTML(`
419 <div hx-ws:connect="/ws/test">
420 <button id="my-button" hx-ws:send hx-trigger="click">Send</button>
421 </div>
422 `);
423 await htmx.timeout(50);
424
425 document.getElementById('my-button').click();
426 await htmx.timeout(20);
427
428 let ws = mockWebSocketInstances[0];
429 let sent = JSON.parse(ws.lastSent);
430 assert.equal(sent.headers['HX-Source'], 'button#my-button');
431 });
432
433 it('generates unique request_id for each message', async function() {
434 let div = createProcessedHTML(`
435 <div hx-ws:connect="/ws/test">
436 <button hx-ws:send hx-trigger="click">Send</button>
437 </div>
438 `);
439 await htmx.timeout(50);
440
441 let button = div.querySelector('button');
442 button.click();
443 await htmx.timeout(20);
444 let firstId = JSON.parse(mockWebSocketInstances[0].lastSent).headers['HX-Request-ID'];
445
446 button.click();
447 await htmx.timeout(20);
448 let secondId = JSON.parse(mockWebSocketInstances[0].lastSent).headers['HX-Request-ID'];
449
450 assert.notEqual(firstId, secondId);
451 });
452
453 it('includes HX-Target when hx-target is set', async function() {
454 let div = createProcessedHTML(`
455 <div hx-ws:connect="/ws/test">
456 <button hx-ws:send hx-trigger="click" hx-target="#result">Send</button>
457 <div id="result"></div>
458 </div>
459 `);
460 await htmx.timeout(50);
461
462 div.querySelector('button').click();
463 await htmx.timeout(20);
464
465 let ws = mockWebSocketInstances[0];
466 let sent = JSON.parse(ws.lastSent);
467 assert.equal(sent.headers['HX-Target'], 'div#result');
468 });
469
470 it('includes async hx-vals (js:) in sent message', async function() {
471 window.testAsyncValue = () => new Promise(resolve => setTimeout(() => resolve('asyncValue'), 10));
472
473 let div = createProcessedHTML(`
474 <div hx-ws:connect="/ws/test">
475 <button hx-ws:send hx-vals='js:{asyncField: await testAsyncValue()}' hx-trigger="click">Send</button>
476 </div>
477 `);
478 await htmx.timeout(50);
479
480 let button = div.querySelector('button');
481 button.click();
482 await htmx.timeout(20);
483
484 let ws = mockWebSocketInstances[0];
485 let sent = JSON.parse(ws.lastSent);
486 assert.equal(sent.body.asyncField, 'asyncValue');
487
488 delete window.testAsyncValue;
489 });
490 });
491
492 // ========================================
493 // 3. MESSAGE RECEIVING & HTML HANDLING
494 // ========================================
495
496 describe('Message Receiving and HTML Handling', function() {
497
498 it('swaps HTML partial into target element', async function() {
499 let div = createProcessedHTML(`
500 <div hx-ws:connect="/ws/test" hx-target="#messages">
501 <div id="messages"></div>
502 </div>
503 `);
504 await htmx.timeout(50);
505
506 let ws = mockWebSocketInstances[0];
507 ws.simulateMessage({
508 content: '<hx-partial id="messages"><p>New message</p></hx-partial>'
509 });
510 await htmx.timeout(20);
511
512 let messages = document.getElementById('messages');
513 assert.include(messages.innerHTML, 'New message');
514 });
515
516 it('uses default swap strategy (innerHTML)', async function() {
517 let div = createProcessedHTML(`
518 <div hx-ws:connect="/ws/test" hx-target="#content">
519 <div id="content">Old</div>
520 </div>
521 `);
522 await htmx.timeout(50);
523
524 let ws = mockWebSocketInstances[0];
525 ws.simulateMessage({
526 content: '<hx-partial id="content">New</hx-partial>'
527 });
528 await htmx.timeout(20);
529
530 assert.equal(document.getElementById('content').textContent, 'New');
531 });
532
533 it('respects hx-swap attribute on partial', async function() {
534 let container = createProcessedHTML(`
535 <div hx-ws:connect="/ws/test" hx-target="#list">
536 <div id="list"><p>Item 1</p></div>
537 </div>
538 `);
539 await htmx.timeout(50);
540
541 let ws = mockWebSocketInstances[0];
542 ws.simulateMessage({
543 content: '<hx-partial id="list" hx-swap="beforeend"><p>Item 2</p></hx-partial>'
544 });
545 await htmx.timeout(20);
546
547 let list = document.getElementById('list');
548 assert.include(list.innerHTML, 'Item 1');
549 assert.include(list.innerHTML, 'Item 2');
550 });
551
552 it('handles multiple partials in one message', async function() {
553 let container = createProcessedHTML(`
554 <div hx-ws:connect="/ws/test">
555 <div id="header"></div>
556 <div id="content"></div>
557 </div>
558 `);
559 await htmx.timeout(50);
560
561 let ws = mockWebSocketInstances[0];
562 ws.simulateMessage({
563 content: `
564 <hx-partial id="header"><h1>Title</h1></hx-partial>
565 <hx-partial id="content"><p>Body</p></hx-partial>
566 `
567 });
568 await htmx.timeout(20);
569
570 assert.include(document.getElementById('header').innerHTML, 'Title');
571 assert.include(document.getElementById('content').innerHTML, 'Body');
572 });
573
574 it('executes script tags in swapped content', async function() {
575 // Clean up any existing test variable
576 delete window.wsScriptTestValue;
577
578 let container = createProcessedHTML(`
579 <div hx-ws:connect="/ws/test" hx-target="#content">
580 <div id="content"></div>
581 </div>
582 `);
583 await htmx.timeout(50);
584
585 let ws = mockWebSocketInstances[0];
586 ws.simulateMessage({
587 content: '<hx-partial id="content"><div>Content</div><script>window.wsScriptTestValue = "executed";</script></hx-partial>'
588 });
589 await htmx.timeout(20);
590
591 assert.equal(window.wsScriptTestValue, 'executed', 'Script tag should have been executed');
592
593 // Clean up
594 delete window.wsScriptTestValue;
595 });
596
597 it('executes multiple script tags in swapped content', async function() {
598 // Clean up any existing test variables
599 delete window.wsScriptTest1;
600 delete window.wsScriptTest2;
601
602 let container = createProcessedHTML(`
603 <div hx-ws:connect="/ws/test" hx-target="#content">
604 <div id="content"></div>
605 </div>
606 `);
607 await htmx.timeout(50);
608
609 let ws = mockWebSocketInstances[0];
610 ws.simulateMessage({
611 content: '<hx-partial id="content"><script>window.wsScriptTest1 = 1;</script><div>Content</div><script>window.wsScriptTest2 = 2;</script></hx-partial>'
612 });
613 await htmx.timeout(20);
614
615 assert.equal(window.wsScriptTest1, 1, 'First script tag should have been executed');
616 assert.equal(window.wsScriptTest2, 2, 'Second script tag should have been executed');
617
618 // Clean up
619 delete window.wsScriptTest1;
620 delete window.wsScriptTest2;
621 });
622
623 it('preserves script tag attributes when executing', async function() {
624 // Clean up any existing test variable
625 delete window.wsScriptAttrTest;
626
627 let container = createProcessedHTML(`
628 <div hx-ws:connect="/ws/test" hx-target="#content">
629 <div id="content"></div>
630 </div>
631 `);
632 await htmx.timeout(50);
633
634 let ws = mockWebSocketInstances[0];
635 ws.simulateMessage({
636 content: '<hx-partial id="content"><script data-testattr="testvalue">window.wsScriptAttrTest = document.currentScript.getAttribute("data-testattr");</script></hx-partial>'
637 });
638 await htmx.timeout(20);
639
640 assert.equal(window.wsScriptAttrTest, 'testvalue', 'Script should access its own attributes');
641
642 // Clean up
643 delete window.wsScriptAttrTest;
644 });
645
646 it('matches request_id for request/response pattern', async function() {
647 let container = createProcessedHTML(`
648 <div hx-ws:connect="/ws/test">
649 <button id="btn" hx-ws:send hx-trigger="click" hx-target="#result">Send</button>
650 <div id="result"></div>
651 </div>
652 `);
653 await htmx.timeout(50);
654
655 let button = document.getElementById('btn');
656 button.click();
657 await htmx.timeout(20);
658
659 let ws = mockWebSocketInstances[0];
660 let sent = JSON.parse(ws.lastSent);
661
662 ws.simulateMessage({
663 content: '<hx-partial id="result">Response</hx-partial>',
664 'HX-Request-ID': sent.headers['HX-Request-ID']
665 });
666 await htmx.timeout(20);
667
668 assert.include(document.getElementById('result').innerHTML, 'Response');
669 });
670 });
671
672 // ========================================
673 // 4. CUSTOM CHANNEL TESTS
674 // ========================================
675
676 describe('Custom Channels', function() {
677
678 it('does not swap JSON messages without content field', async function() {
679 let container = createProcessedHTML(`
680 <div hx-ws:connect="/ws/test" hx-target="#content">
681 <div id="content">Original</div>
682 </div>
683 `);
684 await htmx.timeout(50);
685
686 let eventFired = false;
687 let eventMessage = null;
688 container.addEventListener('htmx:after:ws:message', (e) => {
689 eventFired = true;
690 eventMessage = e.detail.message.json;
691 });
692
693 let ws = mockWebSocketInstances[0];
694 ws.simulateMessage({ type: 'notification', text: 'hello' });
695 await htmx.timeout(20);
696
697 assert.isTrue(eventFired);
698 assert.equal(eventMessage.type, 'notification');
699 assert.equal(document.getElementById('content').textContent, 'Original', 'Data-only messages should not swap');
700 });
701
702 it('fires htmx:before:ws:message for all messages', async function() {
703 let container = createProcessedHTML(`
704 <div hx-ws:connect="/ws/test"></div>
705 `);
706 await htmx.timeout(50);
707
708 let beforeFired = false;
709 container.addEventListener('htmx:before:ws:message', () => {
710 beforeFired = true;
711 });
712
713 let ws = mockWebSocketInstances[0];
714 ws.simulateMessage({
715 content: '<hx-partial id="test">Test</hx-partial>'
716 });
717 await htmx.timeout(20);
718
719 assert.isTrue(beforeFired);
720 });
721
722 it('allows canceling message processing via event', async function() {
723 let container = createProcessedHTML(`
724 <div hx-ws:connect="/ws/test" hx-target="#content">
725 <div id="content">Original</div>
726 </div>
727 `);
728 await htmx.timeout(50);
729
730 container.addEventListener('htmx:before:ws:message', (e) => {
731 e.preventDefault();
732 });
733
734 let ws = mockWebSocketInstances[0];
735 ws.simulateMessage({
736 content: '<hx-partial id="content">Changed</hx-partial>'
737 });
738 await htmx.timeout(20);
739
740 assert.equal(document.getElementById('content').textContent, 'Original');
741 });
742
743 it('uses swap:none for raw HTML when no hx-target is set', async function() {
744 let container = createProcessedHTML(`
745 <div hx-ws:connect="/ws/test">
746 <div id="content">Original</div>
747 </div>
748 `);
749 await htmx.timeout(50);
750
751 let ws = mockWebSocketInstances[0];
752 ws.simulateRawMessage('<div id="content">Should not replace</div>');
753 await htmx.timeout(20);
754
755 assert.equal(document.getElementById('content').textContent, 'Original');
756 });
757
758 it('swaps raw HTML into hx-target when set', async function() {
759 let container = createProcessedHTML(`
760 <div hx-ws:connect="/ws/test" hx-target="#content">
761 <div id="content">Original</div>
762 </div>
763 `);
764 await htmx.timeout(50);
765
766 let ws = mockWebSocketInstances[0];
767 ws.simulateRawMessage('<p>Updated</p>');
768 await htmx.timeout(20);
769
770 assert.include(document.getElementById('content').innerHTML, 'Updated');
771 });
772 });
773
774 // ========================================
775 // 5. ERROR HANDLING & RECONNECTION
776 // ========================================
777
778 describe('Error Handling and Reconnection', function() {
779
780 it('emits htmx:ws:error on connection error', async function() {
781 let container = createProcessedHTML(`
782 <div hx-ws:connect="/ws/test"></div>
783 `);
784
785 let errorFired = false;
786 container.addEventListener('htmx:ws:error', () => {
787 errorFired = true;
788 });
789
790 await htmx.timeout(50);
791 let ws = mockWebSocketInstances[0];
792 ws.triggerEvent('error', { message: 'Connection failed' });
793 await htmx.timeout(20);
794
795 assert.isTrue(errorFired);
796 });
797
798 it('emits htmx:ws:close on connection close', async function() {
799 let container = createProcessedHTML(`
800 <div hx-ws:connect="/ws/test"></div>
801 `);
802
803 let closeFired = false;
804 container.addEventListener('htmx:ws:close', () => {
805 closeFired = true;
806 });
807
808 await htmx.timeout(50);
809 let ws = mockWebSocketInstances[0];
810 ws.close();
811 await htmx.timeout(20);
812
813 assert.isTrue(closeFired);
814 });
815
816 it('attempts reconnection on close when config.reconnect is true', async function() {
817 htmx.config.ws = { reconnect: true, reconnectDelay: 50 };
818
819 let container = createProcessedHTML(`
820 <div hx-ws:connect="/ws/test"></div>
821 `);
822 await htmx.timeout(50);
823
824 let firstWs = mockWebSocketInstances[0];
825 firstWs.close();
826 await htmx.timeout(100);
827
828 assert.isTrue(mockWebSocketInstances.length > 1, 'Should create new WebSocket for reconnection');
829 });
830
831 it('does not reconnect when config.reconnect is false', async function() {
832 htmx.config.ws = { reconnect: false };
833
834 let container = createProcessedHTML(`
835 <div hx-ws:connect="/ws/test"></div>
836 `);
837 await htmx.timeout(50);
838
839 let firstWs = mockWebSocketInstances[0];
840 firstWs.close();
841 await htmx.timeout(100);
842
843 assert.equal(mockWebSocketInstances.length, 1);
844 });
845
846 it('emits htmx:before:ws:connection with attempt > 0 on reconnect', async function() {
847 htmx.config.ws = { reconnect: true, reconnectDelay: 50 };
848
849 let container = createProcessedHTML(`
850 <div hx-ws:connect="/ws/test"></div>
851 `);
852
853 let reconnectAttempt = null;
854 container.addEventListener('htmx:before:ws:connection', (e) => {
855 if (e.detail.connection.attempt > 0) {
856 reconnectAttempt = e.detail.connection.attempt;
857 }
858 });
859
860 await htmx.timeout(50);
861 let firstWs = mockWebSocketInstances[0];
862 firstWs.close();
863 await htmx.timeout(100);
864
865 assert.equal(reconnectAttempt, 1);
866 });
867
868 it('uses exponential backoff for reconnection', async function() {
869 htmx.config.ws = {
870 reconnect: true,
871 reconnectDelay: 100,
872 reconnectMaxDelay: 1000
873 };
874
875 let container = createProcessedHTML(`
876 <div hx-ws:connect="/ws/test"></div>
877 `);
878 await htmx.timeout(50);
879
880 let reconnectTimes = [];
881 container.addEventListener('htmx:before:ws:connection', (e) => {
882 if (e.detail.connection.attempt > 0) {
883 reconnectTimes.push(Date.now());
884 }
885 });
886
887 // First close
888 let ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
889 ws.close();
890 await htmx.timeout(200);
891
892 // Second close
893 ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
894 ws.close();
895 await htmx.timeout(300);
896
897 // Third close
898 ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
899 ws.close();
900 await htmx.timeout(500);
901
902 // Verify delays are increasing
903 assert.isTrue(reconnectTimes.length >= 3, 'Should have at least 3 reconnect attempts');
904 let firstDelay = reconnectTimes[1] - reconnectTimes[0];
905 let secondDelay = reconnectTimes[2] - reconnectTimes[1];
906 assert.isTrue(secondDelay >= firstDelay, 'Second delay should be >= first delay');
907 });
908
909 it('emits htmx:ws:error when send fails', async function() {
910 let container = createProcessedHTML(`
911 <div hx-ws:connect="/ws/test">
912 <button hx-ws:send hx-trigger="click">Send</button>
913 </div>
914 `);
915 await htmx.timeout(50);
916
917 let errorFired = false;
918 container.addEventListener('htmx:ws:error', () => {
919 errorFired = true;
920 });
921
922 // Close the connection
923 let ws = mockWebSocketInstances[0];
924 ws.close();
925 await htmx.timeout(20);
926
927 // Try to send
928 container.querySelector('button').click();
929 await htmx.timeout(20);
930
931 assert.isTrue(errorFired);
932 });
933
934 it('swaps non-JSON messages as raw HTML into hx-target', async function() {
935 let container = createProcessedHTML(`
936 <div hx-ws:connect="/ws/test" hx-target="#content">
937 <div id="content">Original</div>
938 </div>
939 `);
940 await htmx.timeout(50);
941
942 let ws = mockWebSocketInstances[0];
943 ws.simulateRawMessage('<hx-partial id="content"><p>Raw HTML update</p></hx-partial>');
944 await htmx.timeout(20);
945
946 assert.include(document.getElementById('content').innerHTML, 'Raw HTML update');
947 });
948
949 it('uses swap:none for non-JSON messages without hx-target', async function() {
950 let container = createProcessedHTML(`
951 <div id="ws-conn" hx-ws:connect="/ws/test">
952 <div id="content">Original</div>
953 </div>
954 `);
955 await htmx.timeout(50);
956
957 let ws = mockWebSocketInstances[0];
958 // Send raw HTML without hx-partial targeting — should not wipe connection element
959 ws.simulateRawMessage('<p>Should not appear</p>');
960 await htmx.timeout(20);
961
962 // Connection element content should be preserved
963 assert.include(document.getElementById('ws-conn').innerHTML, 'Original');
964 });
965
966 it('processes hx-partial in non-JSON messages even without hx-target', async function() {
967 let container = createProcessedHTML(`
968 <div hx-ws:connect="/ws/test">
969 <div id="widget">Old</div>
970 </div>
971 `);
972 await htmx.timeout(50);
973
974 let ws = mockWebSocketInstances[0];
975 ws.simulateRawMessage('<hx-partial id="widget"><p>Updated via partial</p></hx-partial>');
976 await htmx.timeout(20);
977
978 assert.include(document.getElementById('widget').innerHTML, 'Updated via partial');
979 });
980
981 it('fires htmx:before:ws:message for non-JSON data with message=null', async function() {
982 let container = createProcessedHTML(`
983 <div hx-ws:connect="/ws/test" hx-target="#content">
984 <div id="content">Original</div>
985 </div>
986 `);
987 await htmx.timeout(50);
988
989 let eventFired = false;
990 let receivedData = null;
991 let receivedMessage = 'not-set';
992 container.addEventListener('htmx:before:ws:message', (e) => {
993 eventFired = true;
994 receivedMessage = e.detail.message.json;
995 });
996
997 let ws = mockWebSocketInstances[0];
998 ws.simulateRawMessage('<p>Raw content</p>');
999 await htmx.timeout(20);
1000
1001 assert.isTrue(eventFired);
1002 assert.isNull(receivedMessage, 'message.json should be null for raw messages');
1003 });
1004
1005 it('prevents swap when htmx:before:ws:message is cancelled for raw data', async function() {
1006 let container = createProcessedHTML(`
1007 <div hx-ws:connect="/ws/test" hx-target="#content">
1008 <div id="content">Original</div>
1009 </div>
1010 `);
1011 await htmx.timeout(50);
1012
1013 container.addEventListener('htmx:before:ws:message', (e) => {
1014 if (!e.detail.message.json) e.detail.message.cancelled = true;
1015 });
1016
1017 let ws = mockWebSocketInstances[0];
1018 ws.simulateRawMessage('<hx-partial id="content"><p>Should not appear</p></hx-partial>');
1019 await htmx.timeout(20);
1020
1021 assert.equal(document.getElementById('content').textContent, 'Original');
1022 });
1023 });
1024
1025 // ========================================
1026 // 6. CONFIGURATION TESTS
1027 // ========================================
1028
1029 describe('Configuration', function() {
1030
1031 it('defers connection when explicit trigger is specified', async function() {
1032 let container = createProcessedHTML(`
1033 <div hx-ws:connect="/ws/test" hx-trigger="click"></div>
1034 `);
1035 await htmx.timeout(50);
1036
1037 // Should not connect immediately when explicit trigger is set
1038 assert.equal(mockWebSocketInstances.length, 0, 'Should not connect until trigger fires');
1039 });
1040
1041 it('uses custom reconnectDelay from config', async function() {
1042 htmx.config.ws = {
1043 reconnect: true,
1044 reconnectDelay: 200,
1045 reconnectJitter: 0
1046 };
1047
1048 let container = createProcessedHTML(`
1049 <div hx-ws:connect="/ws/test"></div>
1050 `);
1051 await htmx.timeout(50);
1052
1053 let ws = mockWebSocketInstances[0];
1054 let closeTime = Date.now();
1055 ws.close();
1056
1057 await htmx.timeout(100);
1058 assert.equal(mockWebSocketInstances.length, 1, 'Should not reconnect yet');
1059
1060 await htmx.timeout(150);
1061 assert.isTrue(mockWebSocketInstances.length > 1, 'Should reconnect after delay');
1062 });
1063
1064 it('applies reconnectJitter when enabled', async function() {
1065 htmx.config.ws = {
1066 reconnect: true,
1067 reconnectDelay: 100,
1068 reconnectJitter: 0.3
1069 };
1070
1071 let container = createProcessedHTML(`
1072 <div hx-ws:connect="/ws/test"></div>
1073 `);
1074 await htmx.timeout(50);
1075
1076 // This test just ensures jitter doesn't break reconnection
1077 let ws = mockWebSocketInstances[0];
1078 ws.close();
1079 await htmx.timeout(200);
1080
1081 assert.isTrue(mockWebSocketInstances.length > 1);
1082 });
1083
1084 it('reconnectMaxAttempts limits reconnection attempts on consecutive failures', async function() {
1085 htmx.config.ws = {
1086 reconnect: true,
1087 reconnectDelay: 20,
1088 reconnectMaxAttempts: 2,
1089 reconnectJitter: 0
1090 };
1091
1092 let container = createProcessedHTML(`
1093 <div hx-ws:connect="/ws/test"></div>
1094 `);
1095 await htmx.timeout(50);
1096
1097 let reconnectCount = 0;
1098 container.addEventListener('htmx:before:ws:connection', (e) => {
1099 if (e.detail.connection.attempt > 0) reconnectCount++;
1100 });
1101
1102 // Close the first connection — this triggers reconnect attempt 1
1103 let ws = mockWebSocketInstances[0];
1104 ws.close();
1105 await htmx.timeout(50);
1106
1107 // The reconnected socket auto-opens (mock behavior), which resets
1108 // attempts to 0. Close it immediately before it opens to simulate
1109 // consecutive failures. Override mock to not auto-open.
1110 for (let i = 1; i < mockWebSocketInstances.length; i++) {
1111 let reconnectedWs = mockWebSocketInstances[i];
1112 // Close immediately to prevent the open handler from resetting attempts
1113 reconnectedWs.readyState = mockWebSocket.CLOSED;
1114 reconnectedWs.triggerEvent('close', { code: 1006, reason: '', target: reconnectedWs });
1115 }
1116
1117 // Wait for remaining reconnect attempts to exhaust
1118 await htmx.timeout(200);
1119
1120 assert.equal(reconnectCount, 2, 'Should fire before:ws:connection for exactly 2 reconnect attempts');
1121 });
1122
1123 it('reconnectJitter with numeric factor varies delays', async function() {
1124 htmx.config.ws = {
1125 reconnect: true,
1126 reconnectDelay: 10,
1127 reconnectMaxAttempts: 5,
1128 reconnectJitter: 0.5
1129 };
1130
1131 let container = createProcessedHTML(`
1132 <div hx-ws:connect="/ws/test"></div>
1133 `);
1134 await htmx.timeout(50);
1135
1136 let reconnectAttempts = [];
1137 container.addEventListener('htmx:before:ws:connection', (e) => {
1138 if (e.detail.connection.attempt > 0) {
1139 reconnectAttempts.push(e.detail.connection.attempt);
1140 }
1141 });
1142
1143 let ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
1144 ws.close();
1145 await htmx.timeout(200);
1146
1147 assert.isAtLeast(reconnectAttempts.length, 1, 'Should have at least 1 reconnect');
1148 });
1149
1150 it('reconnectJitter of 0 produces exact base delay', async function() {
1151 htmx.config.ws = {
1152 reconnect: true,
1153 reconnectDelay: 20,
1154 reconnectMaxAttempts: 3,
1155 reconnectJitter: 0
1156 };
1157
1158 let container = createProcessedHTML(`
1159 <div hx-ws:connect="/ws/test"></div>
1160 `);
1161 await htmx.timeout(50);
1162
1163 let reconnectAttempts = [];
1164 container.addEventListener('htmx:before:ws:connection', (e) => {
1165 if (e.detail.connection.attempt > 0) {
1166 reconnectAttempts.push(e.detail.connection.attempt);
1167 }
1168 });
1169
1170 // Each reconnect succeeds (mock auto-opens), so reconnectAttempts
1171 // resets to 0 — each subsequent close starts at attempt 1 again
1172 let ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
1173 ws.close();
1174 await htmx.timeout(50);
1175
1176 ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
1177 ws.close();
1178 await htmx.timeout(50);
1179
1180 assert.isAtLeast(reconnectAttempts.length, 2, 'Should have at least 2 reconnects');
1181 });
1182
1183 it('per-element hx-config overrides global websockets config', async function() {
1184 htmx.config.ws = {
1185 reconnect: true,
1186 reconnectDelay: 5000,
1187 reconnectJitter: 0
1188 };
1189
1190 let container = createProcessedHTML(`
1191 <div hx-ws:connect="/ws/test" hx-config="ws.reconnectDelay:20 ws.reconnectMaxAttempts:2"></div>
1192 `);
1193 await htmx.timeout(50);
1194
1195 let reconnectAttempts = [];
1196 container.addEventListener('htmx:before:ws:connection', (e) => {
1197 if (e.detail.connection.attempt > 0) {
1198 reconnectAttempts.push(e.detail.connection.attempt);
1199 }
1200 });
1201
1202 let ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
1203 ws.close();
1204 await htmx.timeout(100);
1205
1206 // Per-element config set reconnectDelay to 20ms (not global 5000ms),
1207 // so reconnection should have happened quickly
1208 assert.isAtLeast(reconnectAttempts.length, 1, 'Should reconnect using per-element delay');
1209 });
1210
1211 it('per-element hx-config supports JSON object form', async function() {
1212 htmx.config.ws = {
1213 reconnect: true,
1214 reconnectDelay: 5000,
1215 reconnectJitter: 0
1216 };
1217
1218 let container = createProcessedHTML(`
1219 <div hx-ws:connect="/ws/test" hx-config='{"ws": {"reconnectDelay": 20, "reconnectMaxAttempts": 2}}'></div>
1220 `);
1221 await htmx.timeout(50);
1222
1223 let reconnectAttempts = [];
1224 container.addEventListener('htmx:before:ws:connection', (e) => {
1225 if (e.detail.connection.attempt > 0) {
1226 reconnectAttempts.push(e.detail.connection.attempt);
1227 }
1228 });
1229
1230 let ws = mockWebSocketInstances[mockWebSocketInstances.length - 1];
1231 ws.close();
1232 await htmx.timeout(100);
1233
1234 assert.isAtLeast(reconnectAttempts.length, 1, 'Should reconnect using per-element JSON config');
1235 });
1236
1237 it('htmx:ws:error fires for send failures with error message', async function() {
1238 let container = createProcessedHTML(`
1239 <div hx-ws:connect="/ws/test">
1240 <button hx-ws:send hx-trigger="click">Send</button>
1241 </div>
1242 `);
1243 await htmx.timeout(50);
1244
1245 let errorMsg = null;
1246 container.addEventListener('htmx:ws:error', (e) => {
1247 errorMsg = e.detail.error;
1248 });
1249
1250 mockWebSocketInstances[0].close();
1251 await htmx.timeout(20);
1252
1253 container.querySelector('button').click();
1254 await htmx.timeout(20);
1255
1256 assert.equal(errorMsg, 'Connection not open');
1257 });
1258
1259 it('raw messages go through before/after:ws:message with message=null', async function() {
1260 let container = createProcessedHTML(`
1261 <div hx-ws:connect="/ws/test" hx-target="#content">
1262 <div id="content">Original</div>
1263 </div>
1264 `);
1265 await htmx.timeout(50);
1266
1267 let beforeDetail = null;
1268 let afterDetail = null;
1269 container.addEventListener('htmx:before:ws:message', (e) => {
1270 beforeDetail = e.detail;
1271 });
1272 container.addEventListener('htmx:after:ws:message', (e) => {
1273 afterDetail = e.detail;
1274 });
1275
1276 let ws = mockWebSocketInstances[0];
1277 ws.simulateRawMessage('<hx-partial id="content"><p>Updated</p></hx-partial>');
1278 await htmx.timeout(20);
1279
1280 assert.isNotNull(beforeDetail, 'before:ws:message should fire for raw messages');
1281 assert.isNull(beforeDetail.message.json, 'message.json should be null for raw data');
1282 assert.isString(beforeDetail.message.text, 'message.text should be present');
1283
1284 assert.isNotNull(afterDetail, 'after:ws:message should fire for raw messages');
1285 assert.isNull(afterDetail.message.json, 'message.json should be null in after event too');
1286 });
1287
1288 it('JSON messages go through before/after:ws:message with message object', async function() {
1289 let container = createProcessedHTML(`
1290 <div hx-ws:connect="/ws/test" hx-target="#content">
1291 <div id="content"></div>
1292 </div>
1293 `);
1294 await htmx.timeout(50);
1295
1296 let beforeDetail = null;
1297 container.addEventListener('htmx:before:ws:message', (e) => {
1298 beforeDetail = e.detail;
1299 });
1300
1301 let ws = mockWebSocketInstances[0];
1302 ws.simulateMessage({
1303 content: '<hx-partial id="content">New</hx-partial>'
1304 });
1305 await htmx.timeout(20);
1306
1307 assert.isNotNull(beforeDetail, 'before:ws:message should fire');
1308 assert.isNotNull(beforeDetail.message.json, 'message.json should be set for JSON messages');
1309 assert.isDefined(beforeDetail.message.json.content, 'message.json should have content field');
1310 });
1311 });
1312
1313 // ========================================
1314 // 7. EVENT EMISSION TESTS
1315 // ========================================
1316
1317 describe('Event Emission', function() {
1318
1319 it('emits htmx:before:ws:connection before connection', async function() {
1320 let beforeFired = false;
1321 let attempt = null;
1322 let container = document.createElement('div');
1323 container.innerHTML = '<div hx-ws:connect="/ws/test"></div>';
1324
1325 container.addEventListener('htmx:before:ws:connection', (e) => {
1326 beforeFired = true;
1327 attempt = e.detail.connection.attempt;
1328 });
1329
1330 document.body.appendChild(container);
1331 htmx.process(container);
1332 await htmx.timeout(20);
1333
1334 assert.isTrue(beforeFired);
1335 assert.equal(attempt, 0, 'Initial connection should have attempt=0');
1336 container.remove();
1337 });
1338
1339 it('emits htmx:after:ws:connection after connection', async function() {
1340 let afterFired = false;
1341 let container = document.createElement('div');
1342 container.innerHTML = '<div hx-ws:connect="/ws/test"></div>';
1343
1344 container.addEventListener('htmx:after:ws:connection', () => {
1345 afterFired = true;
1346 });
1347
1348 document.body.appendChild(container);
1349 htmx.process(container);
1350 await htmx.timeout(50);
1351
1352 assert.isTrue(afterFired);
1353 container.remove();
1354 });
1355
1356 it('can cancel initial connection via htmx:before:ws:connection', async function() {
1357 let container = document.createElement('div');
1358 container.innerHTML = '<div hx-ws:connect="/ws/test"></div>';
1359
1360 container.addEventListener('htmx:before:ws:connection', (e) => {
1361 e.detail.connection.cancelled = true;
1362 });
1363
1364 document.body.appendChild(container);
1365 htmx.process(container);
1366 await htmx.timeout(50);
1367
1368 assert.equal(mockWebSocketInstances.length, 0, 'Connection should be cancelled');
1369 container.remove();
1370 });
1371
1372 it('can cancel reconnection via htmx:before:ws:connection', async function() {
1373 htmx.config.ws = { reconnect: true, reconnectDelay: 50 };
1374
1375 let container = createProcessedHTML(`
1376 <div hx-ws:connect="/ws/test"></div>
1377 `);
1378
1379 container.addEventListener('htmx:before:ws:connection', (e) => {
1380 if (e.detail.connection.attempt > 0) {
1381 e.detail.connection.cancelled = true;
1382 }
1383 });
1384
1385 await htmx.timeout(50);
1386 let firstWs = mockWebSocketInstances[0];
1387 firstWs.close();
1388 await htmx.timeout(150);
1389
1390 assert.equal(mockWebSocketInstances.length, 1, 'Should not reconnect when cancelled');
1391 });
1392
1393 it('emits htmx:before:ws:request before sending', async function() {
1394 let beforeFired = false;
1395 let div = createProcessedHTML(`
1396 <div hx-ws:connect="/ws/test">
1397 <button hx-ws:send hx-trigger="click">Send</button>
1398 </div>
1399 `);
1400
1401 div.addEventListener('htmx:before:ws:request', () => {
1402 beforeFired = true;
1403 });
1404
1405 await htmx.timeout(50);
1406 div.querySelector('button').click();
1407 await htmx.timeout(20);
1408
1409 assert.isTrue(beforeFired);
1410 });
1411
1412 it('emits htmx:after:ws:request after sending', async function() {
1413 let afterFired = false;
1414 let div = createProcessedHTML(`
1415 <div hx-ws:connect="/ws/test">
1416 <button hx-ws:send hx-trigger="click">Send</button>
1417 </div>
1418 `);
1419
1420 div.addEventListener('htmx:after:ws:request', () => {
1421 afterFired = true;
1422 });
1423
1424 await htmx.timeout(50);
1425 div.querySelector('button').click();
1426 await htmx.timeout(20);
1427
1428 assert.isTrue(afterFired);
1429 });
1430
1431 it('allows modifying message via htmx:before:ws:request', async function() {
1432 let div = createProcessedHTML(`
1433 <div hx-ws:connect="/ws/test">
1434 <button hx-ws:send hx-trigger="click">Send</button>
1435 </div>
1436 `);
1437
1438 div.addEventListener('htmx:before:ws:request', (e) => {
1439 e.detail.body.custom = 'added';
1440 });
1441
1442 await htmx.timeout(50);
1443 div.querySelector('button').click();
1444 await htmx.timeout(20);
1445
1446 let ws = mockWebSocketInstances[0];
1447 let sent = JSON.parse(ws.lastSent);
1448 assert.equal(sent.body.custom, 'added');
1449 });
1450
1451 it('can cancel send via htmx:before:ws:request', async function() {
1452 let div = createProcessedHTML(`
1453 <div hx-ws:connect="/ws/test">
1454 <button hx-ws:send hx-trigger="click">Send</button>
1455 </div>
1456 `);
1457
1458 div.addEventListener('htmx:before:ws:request', (e) => {
1459 e.preventDefault();
1460 });
1461
1462 await htmx.timeout(50);
1463 div.querySelector('button').click();
1464 await htmx.timeout(20);
1465
1466 let ws = mockWebSocketInstances[0];
1467 assert.isUndefined(ws.lastSent);
1468 });
1469 });
1470
1471 // ========================================
1472 // 8. BACKWARD COMPATIBILITY TESTS
1473 // ========================================
1474
1475 describe('Backward Compatibility', function() {
1476
1477 it('supports legacy ws-connect attribute with deprecation warning', async function() {
1478 let warnCalled = false;
1479 let originalWarn = console.warn;
1480 console.warn = () => { warnCalled = true; };
1481
1482 let container = createProcessedHTML(`
1483 <div hx-ext="ws" ws-connect="/ws/test"></div>
1484 `);
1485 await htmx.timeout(50);
1486
1487 console.warn = originalWarn;
1488
1489 // Should still create connection
1490 assert.equal(mockWebSocketInstances.length, 1);
1491 // Should warn about deprecation
1492 assert.isTrue(warnCalled);
1493 });
1494
1495 it('supports legacy ws-send attribute', async function() {
1496 let div = createProcessedHTML(`
1497 <div hx-ext="ws" ws-connect="/ws/test">
1498 <button ws-send hx-trigger="click">Send</button>
1499 </div>
1500 `);
1501 await htmx.timeout(50);
1502
1503 div.querySelector('button').click();
1504 await htmx.timeout(20);
1505
1506 let ws = mockWebSocketInstances[0];
1507 assert.isDefined(ws.lastSent);
1508 });
1509 });
1510
1511 // ========================================
1512 // 9. INTEGRATION TESTS
1513 // ========================================
1514
1515 describe('Integration Scenarios', function() {
1516
1517 it('handles chat application pattern', async function() {
1518 let div = createProcessedHTML(`
1519 <div hx-ws:connect="/ws/chat" hx-target="#messages" hx-swap="beforeend">
1520 <div id="messages"></div>
1521 <form hx-ws:send hx-trigger="submit">
1522 <input name="message" value="Hello">
1523 <button type="submit">Send</button>
1524 </form>
1525 </div>
1526 `);
1527 await htmx.timeout(50);
1528
1529 // Send a message
1530 let form = div.querySelector('form');
1531 form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
1532 await htmx.timeout(20);
1533
1534 // Simulate server response
1535 let ws = mockWebSocketInstances[0];
1536 ws.simulateMessage({
1537 content: '<hx-partial id="messages"><p>Hello</p></hx-partial>'
1538 });
1539 await htmx.timeout(20);
1540
1541 assert.include(document.getElementById('messages').innerHTML, 'Hello');
1542 });
1543
1544 it('handles live notifications pattern', async function() {
1545 let container = createProcessedHTML(`
1546 <div hx-ws:connect="/ws/notifications" hx-target="#notifications">
1547 <div id="notifications"></div>
1548 </div>
1549 `);
1550 await htmx.timeout(50);
1551
1552 let ws = mockWebSocketInstances[0];
1553
1554 // Receive multiple notifications
1555 ws.simulateMessage({
1556 content: '<hx-partial id="notifications" hx-swap="afterbegin"><div class="notif">Notification 1</div></hx-partial>'
1557 });
1558 await htmx.timeout(20);
1559
1560 ws.simulateMessage({
1561 content: '<hx-partial id="notifications" hx-swap="afterbegin"><div class="notif">Notification 2</div></hx-partial>'
1562 });
1563 await htmx.timeout(20);
1564
1565 let notifications = document.getElementById('notifications');
1566 assert.include(notifications.innerHTML, 'Notification 1');
1567 assert.include(notifications.innerHTML, 'Notification 2');
1568 });
1569
1570 it('handles real-time dashboard with multiple widgets', async function() {
1571 let container = createProcessedHTML(`
1572 <div hx-ws:connect="/ws/dashboard">
1573 <div id="widget1"></div>
1574 <div id="widget2"></div>
1575 <div id="widget3"></div>
1576 </div>
1577 `);
1578 await htmx.timeout(50);
1579
1580 let ws = mockWebSocketInstances[0];
1581 ws.simulateMessage({
1582 content: `
1583 <hx-partial id="widget1"><span>Data 1</span></hx-partial>
1584 <hx-partial id="widget2"><span>Data 2</span></hx-partial>
1585 <hx-partial id="widget3"><span>Data 3</span></hx-partial>
1586 `
1587 });
1588 await htmx.timeout(20);
1589
1590 assert.include(document.getElementById('widget1').innerHTML, 'Data 1');
1591 assert.include(document.getElementById('widget2').innerHTML, 'Data 2');
1592 assert.include(document.getElementById('widget3').innerHTML, 'Data 3');
1593 });
1594 });
1595
1596 // ========================================
1597 // 10. TARGET AND SWAP OVERRIDE TESTS
1598 // ========================================
1599
1600 describe('Target and Swap Overrides', function() {
1601
1602 it('respects target override from message', async function() {
1603 let container = createProcessedHTML(`
1604 <div hx-ws:connect="/ws/test" hx-target="#default-target">
1605 <div id="default-target">Default</div>
1606 <div id="override-target">Override</div>
1607 </div>
1608 `);
1609 await htmx.timeout(50);
1610
1611 let ws = mockWebSocketInstances[0];
1612 ws.simulateMessage({
1613 content: '<div>New Content</div>',
1614 target: '#override-target'
1615 });
1616 await htmx.timeout(20);
1617
1618 assert.equal(document.getElementById('default-target').textContent, 'Default');
1619 assert.include(document.getElementById('override-target').innerHTML, 'New Content');
1620 });
1621
1622 it('respects swap override from message', async function() {
1623 let container = createProcessedHTML(`
1624 <div hx-ws:connect="/ws/test" hx-target="#content" hx-swap="innerHTML">
1625 <div id="content"><p>Item 1</p></div>
1626 </div>
1627 `);
1628 await htmx.timeout(50);
1629
1630 let ws = mockWebSocketInstances[0];
1631 ws.simulateMessage({
1632 content: '<p>Item 2</p>',
1633 swap: 'beforeend'
1634 });
1635 await htmx.timeout(20);
1636
1637 let content = document.getElementById('content');
1638 assert.include(content.innerHTML, 'Item 1');
1639 assert.include(content.innerHTML, 'Item 2');
1640 });
1641
1642 it('uses element hx-target when message has no target', async function() {
1643 let container = createProcessedHTML(`
1644 <div hx-ws:connect="/ws/test" hx-target="#element-target">
1645 <div id="element-target"></div>
1646 </div>
1647 `);
1648 await htmx.timeout(50);
1649
1650 let ws = mockWebSocketInstances[0];
1651 ws.simulateMessage({
1652 content: '<div>Content</div>'
1653 });
1654 await htmx.timeout(20);
1655
1656 assert.include(document.getElementById('element-target').innerHTML, 'Content');
1657 });
1658
1659 it('uses element hx-swap when message has no swap', async function() {
1660 let container = createProcessedHTML(`
1661 <div hx-ws:connect="/ws/test" hx-target="#content" hx-swap="beforeend">
1662 <div id="content"><p>Item 1</p></div>
1663 </div>
1664 `);
1665 await htmx.timeout(50);
1666
1667 let ws = mockWebSocketInstances[0];
1668 ws.simulateMessage({
1669 content: '<p>Item 2</p>'
1670 });
1671 await htmx.timeout(20);
1672
1673 let content = document.getElementById('content');
1674 assert.include(content.innerHTML, 'Item 1');
1675 assert.include(content.innerHTML, 'Item 2');
1676 });
1677
1678 it('message target overrides element hx-target', async function() {
1679 let container = createProcessedHTML(`
1680 <div hx-ws:connect="/ws/test" hx-target="#element-target">
1681 <div id="element-target">Element Target</div>
1682 <div id="message-target">Message Target</div>
1683 </div>
1684 `);
1685 await htmx.timeout(50);
1686
1687 let ws = mockWebSocketInstances[0];
1688 ws.simulateMessage({
1689 content: '<div>New</div>',
1690 target: '#message-target'
1691 });
1692 await htmx.timeout(20);
1693
1694 assert.equal(document.getElementById('element-target').textContent, 'Element Target');
1695 assert.include(document.getElementById('message-target').innerHTML, 'New');
1696 });
1697
1698 it('message swap overrides element hx-swap', async function() {
1699 let container = createProcessedHTML(`
1700 <div hx-ws:connect="/ws/test" hx-target="#content" hx-swap="innerHTML">
1701 <div id="content"><p>Original</p></div>
1702 </div>
1703 `);
1704 await htmx.timeout(50);
1705
1706 let ws = mockWebSocketInstances[0];
1707 ws.simulateMessage({
1708 content: '<p>Appended</p>',
1709 swap: 'beforeend'
1710 });
1711 await htmx.timeout(20);
1712
1713 let content = document.getElementById('content');
1714 assert.include(content.innerHTML, 'Original');
1715 assert.include(content.innerHTML, 'Appended');
1716 });
1717 });
1718
1719 // ========================================
1720 // 11. BUG REGRESSION TESTS
1721 // ========================================
1722
1723 describe('Bug Regressions', function() {
1724
1725 it('htmx:after:ws:connection reports correct attempt number on reconnect', async function() {
1726 htmx.config.ws = { reconnect: true, reconnectDelay: 50, reconnectJitter: 0 };
1727
1728 let container = createProcessedHTML(`
1729 <div hx-ws:connect="/ws/test"></div>
1730 `);
1731 await htmx.timeout(50);
1732
1733 let reportedAttempt = null;
1734 container.addEventListener('htmx:after:ws:connection', (e) => {
1735 reportedAttempt = e.detail.connection.attempt;
1736 });
1737
1738 // Close to trigger reconnect
1739 let ws = mockWebSocketInstances[0];
1740 ws.close();
1741 await htmx.timeout(150);
1742
1743 assert.isNotNull(reportedAttempt, 'after:ws:connection should have fired on reconnect');
1744 assert.equal(reportedAttempt, 1, 'Reconnection attempt should be 1, not 0');
1745 });
1746
1747 it('htmx:before:ws:message includes raw data string', async function() {
1748 let container = createProcessedHTML(`
1749 <div hx-ws:connect="/ws/test" hx-target="#content">
1750 <div id="content"></div>
1751 </div>
1752 `);
1753 await htmx.timeout(50);
1754
1755 let receivedData = null;
1756 let receivedMessage = null;
1757 container.addEventListener('htmx:before:ws:message', (e) => {
1758 receivedData = e.detail.message.text;
1759 receivedMessage = e.detail.message.json;
1760 });
1761
1762 let ws = mockWebSocketInstances[0];
1763 ws.simulateMessage({ content: '<p>Hello</p>' });
1764 await htmx.timeout(20);
1765
1766 assert.isString(receivedData, 'text should be the raw string');
1767 assert.isNotNull(receivedMessage, 'json should be the parsed JSON');
1768 assert.equal(receivedMessage.content, '<p>Hello</p>');
1769 });
1770 });
1771
1772 // ========================================
1773 // 12. ORPHANED CONNECTION CLEANUP TESTS (BLOCKER 1)
1774 // ========================================
1775
1776 describe('Orphaned Connection Cleanup', function() {
1777
1778 it('closes WebSocket when connect element is swapped out mid-connection', async function() {
1779 let container = createProcessedHTML(`
1780 <div id="outer">
1781 <div id="ws-host" hx-ws:connect="/ws/test">
1782 <div id="content">Hello</div>
1783 </div>
1784 </div>
1785 `);
1786 await htmx.timeout(50);
1787
1788 let ws = mockWebSocketInstances[0];
1789 assert.equal(ws.readyState, mockWebSocket.OPEN, 'WebSocket should be open');
1790 let registry = htmx.ext.ws.getRegistry();
1791 assert.isTrue(registry.has('/ws/test'), 'Connection should be in registry');
1792
1793 // Swap out the ws-host element entirely (simulates hx-swap replacing it)
1794 await htmx.swap({
1795 text: '<div id="ws-host">Replaced — no hx-ws:connect</div>',
1796 target: document.getElementById('outer'),
1797 swap: 'innerHTML'
1798 });
1799 await htmx.timeout(50);
1800
1801 assert.equal(ws.readyState, mockWebSocket.CLOSED, 'WebSocket should be closed after element removal');
1802 assert.isFalse(registry.has('/ws/test'), 'Connection should be removed from registry');
1803 });
1804
1805 it('cleans up connection when element is removed and message arrives', async function() {
1806 let container = createProcessedHTML(`
1807 <div id="outer">
1808 <div id="ws-host" hx-ws:connect="/ws/test" hx-target="#content">
1809 <div id="content"></div>
1810 </div>
1811 </div>
1812 `);
1813 await htmx.timeout(50);
1814
1815 let ws = mockWebSocketInstances[0];
1816 let registry = htmx.ext.ws.getRegistry();
1817
1818 // Remove the element without triggering htmx cleanup (simulates raw DOM removal)
1819 document.getElementById('ws-host').remove();
1820 await htmx.timeout(20);
1821
1822 // Now a message arrives on the orphaned socket
1823 ws.simulateMessage({ content: '<p>Ghost message</p>' });
1824 await htmx.timeout(20);
1825
1826 assert.equal(ws.readyState, mockWebSocket.CLOSED, 'WebSocket should be closed');
1827 assert.isFalse(registry.has('/ws/test'), 'Connection should be cleaned up');
1828 });
1829
1830 it('cleans up connection on close when element is gone (no reconnect)', async function() {
1831 htmx.config.ws = { reconnect: true, reconnectDelay: 20 };
1832
1833 let container = createProcessedHTML(`
1834 <div id="outer">
1835 <div id="ws-host" hx-ws:connect="/ws/test">
1836 <div id="content">Hello</div>
1837 </div>
1838 </div>
1839 `);
1840 await htmx.timeout(50);
1841
1842 let ws = mockWebSocketInstances[0];
1843 let registry = htmx.ext.ws.getRegistry();
1844
1845 // Remove element from DOM without htmx cleanup
1846 document.getElementById('ws-host').remove();
1847 await htmx.timeout(20);
1848
1849 // Server-side close
1850 ws.close();
1851 await htmx.timeout(100);
1852
1853 // Should NOT attempt reconnection, should clean up
1854 assert.equal(mockWebSocketInstances.length, 1, 'Should not create new WebSocket');
1855 assert.isFalse(registry.has('/ws/test'), 'Connection should be removed from registry');
1856 });
1857
1858 it('cleans up when element removed during reconnect delay', async function() {
1859 htmx.config.ws = { reconnect: true, reconnectDelay: 200, reconnectJitter: 0 };
1860
1861 let container = createProcessedHTML(`
1862 <div id="outer">
1863 <div id="ws-host" hx-ws:connect="/ws/test">Content</div>
1864 </div>
1865 `);
1866 await htmx.timeout(50);
1867
1868 let ws = mockWebSocketInstances[0];
1869 let registry = htmx.ext.ws.getRegistry();
1870
1871 // Close to trigger reconnect scheduling
1872 ws.close();
1873 await htmx.timeout(20);
1874
1875 // Remove element during the reconnect delay
1876 await htmx.swap({
1877 text: '<div>No more WS</div>',
1878 target: document.getElementById('outer'),
1879 swap: 'innerHTML'
1880 });
1881 await htmx.timeout(250);
1882
1883 // Reconnect timer should have fired but found no element, so no new socket
1884 assert.equal(mockWebSocketInstances.length, 1, 'Should not reconnect after element removal');
1885 assert.isFalse(registry.has('/ws/test'), 'Connection should be cleaned up');
1886 });
1887 });
1888
1889 // ========================================
1890 // 13. BACKWARDS COMPAT — json.payload (BLOCKER 2)
1891 // ========================================
1892
1893 describe('Backwards Compatibility - json.payload', function() {
1894
1895 it('swaps HTML from json.payload with deprecation warning', async function() {
1896 let container = createProcessedHTML(`
1897 <div hx-ws:connect="/ws/test" hx-target="#content">
1898 <div id="content">Original</div>
1899 </div>
1900 `);
1901 await htmx.timeout(50);
1902
1903 let warnMessage = null;
1904 let originalWarn = console.warn;
1905 console.warn = (msg) => { warnMessage = msg; };
1906
1907 let ws = mockWebSocketInstances[0];
1908 ws.simulateMessage({
1909 payload: '<hx-partial id="content"><p>Via payload</p></hx-partial>'
1910 });
1911 await htmx.timeout(20);
1912
1913 console.warn = originalWarn;
1914
1915 assert.include(document.getElementById('content').innerHTML, 'Via payload');
1916 assert.isNotNull(warnMessage, 'Should emit deprecation warning');
1917 assert.include(warnMessage, 'payload');
1918 assert.include(warnMessage, 'deprecated');
1919 });
1920
1921 it('prefers json.content over json.payload when both present', async function() {
1922 let container = createProcessedHTML(`
1923 <div hx-ws:connect="/ws/test" hx-target="#content">
1924 <div id="content">Original</div>
1925 </div>
1926 `);
1927 await htmx.timeout(50);
1928
1929 let warnCalled = false;
1930 let originalWarn = console.warn;
1931 console.warn = () => { warnCalled = true; };
1932
1933 let ws = mockWebSocketInstances[0];
1934 ws.simulateMessage({
1935 content: '<p>From content</p>',
1936 payload: '<p>From payload</p>'
1937 });
1938 await htmx.timeout(20);
1939
1940 console.warn = originalWarn;
1941
1942 assert.include(document.getElementById('content').innerHTML, 'From content');
1943 assert.notInclude(document.getElementById('content').innerHTML, 'From payload');
1944 assert.isFalse(warnCalled, 'Should not warn when content is present');
1945 });
1946
1947 it('does not swap when neither content nor payload is present', async function() {
1948 let container = createProcessedHTML(`
1949 <div hx-ws:connect="/ws/test" hx-target="#content">
1950 <div id="content">Original</div>
1951 </div>
1952 `);
1953 await htmx.timeout(50);
1954
1955 let ws = mockWebSocketInstances[0];
1956 ws.simulateMessage({ type: 'ping', data: 'hello' });
1957 await htmx.timeout(20);
1958
1959 assert.equal(document.getElementById('content').textContent, 'Original');
1960 });
1961
1962 it('handles json.payload with target and swap overrides', async function() {
1963 let container = createProcessedHTML(`
1964 <div hx-ws:connect="/ws/test">
1965 <div id="list"><p>Item 1</p></div>
1966 </div>
1967 `);
1968 await htmx.timeout(50);
1969
1970 let originalWarn = console.warn;
1971 console.warn = () => {}; // suppress
1972
1973 let ws = mockWebSocketInstances[0];
1974 ws.simulateMessage({
1975 payload: '<p>Item 2</p>',
1976 target: '#list',
1977 swap: 'beforeend'
1978 });
1979 await htmx.timeout(20);
1980
1981 console.warn = originalWarn;
1982
1983 let list = document.getElementById('list');
1984 assert.include(list.innerHTML, 'Item 1');
1985 assert.include(list.innerHTML, 'Item 2');
1986 });
1987 });
1988
1989 // ========================================
1990 // 14. RECONNECT JITTER BOOLEAN COMPAT (POLISH)
1991 // ========================================
1992
1993 describe('reconnectJitter Boolean Compatibility', function() {
1994
1995 it('treats reconnectJitter: true as 0.3 (default jitter)', async function() {
1996 htmx.config.ws = {
1997 reconnect: true,
1998 reconnectDelay: 50,
1999 reconnectJitter: true
2000 };
2001
2002 let container = createProcessedHTML(`
2003 <div hx-ws:connect="/ws/test"></div>
2004 `);
2005 await htmx.timeout(50);
2006
2007 // Should reconnect without breaking (true * delay would give NaN-like behavior)
2008 let ws = mockWebSocketInstances[0];
2009 ws.close();
2010 await htmx.timeout(150);
2011
2012 assert.isTrue(mockWebSocketInstances.length > 1, 'Should reconnect with boolean jitter=true');
2013 });
2014
2015 it('treats reconnectJitter: false as 0 (no jitter)', async function() {
2016 htmx.config.ws = {
2017 reconnect: true,
2018 reconnectDelay: 50,
2019 reconnectJitter: false
2020 };
2021
2022 let container = createProcessedHTML(`
2023 <div hx-ws:connect="/ws/test"></div>
2024 `);
2025 await htmx.timeout(50);
2026
2027 let ws = mockWebSocketInstances[0];
2028 ws.close();
2029 await htmx.timeout(100);
2030
2031 assert.isTrue(mockWebSocketInstances.length > 1, 'Should reconnect with boolean jitter=false');
2032 });
2033 });
2034
2035 // ========================================
2036 // 15. ADDITIONAL FINDINGS — DEEP REVIEW
2037 // ========================================
2038
2039 describe('Deep Review Fixes', function() {
2040
2041 it('falls back to live element when correlated element is removed from DOM', async function() {
2042 let container = createProcessedHTML(`
2043 <div hx-ws:connect="/ws/test">
2044 <form id="form1" hx-ws:send hx-trigger="submit" hx-target="#result">
2045 <input name="msg" value="hello">
2046 </form>
2047 <div id="result"></div>
2048 </div>
2049 `);
2050 await htmx.timeout(50);
2051
2052 let form = document.getElementById('form1');
2053 form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
2054 await htmx.timeout(20);
2055
2056 let ws = mockWebSocketInstances[0];
2057 let sent = JSON.parse(ws.lastSent);
2058 let requestId = sent.headers['HX-Request-ID'];
2059
2060 // Remove the form that sent the request (simulates swap replacing the form)
2061 form.remove();
2062 await htmx.timeout(20);
2063
2064 // Server responds with the request ID — should fall back to live connect element
2065 ws.simulateMessage({
2066 content: '<hx-partial id="result">Response</hx-partial>',
2067 'HX-Request-ID': requestId
2068 });
2069 await htmx.timeout(20);
2070
2071 assert.include(document.getElementById('result').innerHTML, 'Response');
2072 });
2073
2074 it('cleans up expired pending requests on message receive', async function() {
2075 htmx.config.ws = { pendingRequestTTL: 50 };
2076
2077 let container = createProcessedHTML(`
2078 <div hx-ws:connect="/ws/test">
2079 <button hx-ws:send hx-trigger="click">Send</button>
2080 </div>
2081 `);
2082 await htmx.timeout(50);
2083
2084 let button = container.querySelector('button');
2085 button.click();
2086 await htmx.timeout(20);
2087
2088 let ws = mockWebSocketInstances[0];
2089 let registry = htmx.ext.ws.getRegistry();
2090 let conn = registry.get('/ws/test');
2091 assert.equal(conn.pendingRequests.size, 1, 'Should have 1 pending request');
2092
2093 // Wait for TTL to expire
2094 await htmx.timeout(100);
2095
2096 // Receive any message — should trigger cleanup
2097 ws.simulateMessage({ type: 'ping' });
2098 await htmx.timeout(20);
2099
2100 assert.equal(conn.pendingRequests.size, 0, 'Expired pending request should be cleaned up');
2101 });
2102
2103 it('closeConnection aborts the AbortController', async function() {
2104 let container = createProcessedHTML(`
2105 <div id="outer">
2106 <div id="ws-host" hx-ws:connect="/ws/test">Content</div>
2107 </div>
2108 `);
2109 await htmx.timeout(50);
2110
2111 let registry = htmx.ext.ws.getRegistry();
2112 let conn = registry.get('/ws/test');
2113 assert.isNotNull(conn, 'Connection should exist');
2114 assert.isNotNull(conn.abortController, 'AbortController should exist');
2115 let ac = conn.abortController;
2116
2117 // Remove the element to trigger closeConnection
2118 await htmx.swap({
2119 text: '',
2120 target: document.getElementById('outer'),
2121 swap: 'innerHTML'
2122 });
2123 await htmx.timeout(50);
2124
2125 assert.isTrue(ac.signal.aborted, 'AbortController should be aborted on close');
2126 });
2127 });
2128 });