~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test(js): add vitest coverage for saveThemeToServer, addLogEntry delegation, and renderSubscriptionCard (#4311)
LearningCircuit94eee3728d22
diff --git a/tests/js/components/subscription-manager-render-card.test.js b/tests/js/components/subscription-manager-render-card.test.jsnew file mode 100644index 0000000000..a49fc77c29--- /dev/null+++ b/tests/js/components/subscription-manager-render-card.test.js@@ -0,0 +1,130 @@+/**+ * Tests for components/subscription-manager.js — renderSubscriptionCard.+ *+ * The card is built by template-string interpolation, so the assertions+ * focus on data correctness (escaping, branching) rather than CSS class+ * spelling. Covers active vs paused, optional folder/notes, and the+ * data-subscription-id round-trip used by the action buttons.+ *+ * Kept in its own file (instead of extending subscription-manager.test.js)+ * so it can land alongside / independently of PR #4297 without merge+ * conflicts on a freshly-created test file.+ */++// Load xss-protection.js first so window.escapeHtml is defined: the card+// renderer escapes user fields via the global helper (the class no longer+// ships its own escapeHtml). In production, base.html loads xss-protection.js+// before subscription-manager.js with matching `defer` ordering.+import '@js/security/xss-protection.js';+import '@js/components/subscription-manager.js';++let manager;++beforeAll(() => {+ // The module wires up its singleton inside a DOMContentLoaded listener;+ // dispatch it manually if happy-dom already fired before the dynamic+ // import settled.+ if (!window.subscriptionManager) {+ document.dispatchEvent(new Event('DOMContentLoaded'));+ }+ manager = window.subscriptionManager;+});++function makeSubscription(overrides = {}) {+ // A baseline subscription that exercises the always-present fields.+ // Use a far-future next_refresh so the computed timeUntil is stable+ // (e.g. "365d" rather than something time-sensitive).+ const oneYearMs = 365 * 24 * 60 * 60 * 1000;+ return {+ id: 'sub-abc-123',+ query_or_topic: 'AI safety',+ refresh_interval_minutes: 60,+ next_refresh: new Date(Date.now() + oneYearMs).toISOString(),+ status: 'active',+ ...overrides,+ };+}++describe('subscriptionManager.renderSubscriptionCard', () => {+ it('includes core fields (id, query, interval) in the output', () => {+ const html = manager.renderSubscriptionCard(makeSubscription());+ expect(html).toContain('data-subscription-id="sub-abc-123"');+ expect(html).toContain('AI safety');+ expect(html).toContain('Every 60 min');+ });++ it('shows a Pause button + pause icon when status is active', () => {+ const html = manager.renderSubscriptionCard(+ makeSubscription({ status: 'active' })+ );+ expect(html).toContain('title="Pause"');+ expect(html).toContain('bi-pause');+ expect(html).not.toContain('title="Resume"');+ expect(html).not.toContain('bi-play');+ });++ it('shows a Resume button + play icon when status is not active (paused)', () => {+ const html = manager.renderSubscriptionCard(+ makeSubscription({ status: 'paused' })+ );+ expect(html).toContain('title="Resume"');+ expect(html).toContain('bi-play');+ expect(html).not.toContain('title="Pause"');+ });++ it('omits the folder span when subscription has no folder', () => {+ const html = manager.renderSubscriptionCard(+ makeSubscription({ folder: undefined })+ );+ expect(html).not.toContain('bi-folder');+ });++ it('renders the folder span when a folder is set', () => {+ const html = manager.renderSubscriptionCard(+ makeSubscription({ folder: 'Research' })+ );+ expect(html).toContain('bi-folder');+ expect(html).toContain('Research');+ });++ it('omits the notes paragraph when no notes are provided', () => {+ const html = manager.renderSubscriptionCard(+ makeSubscription({ notes: undefined })+ );+ // The notes branch is the only <p> in the card template.+ expect(html).not.toContain('<p ');+ });++ it('renders notes when provided', () => {+ const html = manager.renderSubscriptionCard(+ makeSubscription({ notes: 'Important topic' })+ );+ expect(html).toContain('Important topic');+ expect(html).toContain('<p ');+ });++ it('escapes HTML in user-supplied fields (XSS protection)', () => {+ const html = manager.renderSubscriptionCard(+ makeSubscription({+ query_or_topic: '<script>alert(1)</script>',+ folder: '<img src=x>',+ notes: '<svg onload=alert(1)>',+ })+ );+ // Local escapeHtml uses div+textContent+innerHTML, which escapes+ // `<` to `<`. The literal `<script>` substring must not appear.+ expect(html).not.toContain('<script>');+ expect(html).not.toContain('<img src=x>');+ expect(html).not.toContain('<svg onload=alert(1)>');+ // The escaped form should be present.+ expect(html).toContain('<script>');+ });++ it('embeds the formatTimeUntil output near "Next:"', () => {+ // Sanity check that the formatTimeUntil method is being called and+ // its output is interpolated into the card. The exact number depends+ // on system time, so just assert that a unit suffix follows "Next:".+ const html = manager.renderSubscriptionCard(makeSubscription());+ expect(html).toMatch(/Next:\s*\d+[mhd]/);+ });+});diff --git a/tests/js/services/socket.test.js b/tests/js/services/socket.test.jsindex 2dcaa6f75a..0f5c824c41 100644--- a/tests/js/services/socket.test.js+++ b/tests/js/services/socket.test.js@@ -133,3 +133,76 @@ describe('unsubscribeFromResearch', () => {expect(emittedEvents).not.toContain('leave');});});++describe('addLogEntry — delegation routing (window._socketAddLogEntry)', () => {+ // The IIFE-private addLogEntry is reachable from outside only via the+ // exported window._socketAddLogEntry. The function delegates in three+ // tiers: (1) if window._socketAddLogEntry was replaced by something+ // OTHER than itself (logpanel.js does this in production), call that;+ // (2) else if window.addConsoleLog exists, call it with adapted args;+ // (3) else fall back to inline DOM template work — NOT tested here+ // (would mostly assert CSS class names we'd type in the test setup).++ let originalAddLogEntry;+ let originalAddConsoleLog;++ beforeAll(() => {+ // Capture the original (which IS the function we want to invoke)+ // BEFORE any test reassigns window._socketAddLogEntry.+ originalAddLogEntry = window._socketAddLogEntry;+ });++ beforeEach(() => {+ originalAddConsoleLog = window.addConsoleLog;+ });++ afterEach(() => {+ // Restore both globals so the next test starts clean.+ window._socketAddLogEntry = originalAddLogEntry;+ if (originalAddConsoleLog === undefined) {+ delete window.addConsoleLog;+ } else {+ window.addConsoleLog = originalAddConsoleLog;+ }+ });++ it('delegates to a replaced window._socketAddLogEntry (logpanel override)', () => {+ const spy = vi.fn();+ window._socketAddLogEntry = spy;++ originalAddLogEntry({ message: 'hi', type: 'info' });++ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy).toHaveBeenCalledWith({ message: 'hi', type: 'info' });+ });++ it('falls back to window.addConsoleLog when _socketAddLogEntry was not overridden', () => {+ const consoleSpy = vi.fn();+ window.addConsoleLog = consoleSpy;+ // _socketAddLogEntry intentionally NOT overridden — it === originalAddLogEntry,+ // so the first branch is skipped.++ originalAddLogEntry({ message: 'm', type: 'warning', metadata: { foo: 'bar' } });++ expect(consoleSpy).toHaveBeenCalledTimes(1);+ expect(consoleSpy).toHaveBeenCalledWith('m', 'warning', { foo: 'bar' });+ });++ it('derives logLevel from metadata.type when top-level type is missing', () => {+ const consoleSpy = vi.fn();+ window.addConsoleLog = consoleSpy;++ originalAddLogEntry({ message: 'm', metadata: { type: 'error' } });++ expect(consoleSpy).toHaveBeenCalledWith('m', 'error', { type: 'error' });+ });++ it('defaults logLevel to "info" when neither type nor metadata.type is present', () => {+ const consoleSpy = vi.fn();+ window.addConsoleLog = consoleSpy;++ originalAddLogEntry({ message: 'm' });++ expect(consoleSpy).toHaveBeenCalledWith('m', 'info', undefined);+ });+});diff --git a/tests/js/services/theme.test.js b/tests/js/services/theme.test.jsindex faee2db1ac..7bafb92a26 100644--- a/tests/js/services/theme.test.js+++ b/tests/js/services/theme.test.js@@ -156,4 +156,61 @@ describe('themeService', () => {expect(() => theme.populateThemeDropdown(null)).not.toThrow();});});++ describe('saveThemeToServer', () => {+ // Restore each test's fetch mock and CSRF stub so we don't leak+ // assertions across the outer describe block's later tests.+ let originalGetCsrfToken;+ beforeEach(() => {+ originalGetCsrfToken = window.api.getCsrfToken;+ });+ afterEach(() => {+ window.api.getCsrfToken = originalGetCsrfToken;+ });++ it('returns Promise.resolve() without calling fetch when CSRF is missing', async () => {+ window.api.getCsrfToken = () => '';+ const fetchSpy = vi.fn();+ globalThis.fetch = fetchSpy;++ await theme.saveThemeToServer('nord');++ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('PUTs to /settings/api/app.theme with CSRF header and JSON body', async () => {+ window.api.getCsrfToken = () => 'csrf-test-123';+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) })+ );++ await theme.saveThemeToServer('nord');++ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ const [url, init] = globalThis.fetch.mock.calls[0];+ expect(url).toBe('/settings/api/app.theme');+ expect(init.method).toBe('PUT');+ expect(init.headers['Content-Type']).toBe('application/json');+ expect(init.headers['X-CSRFToken']).toBe('csrf-test-123');+ expect(JSON.parse(init.body)).toEqual({ value: 'nord' });+ });++ it('swallows non-ok responses without rejecting the caller', async () => {+ window.api.getCsrfToken = () => 'csrf-test-123';+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({}) })+ );++ // Should not throw — the .catch in saveThemeToServer turns the+ // HTTP 404 into a warning log.+ await expect(theme.saveThemeToServer('nord')).resolves.toBeUndefined();+ });++ it('swallows network errors without rejecting the caller', async () => {+ window.api.getCsrfToken = () => 'csrf-test-123';+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('offline')));++ await expect(theme.saveThemeToServer('nord')).resolves.toBeUndefined();+ });+ });});