Skip to main content

max / goingson

19.5 KB · 549 lines History Blame Raw
1 #!/usr/bin/env node
2 /**
3 * GO Frontend JS Test Runner
4 *
5 * Sets up the global environment once, loads all source modules,
6 * then runs all test suites.
7 *
8 * Usage: node src-tauri/frontend/js/tests/run.js
9 */
10
11 const { describe, test, assert, assertEqual, assertDeepEqual, report } = require('./test-runner');
12
13 console.log('Running GO frontend tests...\n');
14
15 // ============================================================
16 // Global environment setup (mocks for browser APIs)
17 // ============================================================
18
19 const mockElements = {};
20
21 function createMockElement(tag) {
22 return {
23 tagName: (tag || 'div').toUpperCase(),
24 className: '',
25 id: '',
26 style: {},
27 dataset: {},
28 innerHTML: '',
29 _text: '',
30 set textContent(v) {
31 this._text = v;
32 this.innerHTML = String(v)
33 .replace(/&/g, '&')
34 .replace(/</g, '&lt;')
35 .replace(/>/g, '&gt;')
36 .replace(/"/g, '&quot;')
37 .replace(/'/g, '&#039;');
38 },
39 get textContent() { return this._text; },
40 children: [],
41 classList: {
42 _classes: new Set(),
43 add(c) { this._classes.add(c); },
44 remove(c) { this._classes.delete(c); },
45 contains(c) { return this._classes.has(c); },
46 },
47 attributes: [],
48 _listeners: {},
49 setAttribute(k, v) { this[k] = v; },
50 getAttribute(k) { return this[k] || null; },
51 removeAttribute(k) { delete this[k]; },
52 addEventListener(ev, fn) { this._listeners[ev] = fn; },
53 querySelector() { return createMockElement('span'); },
54 querySelectorAll() { return []; },
55 appendChild(child) { this.children.push(child); },
56 remove() {},
57 parentNode: { insertBefore() {} },
58 };
59 }
60
61 globalThis.document = {
62 createElement: createMockElement,
63 getElementById: (id) => {
64 if (!mockElements[id]) {
65 mockElements[id] = createMockElement('div');
66 mockElements[id].id = id;
67 }
68 return mockElements[id];
69 },
70 querySelectorAll: () => [],
71 };
72
73 globalThis.window = { GoingsOn: {} };
74 globalThis.GoingsOn = window.GoingsOn;
75
76 // ============================================================
77 // Load source modules (same order as index.html)
78 // ============================================================
79
80 require('../goingson'); // Initializes GoingsOn namespace
81 require('../state'); // GoingsOn.state (AppStateManager)
82 require('../utils'); // GoingsOn.utils (escapeHtml, escapeAttr, etc.)
83 require('../pagination-manager'); // GoingsOn.PaginationManager
84 require('../selection-manager'); // GoingsOn.SelectionManager
85 require('../whats-new'); // GoingsOn.whatsNew (changelog parser/renderer)
86
87 // ============================================================
88 // Test: AppStateManager / GoingsOn.state
89 // ============================================================
90
91 describe('GoingsOn.state', () => {
92 test('set() stores value and notifies subscribers', () => {
93 let called = false;
94 GoingsOn.state.subscribe('_t1', () => { called = true; });
95 GoingsOn.state.set('_t1', 'hello');
96 assert(called, 'Subscriber should fire');
97 assertEqual(GoingsOn.state._t1, 'hello');
98 });
99
100 test('subscribe() returns working unsubscribe function', () => {
101 let count = 0;
102 const unsub = GoingsOn.state.subscribe('_t2', () => { count++; });
103 GoingsOn.state.set('_t2', 'a');
104 assertEqual(count, 1);
105 unsub();
106 GoingsOn.state.set('_t2', 'b');
107 assertEqual(count, 1);
108 });
109
110 test('notify() passes new and old values to callback', () => {
111 GoingsOn.state.set('_t3', 'first');
112 let capturedOld, capturedNew;
113 GoingsOn.state.subscribe('_t3', (n, o) => { capturedNew = n; capturedOld = o; });
114 GoingsOn.state.set('_t3', 'second');
115 assertEqual(capturedOld, 'first');
116 assertEqual(capturedNew, 'second');
117 });
118
119 test('update() batch-updates multiple properties', () => {
120 let aFired = false, bFired = false;
121 GoingsOn.state.subscribe('_t4a', () => { aFired = true; });
122 GoingsOn.state.subscribe('_t4b', () => { bFired = true; });
123 GoingsOn.state.update({ _t4a: 'x', _t4b: 'y' });
124 assert(aFired && bFired, 'Both subscribers should fire');
125 assertEqual(GoingsOn.state._t4a, 'x');
126 assertEqual(GoingsOn.state._t4b, 'y');
127 });
128
129 test('resetPagination(task) resets taskPage to 1', () => {
130 GoingsOn.state.set('taskPage', 5);
131 GoingsOn.state.resetPagination('task');
132 assertEqual(GoingsOn.state.taskPage, 1);
133 });
134
135 test('resetPagination(email) resets emailPage to 1', () => {
136 GoingsOn.state.set('emailPage', 3);
137 GoingsOn.state.resetPagination('email');
138 assertEqual(GoingsOn.state.emailPage, 1);
139 });
140
141 test('clearSelection(task) clears selectedTaskIds Set', () => {
142 GoingsOn.state.selectedTaskIds.add('t1');
143 GoingsOn.state.selectedTaskIds.add('t2');
144 GoingsOn.state.clearSelection('task');
145 assertEqual(GoingsOn.state.selectedTaskIds.size, 0);
146 });
147
148 test('clearSelection(email) clears selectedEmailIds Set', () => {
149 GoingsOn.state.selectedEmailIds.add('e1');
150 GoingsOn.state.clearSelection('email');
151 assertEqual(GoingsOn.state.selectedEmailIds.size, 0);
152 });
153
154 test('multiple subscribers on same key all fire', () => {
155 let a = false, b = false;
156 GoingsOn.state.subscribe('_t5', () => { a = true; });
157 GoingsOn.state.subscribe('_t5', () => { b = true; });
158 GoingsOn.state.set('_t5', 'v');
159 assert(a && b, 'Both should fire');
160 });
161
162 test('subscriber error does not break other subscribers', () => {
163 let secondFired = false;
164 GoingsOn.state.subscribe('_t6', () => { throw new Error('boom'); });
165 GoingsOn.state.subscribe('_t6', () => { secondFired = true; });
166 // Suppress console.error for this test
167 const origError = console.error;
168 console.error = () => {};
169 GoingsOn.state.set('_t6', 'v');
170 console.error = origError;
171 assert(secondFired, 'Second subscriber should still fire');
172 });
173 });
174
175 // ============================================================
176 // Test: GoingsOn.utils — escapeAttr
177 // ============================================================
178
179 describe('GoingsOn.utils.escapeAttr', () => {
180 test('escapes backslashes, quotes, newlines', () => {
181 const r = GoingsOn.utils.escapeAttr('a\\b"c\'d\ne');
182 assert(r.includes('\\\\'), 'Should escape backslash');
183 assert(r.includes('\\"'), 'Should escape double quote');
184 assert(r.includes("\\'"), 'Should escape single quote');
185 assert(r.includes('\\n'), 'Should escape newline');
186 });
187
188 test('returns empty for null/undefined', () => {
189 assertEqual(GoingsOn.utils.escapeAttr(null), '');
190 assertEqual(GoingsOn.utils.escapeAttr(undefined), '');
191 });
192
193 test('converts non-string to string', () => {
194 assertEqual(GoingsOn.utils.escapeAttr(123), '123');
195 assertEqual(GoingsOn.utils.escapeAttr(true), 'true');
196 });
197 });
198
199 // ============================================================
200 // Test: GoingsOn.utils — getErrorMessage
201 // ============================================================
202
203 describe('GoingsOn.utils.getErrorMessage', () => {
204 test('extracts from string', () => {
205 assertEqual(GoingsOn.utils.getErrorMessage('oops'), 'oops');
206 });
207
208 test('extracts from Error object (.message)', () => {
209 assertEqual(GoingsOn.utils.getErrorMessage(new Error('fail')), 'fail');
210 });
211
212 test('uses fallback for unknown type', () => {
213 assertEqual(GoingsOn.utils.getErrorMessage(42, 'fallback'), 'fallback');
214 });
215
216 test('uses default fallback when none provided', () => {
217 assertEqual(GoingsOn.utils.getErrorMessage({}, undefined), 'An error occurred');
218 });
219 });
220
221 // ============================================================
222 // Test: GoingsOn.utils — validateLength, validateEmail
223 // ============================================================
224
225 describe('GoingsOn.utils.validateLength', () => {
226 test('accepts valid length', () => {
227 assert(GoingsOn.utils.validateLength('hello', 10), 'Should accept');
228 });
229
230 test('rejects too long', () => {
231 assert(!GoingsOn.utils.validateLength('hello world', 5), 'Should reject');
232 });
233
234 test('accepts null/empty', () => {
235 assert(GoingsOn.utils.validateLength('', 10), 'Empty should be valid');
236 assert(GoingsOn.utils.validateLength(null, 10), 'Null should be valid');
237 });
238 });
239
240 describe('GoingsOn.utils.validateEmail', () => {
241 test('accepts valid addresses', () => {
242 assert(GoingsOn.utils.validateEmail('user@example.com'), 'Should accept valid');
243 });
244
245 test('rejects invalid', () => {
246 assert(!GoingsOn.utils.validateEmail('notanemail'), 'Should reject invalid');
247 });
248
249 test('accepts empty (optional field)', () => {
250 assert(GoingsOn.utils.validateEmail(''), 'Empty should be valid');
251 });
252 });
253
254 // ============================================================
255 // Test: GoingsOn.utils — parseEmailAddress
256 // ============================================================
257
258 describe('GoingsOn.utils.parseEmailAddress', () => {
259 test('extracts "Name <email>" format', () => {
260 const r = GoingsOn.utils.parseEmailAddress('Jane Smith <jane@example.com>');
261 assertEqual(r.name, 'Jane Smith');
262 assertEqual(r.email, 'jane@example.com');
263 });
264
265 test('handles bare email address', () => {
266 const r = GoingsOn.utils.parseEmailAddress('jane@example.com');
267 assertEqual(r.name, null);
268 assertEqual(r.email, 'jane@example.com');
269 });
270
271 test('handles null/empty input', () => {
272 const r1 = GoingsOn.utils.parseEmailAddress(null);
273 assertEqual(r1.name, null);
274 assertEqual(r1.email, null);
275 const r2 = GoingsOn.utils.parseEmailAddress('');
276 assertEqual(r2.name, null);
277 assertEqual(r2.email, null);
278 });
279 });
280
281 // ============================================================
282 // Test: GoingsOn.utils — debounce
283 // ============================================================
284
285 describe('GoingsOn.utils.debounce', () => {
286 test('does not fire immediately', () => {
287 let called = false;
288 const fn = GoingsOn.utils.debounce(() => { called = true; }, 10);
289 fn();
290 assert(!called, 'Should not fire immediately');
291 });
292
293 test('rapid calls only execute last one', () => {
294 let callCount = 0, lastArg = null;
295 const origST = globalThis.setTimeout;
296 const origCT = globalThis.clearTimeout;
297 let pendingCb = null;
298 globalThis.setTimeout = (cb) => { pendingCb = cb; return 1; };
299 globalThis.clearTimeout = () => { pendingCb = null; };
300
301 const fn = GoingsOn.utils.debounce((arg) => { callCount++; lastArg = arg; }, 100);
302 fn('a');
303 fn('b');
304 fn('c');
305 if (pendingCb) pendingCb();
306
307 assertEqual(callCount, 1);
308 assertEqual(lastArg, 'c');
309
310 globalThis.setTimeout = origST;
311 globalThis.clearTimeout = origCT;
312 });
313 });
314
315 // ============================================================
316 // Test: GoingsOn.utils — escapeHtml
317 // ============================================================
318
319 describe('GoingsOn.utils.escapeHtml', () => {
320 test('escapes angle brackets', () => {
321 const r = GoingsOn.utils.escapeHtml('<b>hi</b>');
322 assert(r.includes('&lt;') && r.includes('&gt;'));
323 });
324
325 test('returns empty for falsy', () => {
326 assertEqual(GoingsOn.utils.escapeHtml(''), '');
327 assertEqual(GoingsOn.utils.escapeHtml(null), '');
328 });
329 });
330
331 // ============================================================
332 // Test: PaginationManager
333 // ============================================================
334
335 describe('PaginationManager', () => {
336 test('constructor sets defaults (page=1, totalItems=0)', () => {
337 const pm = new GoingsOn.PaginationManager('test', 10);
338 assertEqual(pm.currentPage, 1);
339 assertEqual(pm.totalItems, 0);
340 assertEqual(pm.itemsPerPage, 10);
341 });
342
343 test('goToPage(next) increments page', () => {
344 const pm = new GoingsOn.PaginationManager('test', 10);
345 pm.totalItems = 30;
346 pm.goToPage('next');
347 assertEqual(pm.currentPage, 2);
348 });
349
350 test('goToPage(prev) decrements page, clamps to 1', () => {
351 const pm = new GoingsOn.PaginationManager('test', 10);
352 pm.totalItems = 30;
353 pm.currentPage = 2;
354 pm.goToPage('prev');
355 assertEqual(pm.currentPage, 1);
356 pm.goToPage('prev');
357 assertEqual(pm.currentPage, 1);
358 });
359
360 test('goToPage(n) sets specific page, clamped', () => {
361 const pm = new GoingsOn.PaginationManager('test', 10);
362 pm.totalItems = 30;
363 pm.goToPage(3);
364 assertEqual(pm.currentPage, 3);
365 pm.goToPage(99);
366 assertEqual(pm.currentPage, 3); // max page is 3
367 pm.goToPage(0);
368 assertEqual(pm.currentPage, 1);
369 });
370
371 test('getMaxPage() calculates ceil(total/perPage)', () => {
372 const pm = new GoingsOn.PaginationManager('test', 10);
373 pm.totalItems = 25;
374 assertEqual(pm.getMaxPage(), 3);
375 pm.totalItems = 30;
376 assertEqual(pm.getMaxPage(), 3);
377 pm.totalItems = 0;
378 assertEqual(pm.getMaxPage(), 1); // min 1
379 });
380
381 test('setTotalItems() updates and clamps currentPage', () => {
382 const pm = new GoingsOn.PaginationManager('test', 10);
383 pm.currentPage = 5;
384 pm.setTotalItems(20);
385 assertEqual(pm.totalItems, 20);
386 assertEqual(pm.currentPage, 2); // clamped to max page
387 });
388
389 test('reset() returns to page 1', () => {
390 const pm = new GoingsOn.PaginationManager('test', 10);
391 pm.currentPage = 3;
392 pm.reset();
393 assertEqual(pm.currentPage, 1);
394 });
395
396 test('getOffset() returns (page-1)*perPage', () => {
397 const pm = new GoingsOn.PaginationManager('test', 10);
398 pm.currentPage = 3;
399 assertEqual(pm.getOffset(), 20);
400 });
401
402 test('paginate() slices array correctly', () => {
403 const pm = new GoingsOn.PaginationManager('test', 3);
404 pm.totalItems = 7;
405 const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
406 pm.currentPage = 2;
407 assertDeepEqual(pm.paginate(items), ['d', 'e', 'f']);
408 pm.currentPage = 3;
409 assertDeepEqual(pm.paginate(items), ['g']);
410 });
411
412 test('getInfo() returns correct summary object', () => {
413 const pm = new GoingsOn.PaginationManager('test', 10);
414 pm.totalItems = 25;
415 pm.currentPage = 2;
416 const info = pm.getInfo();
417 assertEqual(info.currentPage, 2);
418 assertEqual(info.maxPage, 3);
419 assertEqual(info.start, 11);
420 assertEqual(info.end, 20);
421 assertEqual(info.total, 25);
422 assertEqual(info.hasPrev, true);
423 assertEqual(info.hasNext, true);
424 });
425 });
426
427 // ============================================================
428 // Test: SelectionManager
429 // ============================================================
430
431 describe('SelectionManager', () => {
432 test('constructor initializes empty Set', () => {
433 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
434 assertEqual(sm.selectedIds.size, 0);
435 assertEqual(sm.lastClickedIndex, -1);
436 });
437
438 test('setItems() stores items array', () => {
439 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
440 const items = [{ id: '1' }, { id: '2' }];
441 sm.setItems(items);
442 assertEqual(sm.items.length, 2);
443 });
444
445 test('getSelected() returns the Set', () => {
446 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
447 sm.selectedIds.add('x');
448 assert(sm.getSelected() instanceof Set);
449 assert(sm.getSelected().has('x'));
450 });
451
452 test('hasSelection() returns true when items selected, false when empty', () => {
453 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
454 assert(!sm.hasSelection());
455 sm.selectedIds.add('a');
456 assert(sm.hasSelection());
457 });
458
459 test('getCount() returns correct count', () => {
460 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
461 assertEqual(sm.getCount(), 0);
462 sm.selectedIds.add('a');
463 sm.selectedIds.add('b');
464 assertEqual(sm.getCount(), 2);
465 });
466
467 test('isSelected(id) returns boolean correctly', () => {
468 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
469 sm.selectedIds.add('x');
470 assert(sm.isSelected('x'));
471 assert(!sm.isSelected('y'));
472 });
473
474 test('toggle adds/removes from selectedIds', () => {
475 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
476 sm.setItems([{ id: 'a' }, { id: 'b' }]);
477 // Simulate checking
478 sm.toggle('a', { checked: true }, null);
479 assert(sm.selectedIds.has('a'));
480 // Simulate unchecking
481 sm.toggle('a', { checked: false }, null);
482 assert(!sm.selectedIds.has('a'));
483 });
484
485 test('clear() empties Set and resets lastClickedIndex', () => {
486 const sm = new GoingsOn.SelectionManager('test', '.test', 'bulk-bar');
487 sm.selectedIds.add('a');
488 sm.selectedIds.add('b');
489 sm.lastClickedIndex = 3;
490 sm.clear();
491 assertEqual(sm.selectedIds.size, 0);
492 assertEqual(sm.lastClickedIndex, -1);
493 });
494 });
495
496 // ============================================================
497 // Test: GoingsOn.whatsNew (changelog parsing + rendering)
498 // ============================================================
499
500 describe('GoingsOn.whatsNew', () => {
501 const SAMPLE = [
502 '# Changelog',
503 '',
504 '## [0.4.0] — 2026-06-01',
505 '',
506 'Polish release.',
507 '',
508 '### Added',
509 '- What\'s New dialog after updates',
510 '- Standardized empty states',
511 '',
512 '### Fixed',
513 '- Project list empty copy',
514 '',
515 '## [0.3.0] — 2026-03-28',
516 '',
517 '### Added',
518 '- Initial beta',
519 ].join('\n');
520
521 test('extractSection pulls the requested version body, excluding its header', () => {
522 const section = GoingsOn.whatsNew.extractSection(SAMPLE, '0.4.0');
523 assert(section.includes('Polish release.'), 'keeps the intro line');
524 assert(section.includes('### Added'), 'keeps group headers');
525 assert(section.includes('What\'s New dialog after updates'), 'keeps bullets');
526 assert(!section.includes('[0.4.0]'), 'drops the version header line');
527 assert(!section.includes('Initial beta'), 'stops before the next version');
528 });
529
530 test('extractSection returns empty string for an absent version', () => {
531 assertEqual(GoingsOn.whatsNew.extractSection(SAMPLE, '9.9.9'), '');
532 });
533
534 test('renderSection escapes content and builds structural markup', () => {
535 const html = GoingsOn.whatsNew.renderSection('### Added\n- safe <script> item');
536 assert(html.includes('<h3 class="whats-new-group">Added</h3>'), 'renders group heading');
537 assert(html.includes('<ul class="whats-new-list">'), 'opens a list');
538 assert(html.includes('&lt;script&gt;'), 'escapes HTML in bullets');
539 assert(!html.includes('<script>'), 'no raw markup leaks through');
540 });
541 });
542
543 // ============================================================
544 // Report
545 // ============================================================
546
547 const success = report();
548 process.exit(success ? 0 : 1);
549