Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add vitest unit tests for frontend utils and persistence modules (0% to 92-100%)

Murtaza Nasird37cf7693e84
diff --git a/static/js/modules/db/incognito-storage.test.js b/static/js/modules/db/incognito-storage.test.js
new file mode 100644
index 00000000..66b12282
--- /dev/null
+++ b/static/js/modules/db/incognito-storage.test.js
@@ -0,0 +1,131 @@
+/**
+ * Vitest tests for the incognito-mode storage helpers.
+ *
+ * These functions wrap sessionStorage so an incognito recording lives only for
+ * the lifetime of the tab. sessionStorage does not exist in the node test
+ * environment, so we install a small in-memory stub (the same in-memory
+ * philosophy the other db tests use for fetch/localStorage/IndexedDB).
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import {
+ saveIncognitoRecording,
+ getIncognitoRecording,
+ clearIncognitoRecording,
+ hasIncognitoRecording,
+ updateIncognitoRecording,
+} from './incognito-storage.js';
+
+const INCOGNITO_KEY = 'speakr_incognito_recording';
+
+function installSessionStorage() {
+ const store = new Map();
+ const api = {
+ getItem: vi.fn((k) => (store.has(k) ? store.get(k) : null)),
+ setItem: vi.fn((k, v) => { store.set(k, String(v)); }),
+ removeItem: vi.fn((k) => { store.delete(k); }),
+ clear: vi.fn(() => store.clear()),
+ _store: store,
+ };
+ globalThis.sessionStorage = api;
+ return api;
+}
+
+describe('incognito-storage', () => {
+ let ss;
+
+ beforeEach(() => {
+ ss = installSessionStorage();
+ // Silence the module's console noise but keep spies inspectable.
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete globalThis.sessionStorage;
+ });
+
+ describe('saveIncognitoRecording / getIncognitoRecording', () => {
+ it('round-trips an object through sessionStorage', () => {
+ const data = { title: 'Note', transcription: 'hello', summary: 's', tags: ['a'] };
+ saveIncognitoRecording(data);
+
+ expect(ss.setItem).toHaveBeenCalledWith(INCOGNITO_KEY, JSON.stringify(data));
+ expect(getIncognitoRecording()).toEqual(data);
+ });
+
+ it('serializes to JSON (string) under the hood', () => {
+ saveIncognitoRecording({ n: 1 });
+ expect(ss._store.get(INCOGNITO_KEY)).toBe('{"n":1}');
+ });
+
+ it('getIncognitoRecording returns null when nothing is stored', () => {
+ expect(getIncognitoRecording()).toBeNull();
+ });
+
+ it('getIncognitoRecording returns null and logs on corrupt JSON', () => {
+ ss._store.set(INCOGNITO_KEY, '{not valid json');
+ expect(getIncognitoRecording()).toBeNull();
+ expect(console.error).toHaveBeenCalled();
+ });
+
+ it('saveIncognitoRecording swallows errors when setItem throws (quota)', () => {
+ ss.setItem.mockImplementation(() => { throw new Error('QuotaExceededError'); });
+ expect(() => saveIncognitoRecording({ big: 'x' })).not.toThrow();
+ expect(console.error).toHaveBeenCalled();
+ });
+ });
+
+ describe('hasIncognitoRecording', () => {
+ it('is false when empty and true after a save', () => {
+ expect(hasIncognitoRecording()).toBe(false);
+ saveIncognitoRecording({ a: 1 });
+ expect(hasIncognitoRecording()).toBe(true);
+ });
+
+ it('returns false when sessionStorage throws', () => {
+ ss.getItem.mockImplementation(() => { throw new Error('blocked'); });
+ expect(hasIncognitoRecording()).toBe(false);
+ });
+ });
+
+ describe('clearIncognitoRecording', () => {
+ it('removes the stored recording', () => {
+ saveIncognitoRecording({ a: 1 });
+ expect(hasIncognitoRecording()).toBe(true);
+ clearIncognitoRecording();
+ expect(ss.removeItem).toHaveBeenCalledWith(INCOGNITO_KEY);
+ expect(hasIncognitoRecording()).toBe(false);
+ });
+
+ it('swallows errors when removeItem throws', () => {
+ ss.removeItem.mockImplementation(() => { throw new Error('boom'); });
+ expect(() => clearIncognitoRecording()).not.toThrow();
+ expect(console.error).toHaveBeenCalled();
+ });
+ });
+
+ describe('updateIncognitoRecording', () => {
+ it('merges updates into the existing record and returns it', () => {
+ saveIncognitoRecording({ title: 'Old', transcription: 't', keep: true });
+ const updated = updateIncognitoRecording({ title: 'New', extra: 1 });
+
+ expect(updated).toEqual({ title: 'New', transcription: 't', keep: true, extra: 1 });
+ // Persisted as well.
+ expect(getIncognitoRecording()).toEqual(updated);
+ });
+
+ it('returns null when there is nothing to update', () => {
+ expect(updateIncognitoRecording({ title: 'New' })).toBeNull();
+ expect(hasIncognitoRecording()).toBe(false);
+ });
+
+ it('returns null and logs when retrieval throws', () => {
+ saveIncognitoRecording({ a: 1 });
+ // Make the read inside update blow up after the record exists.
+ ss.getItem.mockImplementation(() => { throw new Error('explode'); });
+ expect(updateIncognitoRecording({ b: 2 })).toBeNull();
+ });
+ });
+});
diff --git a/static/js/modules/db/recording-persistence.test.js b/static/js/modules/db/recording-persistence.test.js
new file mode 100644
index 00000000..80513d62
--- /dev/null
+++ b/static/js/modules/db/recording-persistence.test.js
@@ -0,0 +1,390 @@
+/**
+ * Vitest tests for the IndexedDB recording-persistence layer (crash recovery).
+ *
+ * There is no real IndexedDB (or browser) in the node test environment and the
+ * repo deliberately avoids adding test dependencies, so we install a small
+ * in-memory IndexedDB stub that implements only the surface this module uses:
+ * indexedDB.open() with onupgradeneeded/onsuccess/onerror, and a single object
+ * store supporting get/put/delete via IDBRequest-style callbacks. The module
+ * caches its db handle at module scope, so each test re-imports it fresh with
+ * vi.resetModules() against a freshly-installed mock for deterministic state.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const STORE_NAME = 'activeRecording';
+
+/**
+ * Build an in-memory IndexedDB stub.
+ *
+ * config.failOpen -> indexedDB.open() fires onerror
+ * config.opError -> get/put/delete requests fire onerror (to exercise catch
+ * blocks). Toggle it after seeding data.
+ */
+function createMockIndexedDB() {
+ const stores = new Map(); // storeName -> Map(key -> value)
+ let opened = false;
+ const config = { failOpen: false, opError: false };
+
+ function makeRequest(resultFn) {
+ const req = { onsuccess: null, onerror: null, result: undefined, error: null };
+ queueMicrotask(() => {
+ if (config.opError) {
+ req.error = new Error('op failed');
+ if (req.onerror) req.onerror({ target: req });
+ return;
+ }
+ try {
+ req.result = resultFn();
+ if (req.onsuccess) req.onsuccess({ target: req });
+ } catch (e) {
+ req.error = e;
+ if (req.onerror) req.onerror({ target: req });
+ }
+ });
+ return req;
+ }
+
+ function makeObjectStore(name) {
+ return {
+ createIndex: () => {},
+ get: (key) => makeRequest(() => {
+ const s = stores.get(name);
+ return s ? s.get(key) : undefined;
+ }),
+ put: (value) => makeRequest(() => {
+ if (!stores.has(name)) stores.set(name, new Map());
+ stores.get(name).set(value.id, value);
+ return value.id;
+ }),
+ delete: (key) => makeRequest(() => {
+ const s = stores.get(name);
+ if (s) s.delete(key);
+ return undefined;
+ }),
+ };
+ }
+
+ function makeDB() {
+ return {
+ objectStoreNames: { contains: (n) => stores.has(n) },
+ createObjectStore: (name) => {
+ stores.set(name, new Map());
+ return makeObjectStore(name);
+ },
+ transaction: () => ({ objectStore: (name) => makeObjectStore(name) }),
+ };
+ }
+
+ const indexedDB = {
+ open: () => {
+ const req = {
+ onsuccess: null, onerror: null, onupgradeneeded: null,
+ result: null, error: null,
+ };
+ queueMicrotask(() => {
+ if (config.failOpen) {
+ req.error = new Error('open failed');
+ if (req.onerror) req.onerror({ target: req });
+ return;
+ }
+ const db = makeDB();
+ req.result = db;
+ if (!opened) {
+ opened = true;
+ if (req.onupgradeneeded) req.onupgradeneeded({ target: { result: db } });
+ }
+ if (req.onsuccess) req.onsuccess({ target: req });
+ });
+ return req;
+ },
+ };
+
+ return { indexedDB, config, stores, openCount: () => stores };
+}
+
+// Minimal Blob stub: records its parts/type and exposes size + arrayBuffer.
+class MockBlob {
+ constructor(parts = [], opts = {}) {
+ this.parts = parts;
+ this.type = opts.type;
+ this.size = parts.reduce((n, p) => n + (p && p.byteLength ? p.byteLength : (p && p.length ? p.length : 0)), 0);
+ }
+ async arrayBuffer() {
+ return new ArrayBuffer(this.size);
+ }
+}
+
+function makeChunkBlob(size = 4) {
+ const buf = new ArrayBuffer(size);
+ return { size, arrayBuffer: vi.fn(async () => buf) };
+}
+
+describe('recording-persistence', () => {
+ let mock;
+ let mod;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ mock = createMockIndexedDB();
+ global.indexedDB = mock.indexedDB;
+ global.Blob = MockBlob;
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ mod = await import('./recording-persistence.js');
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete global.indexedDB;
+ delete global.Blob;
+ delete global.navigator;
+ });
+
+ describe('initDB', () => {
+ it('opens the database and resolves a handle', async () => {
+ const db = await mod.initDB();
+ expect(db).toBeTruthy();
+ expect(typeof db.transaction).toBe('function');
+ });
+
+ it('caches the handle so repeated calls return the same instance', async () => {
+ const a = await mod.initDB();
+ const b = await mod.initDB();
+ expect(a).toBe(b);
+ });
+
+ it('rejects when the open request errors', async () => {
+ mock.config.failOpen = true;
+ await expect(mod.initDB()).rejects.toThrow(/open failed/);
+ });
+ });
+
+ describe('startRecordingSession', () => {
+ it('stores a session with sensible defaults', async () => {
+ const session = await mod.startRecordingSession({ mode: 'meeting' });
+ expect(session.id).toBe('current');
+ expect(session.mode).toBe('meeting');
+ expect(session.notes).toBe('');
+ expect(session.tags).toEqual([]);
+ expect(session.asrOptions).toEqual({});
+ expect(session.chunks).toEqual([]);
+ expect(session.mimeType).toBe('audio/webm');
+ expect(session.duration).toBe(0);
+ // Persisted under key 'current'.
+ expect(mock.stores.get(STORE_NAME).get('current')).toMatchObject({ mode: 'meeting' });
+ });
+
+ it('keeps caller-provided values', async () => {
+ const session = await mod.startRecordingSession({
+ mode: 'voice', notes: 'hi', tags: ['x'], asrOptions: { diarize: true }, mimeType: 'audio/ogg',
+ });
+ expect(session.notes).toBe('hi');
+ expect(session.tags).toEqual(['x']);
+ expect(session.asrOptions).toEqual({ diarize: true });
+ expect(session.mimeType).toBe('audio/ogg');
+ });
+
+ it('rejects when the DB cannot be opened', async () => {
+ mock.config.failOpen = true;
+ await expect(mod.startRecordingSession({ mode: 'm' })).rejects.toThrow();
+ });
+ });
+
+ describe('saveChunk', () => {
+ it('appends a chunk to the active session', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ await mod.saveChunk(makeChunkBlob(10), 0);
+ await mod.saveChunk(makeChunkBlob(20), 1);
+
+ const session = mock.stores.get(STORE_NAME).get('current');
+ expect(session.chunks).toHaveLength(2);
+ expect(session.chunks[0]).toMatchObject({ index: 0, size: 10 });
+ expect(session.chunks[1]).toMatchObject({ index: 1, size: 20 });
+ expect(session.chunks[0].data).toBeInstanceOf(ArrayBuffer);
+ });
+
+ it('warns and does nothing when there is no active session', async () => {
+ await mod.initDB(); // store exists, but no 'current' record
+ await mod.saveChunk(makeChunkBlob(5), 0);
+ expect(console.warn).toHaveBeenCalled();
+ expect(mock.stores.get(STORE_NAME).get('current')).toBeUndefined();
+ });
+
+ it('does not throw when arrayBuffer() fails', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ const bad = { size: 1, arrayBuffer: vi.fn(async () => { throw new Error('decode'); }) };
+ await expect(mod.saveChunk(bad, 0)).resolves.toBeUndefined();
+ expect(console.error).toHaveBeenCalled();
+ });
+ });
+
+ describe('updateRecordingMetadata', () => {
+ it('merges updates into the session', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ await mod.updateRecordingMetadata({ duration: 42, notes: 'updated' });
+ const session = mock.stores.get(STORE_NAME).get('current');
+ expect(session.duration).toBe(42);
+ expect(session.notes).toBe('updated');
+ });
+
+ it('warns and returns when there is no active session', async () => {
+ await mod.initDB();
+ await mod.updateRecordingMetadata({ duration: 1 });
+ expect(console.warn).toHaveBeenCalled();
+ });
+
+ it('swallows errors from the store', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ mock.config.opError = true;
+ await expect(mod.updateRecordingMetadata({ duration: 1 })).resolves.toBeUndefined();
+ expect(console.error).toHaveBeenCalled();
+ });
+ });
+
+ describe('pruneOldChunks', () => {
+ async function seedChunks(n) {
+ await mod.startRecordingSession({ mode: 'm' });
+ for (let i = 0; i < n; i++) {
+ await mod.saveChunk(makeChunkBlob(1), i);
+ }
+ }
+
+ it('keeps only the last keepLast chunks', async () => {
+ await seedChunks(8);
+ await mod.pruneOldChunks(3);
+ const session = mock.stores.get(STORE_NAME).get('current');
+ expect(session.chunks).toHaveLength(3);
+ expect(session.chunks.map(c => c.index)).toEqual([5, 6, 7]);
+ });
+
+ it('is a no-op when chunk count is within keepLast', async () => {
+ await seedChunks(2);
+ await mod.pruneOldChunks(5);
+ expect(mock.stores.get(STORE_NAME).get('current').chunks).toHaveLength(2);
+ });
+
+ it('is a no-op when there is no session', async () => {
+ await mod.initDB();
+ await expect(mod.pruneOldChunks(3)).resolves.toBeUndefined();
+ });
+
+ it('defaults keepLast to 5', async () => {
+ await seedChunks(9);
+ await mod.pruneOldChunks();
+ expect(mock.stores.get(STORE_NAME).get('current').chunks).toHaveLength(5);
+ });
+
+ it('swallows errors (best-effort)', async () => {
+ await seedChunks(8);
+ mock.config.opError = true;
+ await expect(mod.pruneOldChunks(2)).resolves.toBeUndefined();
+ });
+ });
+
+ describe('checkForRecoverableRecording', () => {
+ it('returns null when there is no session', async () => {
+ await mod.initDB();
+ expect(await mod.checkForRecoverableRecording()).toBeNull();
+ });
+
+ it('returns null when the session has no chunks', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ expect(await mod.checkForRecoverableRecording()).toBeNull();
+ });
+
+ it('reports total size and the tracked duration', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ await mod.saveChunk(makeChunkBlob(10), 0);
+ await mod.saveChunk(makeChunkBlob(30), 1);
+ await mod.updateRecordingMetadata({ duration: 17 });
+
+ const info = await mod.checkForRecoverableRecording();
+ expect(info.totalSize).toBe(40);
+ expect(info.duration).toBe(17);
+ expect(info.chunks).toHaveLength(2);
+ });
+
+ it('estimates duration from chunk count (x5s) when not tracked', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ await mod.saveChunk(makeChunkBlob(1), 0);
+ await mod.saveChunk(makeChunkBlob(1), 1);
+ await mod.saveChunk(makeChunkBlob(1), 2);
+ // duration stays 0 -> falls back to chunks.length * 5
+ const info = await mod.checkForRecoverableRecording();
+ expect(info.duration).toBe(15);
+ });
+
+ it('returns null on store error', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ mock.config.opError = true;
+ expect(await mod.checkForRecoverableRecording()).toBeNull();
+ });
+ });
+
+ describe('recoverRecording', () => {
+ it('rebuilds chunks as Blobs and returns metadata', async () => {
+ await mod.startRecordingSession({
+ mode: 'voice', notes: 'n', tags: ['t'], asrOptions: { d: 1 }, mimeType: 'audio/ogg',
+ });
+ await mod.saveChunk(makeChunkBlob(8), 0);
+ await mod.saveChunk(makeChunkBlob(8), 1);
+ await mod.updateRecordingMetadata({ duration: 9 });
+
+ const result = await mod.recoverRecording();
+ expect(result.chunks).toHaveLength(2);
+ expect(result.chunks[0]).toBeInstanceOf(MockBlob);
+ expect(result.chunks[0].type).toBe('audio/ogg');
+ expect(result.metadata).toMatchObject({
+ mode: 'voice', notes: 'n', tags: ['t'], asrOptions: { d: 1 },
+ mimeType: 'audio/ogg', duration: 9,
+ });
+ });
+
+ it('returns null when there is nothing to recover', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ expect(await mod.recoverRecording()).toBeNull();
+ });
+
+ it('returns null on store error', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ mock.config.opError = true;
+ expect(await mod.recoverRecording()).toBeNull();
+ });
+ });
+
+ describe('clearRecordingSession', () => {
+ it('deletes the stored session', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ expect(mock.stores.get(STORE_NAME).get('current')).toBeTruthy();
+ await mod.clearRecordingSession();
+ expect(mock.stores.get(STORE_NAME).get('current')).toBeUndefined();
+ });
+
+ it('swallows errors', async () => {
+ await mod.startRecordingSession({ mode: 'm' });
+ mock.config.opError = true;
+ await expect(mod.clearRecordingSession()).resolves.toBeUndefined();
+ expect(console.error).toHaveBeenCalled();
+ });
+ });
+
+ describe('getDatabaseSize', () => {
+ it('returns usage/quota/percentage from navigator.storage.estimate', async () => {
+ global.navigator = { storage: { estimate: vi.fn(async () => ({ usage: 25, quota: 100 })) } };
+ const size = await mod.getDatabaseSize();
+ expect(size).toEqual({ usage: 25, quota: 100, percentage: '25.00' });
+ });
+
+ it('returns null when the Storage API is unavailable', async () => {
+ global.navigator = {};
+ expect(await mod.getDatabaseSize()).toBeNull();
+ });
+
+ it('returns null when estimate throws', async () => {
+ global.navigator = { storage: { estimate: vi.fn(async () => { throw new Error('nope'); }) } };
+ expect(await mod.getDatabaseSize()).toBeNull();
+ });
+ });
+});
diff --git a/static/js/modules/utils/api.test.js b/static/js/modules/utils/api.test.js
new file mode 100644
index 00000000..e1c5329d
--- /dev/null
+++ b/static/js/modules/utils/api.test.js
@@ -0,0 +1,101 @@
+/**
+ * Unit tests for createApiClient in api.js.
+ *
+ * createApiClient is a thin fetch wrapper, but it owns real logic worth
+ * pinning: it attaches the CSRF token (read lazily from a ref-like object on
+ * every call), sets the JSON content type for json verbs, omits it for
+ * multipart form data, serialises bodies, and returns the fetch response. We
+ * mock global.fetch and assert the request shape, mirroring the DOM-mock
+ * pattern used elsewhere in the suite.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { createApiClient } from './api.js';
+
+describe('createApiClient', () => {
+ let fetchMock;
+ let originalFetch;
+ let csrfToken;
+
+ beforeEach(() => {
+ fetchMock = vi.fn(() => Promise.resolve({ ok: true, status: 200 }));
+ originalFetch = global.fetch;
+ global.fetch = fetchMock;
+ csrfToken = { value: 'token-abc' };
+ });
+
+ afterEach(() => {
+ global.fetch = originalFetch;
+ });
+
+ it('get() sends CSRF + JSON content-type headers and no method', async () => {
+ const api = createApiClient(csrfToken);
+ const res = await api.get('/items');
+ expect(res).toEqual({ ok: true, status: 200 });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toBe('/items');
+ expect(opts.method).toBeUndefined();
+ expect(opts.headers).toEqual({
+ 'X-CSRFToken': 'token-abc',
+ 'Content-Type': 'application/json',
+ });
+ });
+
+ it('post() uses POST and serialises the body, defaulting to {}', async () => {
+ const api = createApiClient(csrfToken);
+ await api.post('/create', { name: 'x' });
+ let [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toBe('/create');
+ expect(opts.method).toBe('POST');
+ expect(opts.body).toBe(JSON.stringify({ name: 'x' }));
+ expect(opts.headers['Content-Type']).toBe('application/json');
+ expect(opts.headers['X-CSRFToken']).toBe('token-abc');
+
+ await api.post('/create');
+ [, opts] = fetchMock.mock.calls[1];
+ expect(opts.body).toBe('{}');
+ });
+
+ it('put() uses PUT and serialises the body', async () => {
+ const api = createApiClient(csrfToken);
+ await api.put('/update/1', { a: 1 });
+ const [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toBe('/update/1');
+ expect(opts.method).toBe('PUT');
+ expect(opts.body).toBe(JSON.stringify({ a: 1 }));
+ expect(opts.headers['Content-Type']).toBe('application/json');
+ });
+
+ it('delete() uses DELETE with CSRF + JSON headers and no body', async () => {
+ const api = createApiClient(csrfToken);
+ await api.delete('/remove/1');
+ const [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toBe('/remove/1');
+ expect(opts.method).toBe('DELETE');
+ expect(opts.body).toBeUndefined();
+ expect(opts.headers['X-CSRFToken']).toBe('token-abc');
+ expect(opts.headers['Content-Type']).toBe('application/json');
+ });
+
+ it('postFormData() sends the form body and omits the content-type header', async () => {
+ const api = createApiClient(csrfToken);
+ const form = { isForm: true };
+ await api.postFormData('/upload', form);
+ const [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toBe('/upload');
+ expect(opts.method).toBe('POST');
+ expect(opts.body).toBe(form);
+ expect(opts.headers).toEqual({ 'X-CSRFToken': 'token-abc' });
+ expect(opts.headers['Content-Type']).toBeUndefined();
+ });
+
+ it('reads the CSRF token lazily on each request', async () => {
+ const api = createApiClient(csrfToken);
+ await api.get('/first');
+ csrfToken.value = 'rotated-token';
+ await api.get('/second');
+ expect(fetchMock.mock.calls[0][1].headers['X-CSRFToken']).toBe('token-abc');
+ expect(fetchMock.mock.calls[1][1].headers['X-CSRFToken']).toBe('rotated-token');
+ });
+});
diff --git a/static/js/modules/utils/colors.test.js b/static/js/modules/utils/colors.test.js
new file mode 100644
index 00000000..610fcc27
--- /dev/null
+++ b/static/js/modules/utils/colors.test.js
@@ -0,0 +1,49 @@
+/**
+ * Unit tests for getContrastTextColor in colors.js.
+ *
+ * The helper returns 'black' for backgrounds whose simple luminance exceeds
+ * 0.65 and 'white' otherwise, falling back to 'white' for falsy input or when
+ * the luminance computation throws.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { getContrastTextColor } from './colors.js';
+
+describe('getContrastTextColor', () => {
+ it('defaults to white for falsy input', () => {
+ expect(getContrastTextColor(undefined)).toBe('white');
+ expect(getContrastTextColor(null)).toBe('white');
+ expect(getContrastTextColor('')).toBe('white');
+ });
+
+ it('returns black for very light backgrounds', () => {
+ expect(getContrastTextColor('#ffffff')).toBe('black');
+ expect(getContrastTextColor('#ffff00')).toBe('black'); // yellow, lum ~0.886
+ expect(getContrastTextColor('#cccccc')).toBe('black'); // lum 0.8
+ });
+
+ it('returns white for dark and medium backgrounds', () => {
+ expect(getContrastTextColor('#000000')).toBe('white');
+ expect(getContrastTextColor('#008000')).toBe('white'); // green
+ expect(getContrastTextColor('#808080')).toBe('white'); // mid grey, lum ~0.5
+ });
+
+ it('expands 3-digit hex shorthand', () => {
+ expect(getContrastTextColor('#fff')).toBe('black');
+ expect(getContrastTextColor('#000')).toBe('white');
+ });
+
+ it('tolerates a missing leading hash', () => {
+ expect(getContrastTextColor('ffffff')).toBe('black');
+ expect(getContrastTextColor('000000')).toBe('white');
+ });
+
+ it('falls back to white for an unparseable hex string (NaN luminance)', () => {
+ expect(getContrastTextColor('notacolor')).toBe('white');
+ });
+
+ it('falls back to white when the input throws inside the calculation', () => {
+ // A non-string truthy value has no .replace and throws, exercising the catch branch.
+ expect(getContrastTextColor(123)).toBe('white');
+ });
+});
diff --git a/static/js/modules/utils/dates.test.js b/static/js/modules/utils/dates.test.js
new file mode 100644
index 00000000..6f0d1f5d
--- /dev/null
+++ b/static/js/modules/utils/dates.test.js
@@ -0,0 +1,164 @@
+/**
+ * Unit tests for the relative-date helpers in dates.js.
+ *
+ * Every helper except isSameDay/getDateForSorting reads `new Date()` for "now",
+ * so we pin the system clock with fake timers to a fixed mid-month Wednesday
+ * (2024-06-12, getDay()===3). All input dates are built with the local
+ * `new Date(year, monthIndex, day)` constructor so the comparisons happen in
+ * the same timezone as the helpers and stay deterministic in any CI timezone.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ isSameDay,
+ isToday,
+ isYesterday,
+ isThisWeek,
+ isLastWeek,
+ isThisMonth,
+ isLastMonth,
+ getDateForSorting,
+} from './dates.js';
+
+// Wednesday, 12 June 2024 at noon. Week (Mon-Sun) = Jun 10 - Jun 16.
+const NOW = new Date(2024, 5, 12, 12, 0, 0);
+
+describe('isSameDay', () => {
+ it('is true for the same calendar day at different times', () => {
+ expect(isSameDay(new Date(2024, 5, 12, 8), new Date(2024, 5, 12, 20))).toBe(true);
+ });
+
+ it('is false for different days', () => {
+ expect(isSameDay(new Date(2024, 5, 12), new Date(2024, 5, 13))).toBe(false);
+ });
+
+ it('is false for the same day number in a different month', () => {
+ expect(isSameDay(new Date(2024, 5, 12), new Date(2024, 6, 12))).toBe(false);
+ });
+
+ it('is false for the same day/month in a different year', () => {
+ expect(isSameDay(new Date(2024, 5, 12), new Date(2023, 5, 12))).toBe(false);
+ });
+});
+
+describe('relative-to-now helpers', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe('isToday', () => {
+ it('is true for today regardless of time of day', () => {
+ expect(isToday(new Date(2024, 5, 12, 0, 0, 1))).toBe(true);
+ expect(isToday(new Date(2024, 5, 12, 23, 59))).toBe(true);
+ });
+ it('is false for yesterday and tomorrow', () => {
+ expect(isToday(new Date(2024, 5, 11))).toBe(false);
+ expect(isToday(new Date(2024, 5, 13))).toBe(false);
+ });
+ });
+
+ describe('isYesterday', () => {
+ it('is true for the day before now', () => {
+ expect(isYesterday(new Date(2024, 5, 11, 15))).toBe(true);
+ });
+ it('is false for today and two days ago', () => {
+ expect(isYesterday(new Date(2024, 5, 12))).toBe(false);
+ expect(isYesterday(new Date(2024, 5, 10))).toBe(false);
+ });
+ });
+
+ describe('isThisWeek', () => {
+ it('is true for the Monday and Sunday bounding the current week', () => {
+ expect(isThisWeek(new Date(2024, 5, 10))).toBe(true); // Monday
+ expect(isThisWeek(new Date(2024, 5, 16, 12))).toBe(true); // Sunday
+ });
+ it('is false just outside the week boundaries', () => {
+ expect(isThisWeek(new Date(2024, 5, 9, 12))).toBe(false); // prev Sunday
+ expect(isThisWeek(new Date(2024, 5, 17))).toBe(false); // next Monday
+ });
+ });
+
+ describe('isLastWeek', () => {
+ it('is true for the previous Monday-to-Sunday window (Jun 3 - Jun 9)', () => {
+ expect(isLastWeek(new Date(2024, 5, 3))).toBe(true);
+ expect(isLastWeek(new Date(2024, 5, 9, 12))).toBe(true);
+ });
+ it('is false for the current week and two weeks ago', () => {
+ expect(isLastWeek(new Date(2024, 5, 10))).toBe(false);
+ expect(isLastWeek(new Date(2024, 5, 2))).toBe(false);
+ });
+ });
+
+ describe('isThisMonth', () => {
+ it('is true for any day in the current month/year', () => {
+ expect(isThisMonth(new Date(2024, 5, 1))).toBe(true);
+ expect(isThisMonth(new Date(2024, 5, 30))).toBe(true);
+ });
+ it('is false for an adjacent month or the same month in another year', () => {
+ expect(isThisMonth(new Date(2024, 4, 30))).toBe(false);
+ expect(isThisMonth(new Date(2023, 5, 12))).toBe(false);
+ });
+ });
+
+ describe('isLastMonth', () => {
+ it('is true for any day in the previous month (May 2024)', () => {
+ expect(isLastMonth(new Date(2024, 4, 1))).toBe(true);
+ expect(isLastMonth(new Date(2024, 4, 31))).toBe(true);
+ });
+ it('is false for the current month and the same month in another year', () => {
+ expect(isLastMonth(new Date(2024, 5, 1))).toBe(false);
+ expect(isLastMonth(new Date(2023, 4, 15))).toBe(false);
+ });
+ });
+});
+
+describe('week helpers when "now" is a Sunday (day === 0 edge case)', () => {
+ // Sunday, 16 June 2024. getDay()===0 exercises the special Monday-start
+ // ternary (`day === 0 ? -6 : 1`) in isThisWeek/isLastWeek.
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2024, 5, 16, 12, 0, 0));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('treats Sunday as the end of the current week (Jun 10 - Jun 16)', () => {
+ expect(isThisWeek(new Date(2024, 5, 10))).toBe(true); // Monday
+ expect(isThisWeek(new Date(2024, 5, 16, 8))).toBe(true); // the Sunday itself
+ expect(isThisWeek(new Date(2024, 5, 9))).toBe(false); // prev Sunday
+ expect(isThisWeek(new Date(2024, 5, 17))).toBe(false); // next Monday
+ });
+
+ it('treats the prior Mon-Sun window as last week (Jun 3 - Jun 9)', () => {
+ expect(isLastWeek(new Date(2024, 5, 3))).toBe(true);
+ expect(isLastWeek(new Date(2024, 5, 9, 12))).toBe(true);
+ expect(isLastWeek(new Date(2024, 5, 10))).toBe(false);
+ });
+});
+
+describe('getDateForSorting', () => {
+ it('uses meeting_date when sorting by meeting_date', () => {
+ const rec = { meeting_date: '2024-06-12', created_at: '2024-01-01' };
+ const result = getDateForSorting(rec, 'meeting_date');
+ expect(result.getTime()).toBe(new Date('2024-06-12').getTime());
+ });
+
+ it('uses created_at for any other sort key', () => {
+ const rec = { meeting_date: '2024-06-12', created_at: '2024-01-01' };
+ const result = getDateForSorting(rec, 'created_at');
+ expect(result.getTime()).toBe(new Date('2024-01-01').getTime());
+ });
+
+ it('returns null when the selected date field is missing', () => {
+ expect(getDateForSorting({ created_at: null }, 'created_at')).toBeNull();
+ expect(getDateForSorting({ meeting_date: null, created_at: '2024-01-01' }, 'meeting_date')).toBeNull();
+ expect(getDateForSorting({}, 'created_at')).toBeNull();
+ });
+});
diff --git a/static/js/modules/utils/formatters.test.js b/static/js/modules/utils/formatters.test.js
new file mode 100644
index 00000000..d908388c
--- /dev/null
+++ b/static/js/modules/utils/formatters.test.js
@@ -0,0 +1,219 @@
+/**
+ * Unit tests for the pure formatting helpers in formatters.js.
+ *
+ * Several helpers call `toLocaleDateString` with an undefined locale, so the
+ * exact rendered string depends on the host locale/timezone. For those we
+ * assert timezone-robust properties (presence of the year, emptiness, or
+ * pass-through of invalid input) rather than an exact string, and we use
+ * mid-month/mid-year dates so a UTC<->local shift can never cross a day,
+ * month, or year boundary.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ formatFileSize,
+ formatDisplayDate,
+ formatShortDate,
+ formatStatus,
+ getStatusClass,
+ formatTime,
+ formatDuration,
+ formatProcessingDuration,
+} from './formatters.js';
+
+describe('formatFileSize', () => {
+ it('returns "0 Bytes" for null, undefined and zero', () => {
+ expect(formatFileSize(null)).toBe('0 Bytes');
+ expect(formatFileSize(undefined)).toBe('0 Bytes');
+ expect(formatFileSize(0)).toBe('0 Bytes');
+ });
+
+ it('treats negative input as zero', () => {
+ expect(formatFileSize(-1024)).toBe('0 Bytes');
+ });
+
+ it('formats byte-range values without a decimal', () => {
+ expect(formatFileSize(500)).toBe('500 Bytes');
+ expect(formatFileSize(1023)).toBe('1023 Bytes');
+ });
+
+ it('formats kilobytes, megabytes and gigabytes', () => {
+ expect(formatFileSize(1024)).toBe('1 KB');
+ expect(formatFileSize(1536)).toBe('1.5 KB');
+ expect(formatFileSize(1048576)).toBe('1 MB');
+ expect(formatFileSize(1073741824)).toBe('1 GB');
+ expect(formatFileSize(1099511627776)).toBe('1 TB');
+ });
+
+ it('rounds to two decimal places', () => {
+ expect(formatFileSize(1234567)).toBe('1.18 MB');
+ });
+});
+
+describe('formatDisplayDate', () => {
+ it('returns an empty string for falsy input', () => {
+ expect(formatDisplayDate('')).toBe('');
+ expect(formatDisplayDate(null)).toBe('');
+ expect(formatDisplayDate(undefined)).toBe('');
+ });
+
+ it('returns the original string for unparseable input', () => {
+ expect(formatDisplayDate('not a date')).toBe('not a date');
+ });
+
+ it('returns the original string for an invalid date-only string', () => {
+ expect(formatDisplayDate('2024-13-45')).toBe('2024-13-45');
+ });
+
+ it('renders a valid date and includes the year', () => {
+ const result = formatDisplayDate('2024-06-15T12:00:00');
+ expect(typeof result).toBe('string');
+ expect(result).toContain('2024');
+ });
+
+ it('handles a date-only string', () => {
+ const result = formatDisplayDate('2024-06-15');
+ expect(result).toContain('2024');
+ });
+});
+
+describe('formatShortDate', () => {
+ it('returns an empty string for falsy input', () => {
+ expect(formatShortDate('')).toBe('');
+ expect(formatShortDate(null)).toBe('');
+ });
+
+ it('returns the original string for unparseable input', () => {
+ expect(formatShortDate('nonsense')).toBe('nonsense');
+ });
+
+ it('includes a 2-digit year for dates outside the current year', () => {
+ const result = formatShortDate('2019-06-15T12:00:00');
+ expect(result).toContain('19');
+ });
+
+ it('omits the 4-digit year for current-year dates', () => {
+ const year = new Date().getFullYear();
+ const result = formatShortDate(`${year}-06-15T12:00:00`);
+ expect(result).not.toContain(String(year));
+ expect(result.length).toBeGreaterThan(0);
+ });
+});
+
+describe('formatStatus', () => {
+ const t = (key) => key;
+
+ it('returns an empty string for falsy status or COMPLETED', () => {
+ expect(formatStatus('', t)).toBe('');
+ expect(formatStatus(null, t)).toBe('');
+ expect(formatStatus('COMPLETED', t)).toBe('');
+ });
+
+ it('maps known statuses through the translation function', () => {
+ expect(formatStatus('PENDING', t)).toBe('status.queued');
+ expect(formatStatus('QUEUED', t)).toBe('status.queued');
+ expect(formatStatus('PROCESSING', t)).toBe('status.processing');
+ expect(formatStatus('TRANSCRIBING', t)).toBe('status.transcribing');
+ expect(formatStatus('SUMMARIZING', t)).toBe('status.summarizing');
+ expect(formatStatus('FAILED', t)).toBe('status.failed');
+ expect(formatStatus('UPLOADING', t)).toBe('status.uploading');
+ });
+
+ it('title-cases unknown statuses', () => {
+ expect(formatStatus('WEIRD', t)).toBe('Weird');
+ expect(formatStatus('custom', t)).toBe('Custom');
+ });
+});
+
+describe('getStatusClass', () => {
+ it('maps each known status to its CSS class', () => {
+ expect(getStatusClass('PENDING')).toBe('status-pending');
+ expect(getStatusClass('QUEUED')).toBe('status-pending');
+ expect(getStatusClass('PROCESSING')).toBe('status-processing');
+ expect(getStatusClass('SUMMARIZING')).toBe('status-summarizing');
+ expect(getStatusClass('COMPLETED')).toBe('');
+ expect(getStatusClass('FAILED')).toBe('status-failed');
+ });
+
+ it('defaults unknown statuses to status-pending', () => {
+ expect(getStatusClass('SOMETHING')).toBe('status-pending');
+ expect(getStatusClass(undefined)).toBe('status-pending');
+ });
+});
+
+describe('formatTime', () => {
+ it('formats zero as 00:00', () => {
+ expect(formatTime(0)).toBe('00:00');
+ });
+
+ it('zero-pads minutes and seconds', () => {
+ expect(formatTime(5)).toBe('00:05');
+ expect(formatTime(65)).toBe('01:05');
+ });
+
+ it('formats whole minutes', () => {
+ expect(formatTime(600)).toBe('10:00');
+ expect(formatTime(3599)).toBe('59:59');
+ });
+
+ it('lets minutes exceed 60 (no hour rollover)', () => {
+ expect(formatTime(3661)).toBe('61:01');
+ });
+});
+
+describe('formatDuration', () => {
+ it('returns N/A for null, undefined and negative values', () => {
+ expect(formatDuration(null)).toBe('N/A');
+ expect(formatDuration(undefined)).toBe('N/A');
+ expect(formatDuration(-5)).toBe('N/A');
+ });
+
+ it('renders sub-second values with two decimals', () => {
+ expect(formatDuration(0)).toBe('0.00 seconds');
+ expect(formatDuration(0.5)).toBe('0.50 seconds');
+ });
+
+ it('renders seconds below a minute', () => {
+ expect(formatDuration(30)).toBe('30 sec');
+ expect(formatDuration(59)).toBe('59 sec');
+ });
+
+ it('rounds to the nearest whole second', () => {
+ expect(formatDuration(29.4)).toBe('29 sec');
+ expect(formatDuration(59.6)).toBe('1 min');
+ });
+
+ it('renders minutes and seconds', () => {
+ expect(formatDuration(60)).toBe('1 min');
+ expect(formatDuration(90)).toBe('1 min 30 sec');
+ });
+
+ it('renders hours and omits seconds when hours are present', () => {
+ expect(formatDuration(3600)).toBe('1 hr');
+ expect(formatDuration(3661)).toBe('1 hr 1 min');
+ expect(formatDuration(7200)).toBe('2 hr');
+ });
+});
+
+describe('formatProcessingDuration', () => {
+ it('returns null for null and undefined but not for zero', () => {
+ expect(formatProcessingDuration(null)).toBeNull();
+ expect(formatProcessingDuration(undefined)).toBeNull();
+ expect(formatProcessingDuration(0)).toBe('0s');
+ });
+
+ it('renders seconds below a minute', () => {
+ expect(formatProcessingDuration(30)).toBe('30s');
+ expect(formatProcessingDuration(59)).toBe('59s');
+ });
+
+ it('renders whole minutes without a seconds part', () => {
+ expect(formatProcessingDuration(60)).toBe('1m');
+ expect(formatProcessingDuration(120)).toBe('2m');
+ });
+
+ it('renders minutes and seconds', () => {
+ expect(formatProcessingDuration(90)).toBe('1m 30s');
+ expect(formatProcessingDuration(125)).toBe('2m 5s');
+ });
+});