From 4c4ddf741eb00d29a523be875df81a99523960ab Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 16:46:39 -0500 Subject: [PATCH] test(web): drop URL-echo and scaffold tests, merge repeated cases into tables (#8300) Client tests that only restated a function's URL, or asserted on the value their own mock returned, are gone; what those functions do beyond the URL (escaping an id, leaving out an empty note, paging) keeps a test. Repeated cases in the player store, row keyboard handling, public routes, register refusals and others are tables. The shuffle test used an rng that never swapped, so it could not fail; it now pins the order. Co-Authored-By: Claude Opus 5.5 --- web/src/lib/api/admin.cover-sources.test.ts | 103 ------- web/src/lib/api/admin.coverage.test.ts | 40 --- web/src/lib/api/admin.covers.test.ts | 33 --- web/src/lib/api/admin.duplicates.test.ts | 47 +-- web/src/lib/api/admin.fingerprints.test.ts | 62 ---- web/src/lib/api/admin.research-art.test.ts | 19 -- web/src/lib/api/admin.scan.test.ts | 28 -- web/src/lib/api/admin.tag-sources.test.ts | 84 ------ web/src/lib/api/admin.test.ts | 123 -------- web/src/lib/api/albums.test.ts | 33 --- web/src/lib/api/artists.test.ts | 23 -- web/src/lib/api/client.test.ts | 9 +- web/src/lib/api/errors.test.ts | 52 +--- web/src/lib/api/history.test.ts | 59 +--- web/src/lib/api/home.test.ts | 34 --- web/src/lib/api/likes.test.ts | 31 +- web/src/lib/api/me.test.ts | 21 -- web/src/lib/api/paging.test.ts | 48 +--- web/src/lib/api/playlists.test.ts | 75 ----- web/src/lib/api/quarantine.test.ts | 119 +------- web/src/lib/api/queries.test.ts | 40 --- web/src/lib/auth/publicRoutes.test.ts | 61 ++-- .../PlaylistPlaceholderCard.test.ts | 42 +-- .../lib/components/PlaylistTrackRow.test.ts | 20 +- web/src/lib/components/QueueTrackRow.test.ts | 36 +-- web/src/lib/components/StageBadge.test.ts | 35 +-- web/src/lib/components/TrackRow.test.ts | 10 +- web/src/lib/components/queue-row-math.test.ts | 50 ++-- web/src/lib/example.test.ts | 7 - web/src/lib/media/duration.test.ts | 41 +-- web/src/lib/player/store.test.ts | 271 ++++++------------ web/src/routes/admin/admin.test.ts | 25 +- .../routes/playlists/[id]/playlist.test.ts | 48 +--- web/src/routes/register/register.test.ts | 41 +-- .../settings/appearance/appearance.test.ts | 18 +- 35 files changed, 280 insertions(+), 1508 deletions(-) delete mode 100644 web/src/lib/api/admin.cover-sources.test.ts delete mode 100644 web/src/lib/api/admin.coverage.test.ts delete mode 100644 web/src/lib/api/admin.covers.test.ts delete mode 100644 web/src/lib/api/admin.fingerprints.test.ts delete mode 100644 web/src/lib/api/admin.research-art.test.ts delete mode 100644 web/src/lib/api/admin.scan.test.ts delete mode 100644 web/src/lib/api/admin.tag-sources.test.ts delete mode 100644 web/src/lib/api/admin.test.ts delete mode 100644 web/src/lib/api/albums.test.ts delete mode 100644 web/src/lib/api/artists.test.ts delete mode 100644 web/src/lib/api/home.test.ts delete mode 100644 web/src/lib/api/me.test.ts delete mode 100644 web/src/lib/api/playlists.test.ts delete mode 100644 web/src/lib/api/queries.test.ts delete mode 100644 web/src/lib/example.test.ts diff --git a/web/src/lib/api/admin.cover-sources.test.ts b/web/src/lib/api/admin.cover-sources.test.ts deleted file mode 100644 index 46b8f060..00000000 --- a/web/src/lib/api/admin.cover-sources.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { - getCoverProviders, - updateCoverProvider, - testCoverProvider, - type CoverProvider, - type CoverProvidersResponse -} from './admin'; - -vi.mock('./client', () => ({ - api: { get: vi.fn(), post: vi.fn(), patch: vi.fn() } -})); - -import { api } from './client'; - -describe('admin cover-sources API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('getCoverProviders GETs the correct path', async () => { - const sample: CoverProvidersResponse = { - providers: [ - { - id: 'mbcaa', - display_name: 'Cover Art Archive', - requires_api_key: false, - supports: ['album_cover'], - enabled: true, - api_key_set: false, - display_order: 0, - testable: true - } - ], - sources_version: 1 - }; - (api.get as unknown as ReturnType).mockResolvedValueOnce(sample); - const got = await getCoverProviders(); - expect(api.get).toHaveBeenCalledWith('/api/admin/cover-sources'); - expect(got.providers[0].id).toBe('mbcaa'); - expect(got.sources_version).toBe(1); - }); - - it('updateCoverProvider PATCHes the right path with patch body', async () => { - const patched: CoverProvider & { version_bumped: boolean } = { - id: 'theaudiodb', - display_name: 'TheAudioDB', - requires_api_key: true, - supports: ['album_cover', 'artist_thumb', 'artist_fanart'], - enabled: true, - api_key_set: true, - display_order: 1, - testable: true, - version_bumped: false - }; - (api.patch as unknown as ReturnType).mockResolvedValueOnce(patched); - const got = await updateCoverProvider('theaudiodb', { api_key: 'mykey' }); - expect(api.patch).toHaveBeenCalledWith( - '/api/admin/cover-sources/theaudiodb', - { api_key: 'mykey' } - ); - expect(got.api_key_set).toBe(true); - expect(got.version_bumped).toBe(false); - }); - - it('updateCoverProvider with enabled toggle returns version_bumped: true', async () => { - const patched: CoverProvider & { version_bumped: boolean } = { - id: 'theaudiodb', - display_name: 'TheAudioDB', - requires_api_key: true, - supports: ['album_cover', 'artist_thumb', 'artist_fanart'], - enabled: false, - api_key_set: false, - display_order: 1, - testable: true, - version_bumped: true - }; - (api.patch as unknown as ReturnType).mockResolvedValueOnce(patched); - const got = await updateCoverProvider('theaudiodb', { enabled: false }); - expect(got.version_bumped).toBe(true); - expect(got.enabled).toBe(false); - }); - - it('testCoverProvider POSTs to /test endpoint with empty body', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ - ok: true, - duration_ms: 234 - }); - const got = await testCoverProvider('theaudiodb'); - expect(api.post).toHaveBeenCalledWith('/api/admin/cover-sources/theaudiodb/test', {}); - expect(got.ok).toBe(true); - expect(got.duration_ms).toBe(234); - }); - - it('testCoverProvider returns ok=false with error string on failure', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ - ok: false, - duration_ms: 12, - error: 'connection refused' - }); - const got = await testCoverProvider('theaudiodb'); - expect(got.ok).toBe(false); - expect(got.error).toBe('connection refused'); - }); -}); diff --git a/web/src/lib/api/admin.coverage.test.ts b/web/src/lib/api/admin.coverage.test.ts deleted file mode 100644 index c6b5b296..00000000 --- a/web/src/lib/api/admin.coverage.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { getCoverageRollup, type CoverageRollup } from './admin'; - -vi.mock('./client', () => ({ - api: { get: vi.fn(), post: vi.fn() } -})); - -import { api } from './client'; - -describe('admin coverage API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('getCoverageRollup GETs the correct path', async () => { - const sample: CoverageRollup = { - total: 18026, - with_art: 12400, - pending: 5400, - settled: 226, - pending_no_mbid: 320 - }; - (api.get as unknown as ReturnType).mockResolvedValueOnce(sample); - const got = await getCoverageRollup(); - expect(api.get).toHaveBeenCalledWith('/api/admin/library/coverage'); - expect(got).toEqual(sample); - }); - - it('returns zeros on an empty library', async () => { - const empty: CoverageRollup = { - total: 0, - with_art: 0, - pending: 0, - settled: 0, - pending_no_mbid: 0 - }; - (api.get as unknown as ReturnType).mockResolvedValueOnce(empty); - const got = await getCoverageRollup(); - expect(got.total).toBe(0); - expect(got.with_art + got.pending + got.settled).toBe(got.total); - }); -}); diff --git a/web/src/lib/api/admin.covers.test.ts b/web/src/lib/api/admin.covers.test.ts deleted file mode 100644 index 75b2aa0e..00000000 --- a/web/src/lib/api/admin.covers.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; - -vi.mock('./client', () => ({ - api: { - get: vi.fn(), - post: vi.fn(), - put: vi.fn(), - del: vi.fn() - } -})); - -import { refetchAlbumCover, refetchMissingCovers } from './admin'; -import { api } from './client'; - -describe('admin covers API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('refetchAlbumCover POSTs to the correct path', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ - album_id: 'a1', cover_art_path: '/x.jpg', cover_art_source: 'mbcaa' - }); - const got = await refetchAlbumCover('a1'); - expect(api.post).toHaveBeenCalledWith('/api/admin/albums/a1/cover/refetch', {}); - expect(got.cover_art_source).toBe('mbcaa'); - }); - - it('refetchMissingCovers POSTs to the bulk endpoint', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ started: true }); - const got = await refetchMissingCovers(); - expect(api.post).toHaveBeenCalledWith('/api/admin/covers/refetch-missing', {}); - expect(got.started).toBe(true); - }); -}); diff --git a/web/src/lib/api/admin.duplicates.test.ts b/web/src/lib/api/admin.duplicates.test.ts index 44a53a94..8a3cb65a 100644 --- a/web/src/lib/api/admin.duplicates.test.ts +++ b/web/src/lib/api/admin.duplicates.test.ts @@ -1,12 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { - dismissDuplicateGroup, - duplicatesNextOffset, - listDuplicates, - listResolvedDuplicates, - mergeDuplicateGroup, - runDuplicateSweep -} from './admin'; +import { dismissDuplicateGroup, duplicatesNextOffset } from './admin'; import type { AdminDuplicatesResponse } from './types'; vi.mock('./client', () => ({ @@ -18,18 +11,12 @@ import { api } from './client'; describe('admin duplicates API', () => { beforeEach(() => vi.clearAllMocks()); - it('listDuplicates GETs one tab of the paged report', async () => { - (api.get as unknown as ReturnType).mockResolvedValueOnce({ groups: [] }); - await listDuplicates('cross_release', 25); - expect(api.get).toHaveBeenCalledWith( - '/api/admin/library/duplicates?view=cross_release&limit=25&offset=25' - ); - }); - - it('listResolvedDuplicates GETs what the resolver did', async () => { - (api.get as unknown as ReturnType).mockResolvedValueOnce({ items: [] }); - await listResolvedDuplicates(50); - expect(api.get).toHaveBeenCalledWith('/api/admin/library/duplicates/resolved?limit=25&offset=50'); + // A group id is the server's own string and may carry a slash; it must stay + // one path segment. + it('escapes the group id in the path', async () => { + (api.post as unknown as ReturnType).mockResolvedValueOnce(undefined); + await dismissDuplicateGroup('g/1'); + expect(api.post).toHaveBeenCalledWith('/api/admin/library/duplicates/g%2F1/dismiss', {}); }); // The next offset counts groups, and stops at the total or on an empty page. @@ -40,24 +27,4 @@ describe('admin duplicates API', () => { expect(duplicatesNextOffset(page(50, 10, 60))).toBeUndefined(); expect(duplicatesNextOffset(page(25, 0, 60))).toBeUndefined(); }); - - it('runDuplicateSweep POSTs the trigger', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ started: true }); - await runDuplicateSweep(); - expect(api.post).toHaveBeenCalledWith('/api/admin/library/duplicates/sweep', {}); - }); - - it('dismissDuplicateGroup POSTs to the group', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce(undefined); - await dismissDuplicateGroup('g/1'); - expect(api.post).toHaveBeenCalledWith('/api/admin/library/duplicates/g%2F1/dismiss', {}); - }); - - it('mergeDuplicateGroup POSTs the chosen survivor', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ removed_paths: [] }); - await mergeDuplicateGroup('g-1', { survivor_track_id: 't-1' }); - expect(api.post).toHaveBeenCalledWith('/api/admin/library/duplicates/g-1/merge', { - survivor_track_id: 't-1' - }); - }); }); diff --git a/web/src/lib/api/admin.fingerprints.test.ts b/web/src/lib/api/admin.fingerprints.test.ts deleted file mode 100644 index 9d8aa991..00000000 --- a/web/src/lib/api/admin.fingerprints.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { - getFingerprintCoverage, - getFingerprintSettings, - updateFingerprintSettings, - type FingerprintCoverage, - type FingerprintSettings -} from './admin'; - -vi.mock('./client', () => ({ - api: { get: vi.fn(), post: vi.fn(), put: vi.fn() } -})); - -import { api } from './client'; - -describe('admin fingerprint coverage API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('getFingerprintCoverage GETs the correct path', async () => { - const sample: FingerprintCoverage = { - total: 18026, - fingerprinted: 9400, - rejected: 12, - pending: 8614, - enabled: true - }; - (api.get as unknown as ReturnType).mockResolvedValueOnce(sample); - const got = await getFingerprintCoverage(); - expect(api.get).toHaveBeenCalledWith('/api/admin/library/fingerprints'); - expect(got).toEqual(sample); - }); - - it('buckets sum to the total', async () => { - const sample: FingerprintCoverage = { - total: 10, - fingerprinted: 6, - rejected: 1, - pending: 3, - enabled: true - }; - (api.get as unknown as ReturnType).mockResolvedValueOnce(sample); - const got = await getFingerprintCoverage(); - expect(got.fingerprinted + got.rejected + got.pending).toBe(got.total); - }); - - it('reads and saves the fingerprinting settings at one path', async () => { - const settings: FingerprintSettings = { - enabled: true, - chromaprint_length_sec: 120, - acoustic_max_bit_error_rate: 0.15, - backfill_concurrency: 2, - sweep_interval_hours: 1, - auto_resolve: true - }; - (api.get as unknown as ReturnType).mockResolvedValueOnce(settings); - (api.put as unknown as ReturnType).mockResolvedValueOnce(settings); - await getFingerprintSettings(); - await updateFingerprintSettings(settings); - expect(api.get).toHaveBeenCalledWith('/api/admin/library/fingerprint-settings'); - expect(api.put).toHaveBeenCalledWith('/api/admin/library/fingerprint-settings', settings); - }); -}); diff --git a/web/src/lib/api/admin.research-art.test.ts b/web/src/lib/api/admin.research-art.test.ts deleted file mode 100644 index b482700b..00000000 --- a/web/src/lib/api/admin.research-art.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { researchMissingArt } from './admin'; - -vi.mock('./client', () => ({ - api: { get: vi.fn(), post: vi.fn(), patch: vi.fn() } -})); - -import { api } from './client'; - -describe('admin research missing art API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('researchMissingArt POSTs the correct path and returns version', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ version: 7 }); - const got = await researchMissingArt(); - expect(api.post).toHaveBeenCalledWith('/api/admin/cover-sources/research', {}); - expect(got.version).toBe(7); - }); -}); diff --git a/web/src/lib/api/admin.scan.test.ts b/web/src/lib/api/admin.scan.test.ts deleted file mode 100644 index 9c9eb28f..00000000 --- a/web/src/lib/api/admin.scan.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { getScanStatus, triggerScan } from './admin'; - -vi.mock('./client', () => ({ - api: { get: vi.fn(), post: vi.fn() } -})); - -import { api } from './client'; - -describe('admin scan API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('getScanStatus GETs the correct path', async () => { - (api.get as unknown as ReturnType).mockResolvedValueOnce({ - id: 's1', started_at: '2026-05-04T00:00:00Z', finished_at: null, in_flight: true - }); - const got = await getScanStatus(); - expect(api.get).toHaveBeenCalledWith('/api/admin/scan/status'); - expect(got.in_flight).toBe(true); - }); - - it('triggerScan POSTs an empty body to /run', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ id: 's2' }); - const got = await triggerScan(); - expect(api.post).toHaveBeenCalledWith('/api/admin/scan/run', {}); - expect(got.id).toBe('s2'); - }); -}); diff --git a/web/src/lib/api/admin.tag-sources.test.ts b/web/src/lib/api/admin.tag-sources.test.ts deleted file mode 100644 index e7b9c4d2..00000000 --- a/web/src/lib/api/admin.tag-sources.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { - getTagProviders, - updateTagProvider, - testTagProvider, - type TagProvider, - type TagProvidersResponse -} from './admin'; - -vi.mock('./client', () => ({ - api: { get: vi.fn(), post: vi.fn(), patch: vi.fn() } -})); - -import { api } from './client'; - -describe('admin tag-sources API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('getTagProviders GETs the correct path', async () => { - const sample: TagProvidersResponse = { - providers: [ - { - id: 'musicbrainz', - display_name: 'MusicBrainz', - requires_api_key: false, - supports: ['track_tags'], - enabled: true, - api_key_set: false, - display_order: 0, - testable: true - } - ], - sources_version: 1 - }; - (api.get as unknown as ReturnType).mockResolvedValueOnce(sample); - const got = await getTagProviders(); - expect(api.get).toHaveBeenCalledWith('/api/admin/tag-sources'); - expect(got.providers[0].id).toBe('musicbrainz'); - expect(got.sources_version).toBe(1); - }); - - it('updateTagProvider PATCHes the right path with patch body', async () => { - const patched: TagProvider & { version_bumped: boolean } = { - id: 'lastfm', - display_name: 'Last.fm', - requires_api_key: true, - supports: ['track_tags'], - enabled: true, - api_key_set: true, - display_order: 1, - testable: true, - version_bumped: true - }; - (api.patch as unknown as ReturnType).mockResolvedValueOnce(patched); - const got = await updateTagProvider('lastfm', { enabled: true, api_key: 'mykey' }); - expect(api.patch).toHaveBeenCalledWith( - '/api/admin/tag-sources/lastfm', - { enabled: true, api_key: 'mykey' } - ); - expect(got.api_key_set).toBe(true); - expect(got.version_bumped).toBe(true); - }); - - it('testTagProvider POSTs to /test endpoint with empty body', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ - ok: true, - duration_ms: 55 - }); - const got = await testTagProvider('musicbrainz'); - expect(api.post).toHaveBeenCalledWith('/api/admin/tag-sources/musicbrainz/test', {}); - expect(got.ok).toBe(true); - expect(got.duration_ms).toBe(55); - }); - - it('testTagProvider returns ok=false with error string on failure', async () => { - (api.post as unknown as ReturnType).mockResolvedValueOnce({ - ok: false, - error: 'lastfm api key not set' - }); - const got = await testTagProvider('lastfm'); - expect(got.ok).toBe(false); - expect(got.error).toBe('lastfm api key not set'); - }); -}); diff --git a/web/src/lib/api/admin.test.ts b/web/src/lib/api/admin.test.ts deleted file mode 100644 index 8681b4f8..00000000 --- a/web/src/lib/api/admin.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, expect, test, vi, beforeEach } from 'vitest'; - -vi.mock('./client', () => ({ - api: { - get: vi.fn(), - post: vi.fn(), - put: vi.fn(), - del: vi.fn() - } -})); - -import { - listAdminQuarantine, - resolveQuarantine, - deleteQuarantineFile, - listQuarantineActions -} from './admin'; -import { api } from './client'; -import { qk } from './queries'; -import type { - ActionResult, - AdminQuarantineRow, - QuarantineActionRow -} from './types'; - -beforeEach(() => { - vi.clearAllMocks(); -}); - -const baseQuarantineRow: AdminQuarantineRow = { - track_id: 't1', - track_title: 'Juin 21st', - artist_name: 'Apex Sibling', - album_title: 'Drumkits', - album_id: 'alb1', - report_count: 1, - latest_at: '2026-01-01T00:00:00Z', - reason_counts: { bad_rip: 1 }, - reports: [] -}; - -const baseAction: ActionResult = { - action_id: 'a1', - affected_users: 1 -}; - -const baseActionRow: QuarantineActionRow = { - id: 'a1', - track_id: 't1', - track_title: 'Juin 21st', - artist_name: 'Apex Sibling', - album_title: 'Drumkits', - action: 'resolved', - admin_id: 'admin1', - affected_users: 1, - created_at: '2026-01-01T00:00:00Z' -}; - -describe('listAdminQuarantine', () => { - test('GETs /api/admin/quarantine', async () => { - (api.get as ReturnType).mockResolvedValueOnce([baseQuarantineRow]); - const out = await listAdminQuarantine(); - expect(api.get).toHaveBeenCalledWith('/api/admin/quarantine'); - expect(out).toEqual([baseQuarantineRow]); - }); -}); - -describe('resolveQuarantine', () => { - test('POSTs /api/admin/quarantine/:trackID/resolve with empty body', async () => { - (api.post as ReturnType).mockResolvedValueOnce(baseAction); - const out = await resolveQuarantine('t1'); - expect(api.post).toHaveBeenCalledWith('/api/admin/quarantine/t1/resolve', {}); - expect(out).toBe(baseAction); - }); -}); - -describe('deleteQuarantineFile', () => { - test('POSTs /api/admin/quarantine/:trackID/delete-file with empty body', async () => { - (api.post as ReturnType).mockResolvedValueOnce(baseAction); - const out = await deleteQuarantineFile('t1'); - expect(api.post).toHaveBeenCalledWith( - '/api/admin/quarantine/t1/delete-file', - {} - ); - expect(out).toBe(baseAction); - }); -}); - -describe('listQuarantineActions', () => { - test('defaults to limit=50 when no argument', async () => { - (api.get as ReturnType).mockResolvedValueOnce([baseActionRow]); - await listQuarantineActions(); - expect(api.get).toHaveBeenCalledWith( - '/api/admin/quarantine/actions?limit=50' - ); - }); - - test('forwards explicit limit', async () => { - (api.get as ReturnType).mockResolvedValueOnce([baseActionRow]); - await listQuarantineActions(10); - expect(api.get).toHaveBeenCalledWith( - '/api/admin/quarantine/actions?limit=10' - ); - }); -}); - -describe('qk admin quarantine keys', () => { - test('adminQuarantine key', () => { - expect(qk.adminQuarantine()).toEqual(['adminQuarantine']); - }); - test('adminQuarantineActions key defaults to limit 50', () => { - expect(qk.adminQuarantineActions()).toEqual([ - 'adminQuarantineActions', - { limit: 50 } - ]); - }); - test('adminQuarantineActions key reflects custom limit', () => { - expect(qk.adminQuarantineActions(25)).toEqual([ - 'adminQuarantineActions', - { limit: 25 } - ]); - }); -}); diff --git a/web/src/lib/api/albums.test.ts b/web/src/lib/api/albums.test.ts deleted file mode 100644 index b5dbef43..00000000 --- a/web/src/lib/api/albums.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; - -vi.mock('./client', () => ({ - api: { get: vi.fn() } -})); - -import { listAlbumsAlpha } from './albums'; -import { qk } from './queries'; -import { api } from './client'; - -afterEach(() => vi.clearAllMocks()); - -describe('albums client', () => { - test('listAlbumsAlpha hits /api/library/albums with paging', async () => { - (api.get as ReturnType).mockResolvedValueOnce({ - items: [], total: 0, limit: 50, offset: 0 - }); - await listAlbumsAlpha(50, 0); - expect(api.get).toHaveBeenCalledWith('/api/library/albums?limit=50&offset=0'); - }); - - test('listAlbumsAlpha honors custom limit and offset', async () => { - (api.get as ReturnType).mockResolvedValueOnce({ - items: [], total: 0, limit: 25, offset: 100 - }); - await listAlbumsAlpha(25, 100); - expect(api.get).toHaveBeenCalledWith('/api/library/albums?limit=25&offset=100'); - }); - - test('qk.albumsAlpha key is stable', () => { - expect(qk.albumsAlpha()).toEqual(['albumsAlpha']); - }); -}); diff --git a/web/src/lib/api/artists.test.ts b/web/src/lib/api/artists.test.ts deleted file mode 100644 index a2eba5b0..00000000 --- a/web/src/lib/api/artists.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; - -vi.mock('./client', () => ({ - api: { get: vi.fn() } -})); - -import { listArtistTracks } from './artists'; -import { qk } from './queries'; -import { api } from './client'; - -afterEach(() => vi.clearAllMocks()); - -describe('artists client', () => { - test('listArtistTracks hits /api/artists/:id/tracks', async () => { - (api.get as ReturnType).mockResolvedValueOnce([]); - await listArtistTracks('art-1'); - expect(api.get).toHaveBeenCalledWith('/api/artists/art-1/tracks'); - }); - - test('qk.artistTracks key includes the artist id', () => { - expect(qk.artistTracks('art-1')).toEqual(['artistTracks', 'art-1']); - }); -}); diff --git a/web/src/lib/api/client.test.ts b/web/src/lib/api/client.test.ts index d65bedcf..9f05ce59 100644 --- a/web/src/lib/api/client.test.ts +++ b/web/src/lib/api/client.test.ts @@ -56,14 +56,7 @@ describe('apiFetch', () => { }); }); -describe('api.get/post/del', () => { - test('api.get returns typed JSON on 200', async () => { - stubFetch(200, { id: 'abc', name: 'A' }); - type T = { id: string; name: string }; - const result = await api.get('/api/artists/abc'); - expect(result).toEqual({ id: 'abc', name: 'A' }); - }); - +describe('api.post/del', () => { test('api.post serializes body and sets method', async () => { const spy = stubFetch(200, { ok: true }); await api.post('/api/auth/login', { username: 'u', password: 'p' }); diff --git a/web/src/lib/api/errors.test.ts b/web/src/lib/api/errors.test.ts index 2cc04b6f..68333bfc 100644 --- a/web/src/lib/api/errors.test.ts +++ b/web/src/lib/api/errors.test.ts @@ -3,50 +3,22 @@ import { errCode, errMessage } from './errors'; import { ERROR_COPY } from './error-copy'; describe('errCode', () => { - test('returns code from object', () => { - expect(errCode({ code: 'foo' })).toBe('foo'); - }); - - test("returns 'unknown' for null", () => { - expect(errCode(null)).toBe('unknown'); - }); - - test("returns 'unknown' for undefined", () => { - expect(errCode(undefined)).toBe('unknown'); - }); - - test("returns 'unknown' for non-object values", () => { - expect(errCode('boom')).toBe('unknown'); - expect(errCode(42)).toBe('unknown'); - expect(errCode(true)).toBe('unknown'); - }); - - test('handles missing code field', () => { - expect(errCode({})).toBe('unknown'); - expect(errCode({ message: 'hi' })).toBe('unknown'); + test.each([ + ['an error with a code', { code: 'foo' }, 'foo'], + ['null', null, 'unknown'], + ['undefined', undefined, 'unknown'], + ['a string', 'boom', 'unknown'], + ['a number', 42, 'unknown'], + ['an object with no code', { message: 'hi' }, 'unknown'] + ])('%s', (_label, err, want) => { + expect(errCode(err)).toBe(want); }); }); describe('errMessage', () => { - test('returns mapped copy when code is known', () => { - const expected = ERROR_COPY.track_not_found; - expect(errMessage({ code: 'track_not_found' })).toBe(expected); - }); - - test('returns the unknown-fallback copy when code is missing', () => { - const result = errMessage({ code: 'definitely_not_a_real_code_xyz' }); - expect(result).toBeTruthy(); - expect(typeof result).toBe('string'); - expect(result.length).toBeGreaterThan(0); - }); - - test('accepts custom fallback parameter without throwing', () => { - // copyForCode itself returns a non-empty string for any input, so the - // explicit fallback only matters in narrow cases. Just exercise the - // signature. - const result = errMessage(null, 'custom fallback'); - expect(typeof result).toBe('string'); - expect(result.length).toBeGreaterThan(0); + test('a known code reads as its copy, and an unknown one as the general copy', () => { + expect(errMessage({ code: 'track_not_found' })).toBe(ERROR_COPY.track_not_found); + expect(errMessage({ code: 'definitely_not_a_real_code_xyz' })).toBe(ERROR_COPY.unknown); }); }); diff --git a/web/src/lib/api/history.test.ts b/web/src/lib/api/history.test.ts index 47fabccf..c12dc16e 100644 --- a/web/src/lib/api/history.test.ts +++ b/web/src/lib/api/history.test.ts @@ -1,52 +1,13 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { - fetchHistoryPage, - getNextPageParam, - HISTORY_PAGE_SIZE, - type HistoryResponse -} from './history'; +import { describe, it, expect } from 'vitest'; +import { getNextPageParam, type HistoryResponse } from './history'; -vi.mock('./client', () => ({ - api: { - get: vi.fn() - } -})); - -import { api } from './client'; - -describe('history API helpers', () => { - beforeEach(() => { - vi.mocked(api.get).mockReset(); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('HISTORY_PAGE_SIZE is 50', () => { - expect(HISTORY_PAGE_SIZE).toBe(50); - }); - - it('fetchHistoryPage hits /api/me/history?offset=N&limit=50', async () => { - vi.mocked(api.get).mockResolvedValue({ events: [], has_more: false }); - await fetchHistoryPage(50); - expect(api.get).toHaveBeenCalledWith('/api/me/history?offset=50&limit=50'); - }); - - it('fetchHistoryPage uses offset=0 by default', async () => { - vi.mocked(api.get).mockResolvedValue({ events: [], has_more: false }); - await fetchHistoryPage(); - expect(api.get).toHaveBeenCalledWith('/api/me/history?offset=0&limit=50'); - }); - - it('getNextPageParam returns next offset when has_more is true', () => { - const page: HistoryResponse = { events: [], has_more: true }; - expect(getNextPageParam(page, [], 0)).toBe(50); - expect(getNextPageParam(page, [], 50)).toBe(100); - }); - - it('getNextPageParam returns undefined when has_more is false', () => { - const page: HistoryResponse = { events: [], has_more: false }; - expect(getNextPageParam(page, [], 50)).toBeUndefined(); +describe('history paging', () => { + // The server says whether more remain; the next offset is one page on. + it('asks for the next page only while the server has more', () => { + const more: HistoryResponse = { events: [], has_more: true }; + const done: HistoryResponse = { events: [], has_more: false }; + expect(getNextPageParam(more, [], 0)).toBe(50); + expect(getNextPageParam(more, [], 50)).toBe(100); + expect(getNextPageParam(done, [], 50)).toBeUndefined(); }); }); diff --git a/web/src/lib/api/home.test.ts b/web/src/lib/api/home.test.ts deleted file mode 100644 index 354cefd9..00000000 --- a/web/src/lib/api/home.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; - -vi.mock('./client', () => ({ - api: { get: vi.fn() } -})); - -import { listHome } from './home'; -import { qk } from './queries'; -import { api } from './client'; -import type { HomePayload } from './types'; - -afterEach(() => vi.clearAllMocks()); - -describe('home client', () => { - test('listHome hits /api/home', async () => { - const fixture: HomePayload = { - recently_added_albums: [], - rediscover_albums: [], - rediscover_artists: [], - most_played_tracks: [], - last_played_artists: [], - you_might_like_albums: [], - you_might_like_artists: [] - }; - (api.get as ReturnType).mockResolvedValueOnce(fixture); - const got = await listHome(); - expect(api.get).toHaveBeenCalledWith('/api/home'); - expect(got).toEqual(fixture); - }); - - test('qk.home key is stable', () => { - expect(qk.home()).toEqual(['home']); - }); -}); diff --git a/web/src/lib/api/likes.test.ts b/web/src/lib/api/likes.test.ts index 333776bd..395b61f8 100644 --- a/web/src/lib/api/likes.test.ts +++ b/web/src/lib/api/likes.test.ts @@ -28,28 +28,15 @@ beforeEach(() => { afterEach(() => client.clear()); describe('likes mutations', () => { - test('likeEntity track adds id to track_ids in cache (optimistic)', async () => { - await likeEntity(client, 'track', 't2'); - const cached = client.getQueryData(qk.likedIds()) as - | { track_ids: string[] } | undefined; - expect(cached?.track_ids).toContain('t2'); - expect(api.post).toHaveBeenCalledWith('/api/likes/tracks/t2', undefined); - }); - - test('likeEntity album hits albums endpoint and adds to album_ids', async () => { - await likeEntity(client, 'album', 'al1'); - const cached = client.getQueryData(qk.likedIds()) as - | { album_ids: string[] } | undefined; - expect(cached?.album_ids).toContain('al1'); - expect(api.post).toHaveBeenCalledWith('/api/likes/albums/al1', undefined); - }); - - test('likeEntity artist adds to artist_ids', async () => { - await likeEntity(client, 'artist', 'ar1'); - const cached = client.getQueryData(qk.likedIds()) as - | { artist_ids: string[] } | undefined; - expect(cached?.artist_ids).toContain('ar1'); - expect(api.post).toHaveBeenCalledWith('/api/likes/artists/ar1', undefined); + test.each([ + ['track', 't2', 'tracks', 'track_ids'], + ['album', 'al1', 'albums', 'album_ids'], + ['artist', 'ar1', 'artists', 'artist_ids'] + ] as const)('liking a %s posts it and adds it to the cache at once', async (kind, id, path, field) => { + await likeEntity(client, kind, id); + const cached = client.getQueryData(qk.likedIds()) as Record | undefined; + expect(cached?.[field]).toContain(id); + expect(api.post).toHaveBeenCalledWith(`/api/likes/${path}/${id}`, undefined); }); test('unlikeEntity removes id from cache', async () => { diff --git a/web/src/lib/api/me.test.ts b/web/src/lib/api/me.test.ts deleted file mode 100644 index e37eacb5..00000000 --- a/web/src/lib/api/me.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { getSystemPlaylistsStatus } from './me'; - -vi.mock('./client', () => ({ - api: { get: vi.fn() } -})); - -import { api } from './client'; - -describe('me API', () => { - beforeEach(() => vi.clearAllMocks()); - - it('getSystemPlaylistsStatus GETs the correct path', async () => { - (api.get as unknown as ReturnType).mockResolvedValueOnce({ - in_flight: false, last_run_at: null, last_error: null - }); - const got = await getSystemPlaylistsStatus(); - expect(api.get).toHaveBeenCalledWith('/api/me/system-playlists-status'); - expect(got.in_flight).toBe(false); - }); -}); diff --git a/web/src/lib/api/paging.test.ts b/web/src/lib/api/paging.test.ts index a8afe9d1..e9ee88db 100644 --- a/web/src/lib/api/paging.test.ts +++ b/web/src/lib/api/paging.test.ts @@ -2,44 +2,16 @@ import { describe, it, expect } from 'vitest'; import { pageGetNextPageParam } from './paging'; import type { Page } from './types'; -function mkPage(items: T[], offset: number, total: number, limit = 50): Page { - return { items, offset, total, limit }; -} - +// The next offset is where this page ended, until that reaches the total. describe('pageGetNextPageParam', () => { - it('returns next offset (offset + items.length) when more items remain', () => { - const next = pageGetNextPageParam(); - const last = mkPage([1, 2, 3, 4, 5], 0, 12); - expect(next(last)).toBe(5); - }); - - it('returns next offset accounting for prior offset', () => { - const next = pageGetNextPageParam(); - const last = mkPage([1, 2, 3], 50, 100); - expect(next(last)).toBe(53); - }); - - it('returns undefined when loaded reaches total', () => { - const next = pageGetNextPageParam(); - const last = mkPage([1, 2, 3], 7, 10); - expect(next(last)).toBeUndefined(); - }); - - it('returns undefined when last page is empty and offset already equals total', () => { - const next = pageGetNextPageParam(); - const last = mkPage([], 10, 10); - expect(next(last)).toBeUndefined(); - }); - - it('returns undefined when loaded exceeds total (defensive)', () => { - const next = pageGetNextPageParam(); - const last = mkPage([1, 2, 3], 9, 10); - expect(next(last)).toBeUndefined(); - }); - - it('works for different element types via generic parameter', () => { - const next = pageGetNextPageParam(); - const last = mkPage(['a', 'b'], 0, 5); - expect(next(last)).toBe(2); + it.each([ + ['more remain', 0, 5, 12, 5], + ['more remain after an earlier offset', 50, 3, 100, 53], + ['this page reaches the total', 7, 3, 10, undefined], + ['an empty last page at the total', 10, 0, 10, undefined], + ['a page that overshoots the total', 9, 3, 10, undefined] + ])('%s', (_label, offset, n, total, want) => { + const page: Page = { items: Array.from({ length: n }, (_, i) => i), offset, total, limit: 50 }; + expect(pageGetNextPageParam()(page)).toBe(want); }); }); diff --git a/web/src/lib/api/playlists.test.ts b/web/src/lib/api/playlists.test.ts deleted file mode 100644 index 7727c8f4..00000000 --- a/web/src/lib/api/playlists.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { - listPlaylists, - getPlaylist, - createPlaylist, - reorderPlaylist, - removePlaylistTrack -} from './playlists'; - -function stubFetch(status: number, body: unknown, init: Partial = {}) { - const res = new Response( - body === null ? null : JSON.stringify(body), - { status, headers: { 'Content-Type': 'application/json' }, ...init } - ); - const spy = vi.fn().mockResolvedValue(res); - vi.stubGlobal('fetch', spy); - return spy; -} - -afterEach(() => { - vi.unstubAllGlobals(); -}); - -describe('playlists API helper', () => { - test('listPlaylists GETs /api/playlists with default kind=user', async () => { - const spy = stubFetch(200, { owned: [], public: [] }); - const r = await listPlaylists(); - expect(r.owned).toEqual([]); - expect(r.public).toEqual([]); - const call = spy.mock.calls[0]; - expect(call[0]).toBe('/api/playlists?kind=user'); - // GET is fetch's default method; api.get omits init.method entirely. - expect((call[1] as RequestInit | undefined)?.method ?? 'GET').toBe('GET'); - }); - - test('listPlaylists passes kind=system through the query string', async () => { - const spy = stubFetch(200, { owned: [], public: [] }); - await listPlaylists('system'); - const call = spy.mock.calls[0]; - expect(call[0]).toBe('/api/playlists?kind=system'); - }); - - test('createPlaylist POSTs JSON body', async () => { - const spy = stubFetch(200, { id: 'p1', name: 'Test' }); - const r = await createPlaylist({ name: 'Test' }); - expect(r.id).toBe('p1'); - const call = spy.mock.calls[0]; - expect((call[1] as RequestInit).method).toBe('POST'); - expect(JSON.parse((call[1] as RequestInit).body as string)).toEqual({ name: 'Test' }); - }); - - test('reorderPlaylist PUTs ordered_positions', async () => { - const spy = stubFetch(200, { id: 'p1', tracks: [] }); - await reorderPlaylist('p1', [2, 1, 0]); - const call = spy.mock.calls[0]; - expect(call[0]).toBe('/api/playlists/p1/tracks'); - expect((call[1] as RequestInit).method).toBe('PUT'); - expect(JSON.parse((call[1] as RequestInit).body as string)).toEqual({ - ordered_positions: [2, 1, 0] - }); - }); - - test('removePlaylistTrack DELETEs by position', async () => { - const spy = stubFetch(200, { id: 'p1', tracks: [] }); - await removePlaylistTrack('p1', 3); - const call = spy.mock.calls[0]; - expect(call[0]).toBe('/api/playlists/p1/tracks/3'); - expect((call[1] as RequestInit).method).toBe('DELETE'); - }); - - test('not_found surfaces as ApiError', async () => { - stubFetch(404, { error: { code: 'not_found', message: 'not found' } }); - await expect(getPlaylist('missing')).rejects.toMatchObject({ code: 'not_found' }); - }); -}); diff --git a/web/src/lib/api/quarantine.test.ts b/web/src/lib/api/quarantine.test.ts index 6d05dd71..62e7ce83 100644 --- a/web/src/lib/api/quarantine.test.ts +++ b/web/src/lib/api/quarantine.test.ts @@ -1,116 +1,27 @@ -import { describe, expect, test, vi, beforeEach, afterEach } from 'vitest'; +import { describe, expect, test, vi, beforeEach } from 'vitest'; vi.mock('./client', () => ({ - api: { - get: vi.fn(), - post: vi.fn(), - put: vi.fn(), - del: vi.fn() - }, - apiFetch: vi.fn() + api: { post: vi.fn() } })); -import { flagTrack, unflagTrack, listMyQuarantine } from './quarantine'; -import { api, apiFetch } from './client'; -import { qk } from './queries'; -import type { - QuarantineRow, - QuarantineMineRow -} from './types'; - -const mockRow: QuarantineRow = { - user_id: 'u1', - track_id: 't1', - reason: 'bad_rip', - notes: null, - created_at: '2026-01-01T00:00:00Z' -}; - -const mockMineRow: QuarantineMineRow = { - track_id: 't1', - reason: 'bad_rip', - notes: null, - created_at: '2026-01-01T00:00:00Z', - track_title: 'Juin 21st', - track_duration_ms: 120000, - album_id: 'alb1', - album_title: 'Drumkits', - album_cover_art_path: null, - artist_id: 'art1', - artist_name: 'Apex Sibling' -}; +import { flagTrack } from './quarantine'; +import { api } from './client'; beforeEach(() => { vi.clearAllMocks(); }); -afterEach(() => { - vi.clearAllMocks(); -}); - +// Notes go only when the listener wrote some: an empty string is the same as +// none, so the server never stores a blank note. describe('flagTrack', () => { - test('POSTs /api/quarantine without notes when none provided', async () => { - (api.post as ReturnType).mockResolvedValueOnce(mockRow); - const out = await flagTrack({ track_id: 't1', reason: 'bad_rip' }); - expect(api.post).toHaveBeenCalledWith('/api/quarantine', { - track_id: 't1', - reason: 'bad_rip' - }); - const body = (api.post as ReturnType).mock.calls[0][1] as Record< - string, - unknown - >; - expect(body).not.toHaveProperty('notes'); - expect(out).toBe(mockRow); - }); - - test('omits empty-string notes from the body', async () => { - (api.post as ReturnType).mockResolvedValueOnce(mockRow); - await flagTrack({ track_id: 't1', reason: 'wrong_tags', notes: '' }); - const body = (api.post as ReturnType).mock.calls[0][1] as Record< - string, - unknown - >; - expect(body).toEqual({ track_id: 't1', reason: 'wrong_tags' }); - expect(body).not.toHaveProperty('notes'); - }); - - test('includes notes when a non-empty string is provided', async () => { - (api.post as ReturnType).mockResolvedValueOnce(mockRow); - await flagTrack({ - track_id: 't1', - reason: 'duplicate', - notes: 'same as t0' - }); - expect(api.post).toHaveBeenCalledWith('/api/quarantine', { - track_id: 't1', - reason: 'duplicate', - notes: 'same as t0' - }); - }); -}); - -describe('unflagTrack', () => { - test('DELETEs /api/quarantine/:trackID', async () => { - (apiFetch as ReturnType).mockResolvedValueOnce(null); - await unflagTrack('t1'); - expect(apiFetch).toHaveBeenCalledWith('/api/quarantine/t1', { - method: 'DELETE' - }); - }); -}); - -describe('listMyQuarantine', () => { - test('GETs /api/quarantine/mine', async () => { - (api.get as ReturnType).mockResolvedValueOnce([mockMineRow]); - const out = await listMyQuarantine(); - expect(api.get).toHaveBeenCalledWith('/api/quarantine/mine'); - expect(out).toEqual([mockMineRow]); - }); -}); - -describe('qk.myQuarantine', () => { - test('returns the expected key tuple', () => { - expect(qk.myQuarantine()).toEqual(['myQuarantine']); + test.each([ + ['no notes', undefined, { track_id: 't1', reason: 'bad_rip' }], + ['empty notes', '', { track_id: 't1', reason: 'bad_rip' }], + ['written notes', 'same as t0', { track_id: 't1', reason: 'bad_rip', notes: 'same as t0' }] + ])('%s', async (_label, notes, body) => { + (api.post as ReturnType).mockResolvedValueOnce({}); + await flagTrack({ track_id: 't1', reason: 'bad_rip', notes }); + expect(api.post).toHaveBeenCalledWith('/api/quarantine', body); + expect((api.post as ReturnType).mock.calls[0][1]).toStrictEqual(body); }); }); diff --git a/web/src/lib/api/queries.test.ts b/web/src/lib/api/queries.test.ts deleted file mode 100644 index e55b68f7..00000000 --- a/web/src/lib/api/queries.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { qk } from './queries'; - -describe('qk key generators', () => { - test('artists key includes sort discriminator', () => { - expect(qk.artists('alpha')).toEqual(['artists', { sort: 'alpha' }]); - expect(qk.artists('newest')).toEqual(['artists', { sort: 'newest' }]); - }); - - test('artist key tuple', () => { - expect(qk.artist('abc')).toEqual(['artist', 'abc']); - }); - - test('album key tuple', () => { - expect(qk.album('xyz')).toEqual(['album', 'xyz']); - }); -}); - -describe('qk search keys', () => { - test('search summary key includes q', () => { - expect(qk.search('foo')).toEqual(['search', { q: 'foo' }]); - }); - test('searchArtists key includes q', () => { - expect(qk.searchArtists('foo')).toEqual(['searchArtists', { q: 'foo' }]); - }); - test('searchAlbums key includes q', () => { - expect(qk.searchAlbums('foo')).toEqual(['searchAlbums', { q: 'foo' }]); - }); - test('searchTracks key includes q', () => { - expect(qk.searchTracks('foo')).toEqual(['searchTracks', { q: 'foo' }]); - }); -}); - -describe('qk M6a keys', () => { - test('M6a query keys are stable', () => { - expect(qk.home()).toEqual(['home']); - expect(qk.albumsAlpha()).toEqual(['albumsAlpha']); - expect(qk.artistTracks('a1')).toEqual(['artistTracks', 'a1']); - }); -}); diff --git a/web/src/lib/auth/publicRoutes.test.ts b/web/src/lib/auth/publicRoutes.test.ts index 4a14ad03..e5adf7af 100644 --- a/web/src/lib/auth/publicRoutes.test.ts +++ b/web/src/lib/auth/publicRoutes.test.ts @@ -1,49 +1,24 @@ import { describe, expect, test } from 'vitest'; import { isPublicRoute } from './publicRoutes'; +// The pages a signed-out visitor can reach. /register must stay public: an +// invite link lands there, and so does the first account of a new server. +// The reset flow is entered from an email link while signed out, so only the +// /reset-password/ sub-path is public, not /reset-password itself. describe('isPublicRoute', () => { - test('/login is public — login form must render to unauthenticated visitors', () => { - expect(isPublicRoute('/login')).toBe(true); - }); - - // /register must stay public: bounced to /login by the layout guard, the - // bootstrap admin of a fresh deployment could not register. Do NOT remove - // /register from the public set unless you have a deliberate replacement - // (e.g. invite-only landing page). - test('/register is public — bootstrap admin must reach the form', () => { - expect(isPublicRoute('/register')).toBe(true); - }); - - test('/ is gated', () => { - expect(isPublicRoute('/')).toBe(false); - }); - - test('/admin/users is gated', () => { - expect(isPublicRoute('/admin/users')).toBe(false); - }); - - test('/settings is gated', () => { - expect(isPublicRoute('/settings')).toBe(false); - }); - - test('paths that merely start with /login are not public', () => { - expect(isPublicRoute('/login/extra')).toBe(false); - expect(isPublicRoute('/loginx')).toBe(false); - }); - - // /forgot-password and the /reset-password/ deep links must be - // reachable without a session — the reset flow is entered by clicking - // an email link while signed out. - test('/forgot-password is public', () => { - expect(isPublicRoute('/forgot-password')).toBe(true); - }); - - test('/reset-password/ is public', () => { - expect(isPublicRoute('/reset-password/abc-123')).toBe(true); - expect(isPublicRoute('/reset-password/')).toBe(true); - }); - - test('/reset-password (no trailing slash) is NOT public — only the token sub-path', () => { - expect(isPublicRoute('/reset-password')).toBe(false); + test.each([ + ['/login', true], + ['/register', true], + ['/forgot-password', true], + ['/reset-password/abc-123', true], + ['/reset-password/', true], + ['/reset-password', false], + ['/login/extra', false], + ['/loginx', false], + ['/', false], + ['/admin/users', false], + ['/settings', false] + ])('%s → %s', (path, want) => { + expect(isPublicRoute(path)).toBe(want); }); }); diff --git a/web/src/lib/components/PlaylistPlaceholderCard.test.ts b/web/src/lib/components/PlaylistPlaceholderCard.test.ts index 1d92a4cb..b0c7ec9f 100644 --- a/web/src/lib/components/PlaylistPlaceholderCard.test.ts +++ b/web/src/lib/components/PlaylistPlaceholderCard.test.ts @@ -2,35 +2,21 @@ import { describe, test, expect } from 'vitest'; import { render, screen } from '@testing-library/svelte'; import PlaylistPlaceholderCard from './PlaylistPlaceholderCard.svelte'; +// A placeholder names the mix and says why it is not there yet. It pulses +// while the mix is still coming, and not once it has failed or needs more +// listening. describe('PlaylistPlaceholderCard', () => { - test('renders label', () => { - render(PlaylistPlaceholderCard, { props: { label: 'For You', variant: 'pending' } }); + test.each([ + ['pending', undefined, /within 24h/i, true], + ['building', 'building', /Building your daily mix/i, true], + ['failed', 'failed', /Couldn.t build this mix/i, false], + ['seed-needed', 'seed-needed', /Listen to more variety/i, false] + ] as const)('%s', (shown, variant, copy, pulses) => { + const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You', variant } }); expect(screen.getByText('For You')).toBeInTheDocument(); - }); - - test('building variant shows building copy and pulses', () => { - const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You', variant: 'building' } }); - expect(screen.getByText(/Building your daily mix/i)).toBeInTheDocument(); - const cover = container.querySelector('[data-variant="building"] .aspect-square'); - expect(cover?.className).toMatch(/animate-pulse/); - }); - - test('failed variant shows failure copy and does NOT pulse', () => { - const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You', variant: 'failed' } }); - expect(screen.getByText(/Couldn.t build this mix/i)).toBeInTheDocument(); - const cover = container.querySelector('[data-variant="failed"] .aspect-square'); - expect(cover?.className).not.toMatch(/animate-pulse/); - }); - - test('seed-needed variant shows variety copy', () => { - render(PlaylistPlaceholderCard, { props: { label: 'Songs like…', variant: 'seed-needed' } }); - expect(screen.getByText(/Listen to more variety/i)).toBeInTheDocument(); - }); - - test('pending variant (default) shows within-24h copy and pulses', () => { - const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You' } }); - expect(screen.getByText(/within 24h/i)).toBeInTheDocument(); - const cover = container.querySelector('[data-variant="pending"] .aspect-square'); - expect(cover?.className).toMatch(/animate-pulse/); + expect(screen.getByText(copy)).toBeInTheDocument(); + const cover = container.querySelector(`[data-variant="${shown}"] .aspect-square`); + expect(cover).not.toBeNull(); + expect(/animate-pulse/.test(cover!.className)).toBe(pulses); }); }); diff --git a/web/src/lib/components/PlaylistTrackRow.test.ts b/web/src/lib/components/PlaylistTrackRow.test.ts index 5cc993fc..8f9e7c27 100644 --- a/web/src/lib/components/PlaylistTrackRow.test.ts +++ b/web/src/lib/components/PlaylistTrackRow.test.ts @@ -93,24 +93,16 @@ describe('PlaylistTrackRow', () => { ).not.toBeInTheDocument(); }); - test('ArrowDown on the reorder handle calls onMove(pos, pos+1)', async () => { + test.each([ + ['ArrowDown', 3], + ['ArrowUp', 1] + ])('%s on the reorder handle moves the row one place', async (key, to) => { const onMove = vi.fn(); render(PlaylistTrackRow, { props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn(), onMove } }); - const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: 'ArrowDown' }); - expect(onMove).toHaveBeenCalledWith(2, 3); - }); - - test('ArrowUp on the reorder handle calls onMove(pos, pos-1)', async () => { - const onMove = vi.fn(); - render(PlaylistTrackRow, { - props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn(), onMove } - }); - const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: 'ArrowUp' }); - expect(onMove).toHaveBeenCalledWith(2, 1); + await fireEvent.keyDown(screen.getByLabelText(/reorder track/i), { key }); + expect(onMove).toHaveBeenCalledWith(2, to); }); test('greyed-out + strikethrough when track_id is null', () => { diff --git a/web/src/lib/components/QueueTrackRow.test.ts b/web/src/lib/components/QueueTrackRow.test.ts index 17b7f77e..c27d690d 100644 --- a/web/src/lib/components/QueueTrackRow.test.ts +++ b/web/src/lib/components/QueueTrackRow.test.ts @@ -67,32 +67,20 @@ describe('QueueTrackRow', () => { expect(playFromQueueIndex).not.toHaveBeenCalled(); }); - it('ArrowDown on the drag handle calls moveQueueItem with index+1', async () => { + // The arrows move the row one place. Enter and Space move nothing, and are + // held so Space doesn't scroll the queue. + it.each([ + ['ArrowDown', [3, 4]], + ['ArrowUp', [3, 2]], + ['Enter', null], + [' ', null] + ] as const)('%s on the drag handle', async (key, move) => { render(QueueTrackRow, { props: { track: sampleTrack, index: 3, isCurrent: false } }); const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: 'ArrowDown' }); - expect(moveQueueItem).toHaveBeenCalledWith(3, 4); - }); - - it('ArrowUp on the drag handle calls moveQueueItem with index-1', async () => { - render(QueueTrackRow, { props: { track: sampleTrack, index: 3, isCurrent: false } }); - const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: 'ArrowUp' }); - expect(moveQueueItem).toHaveBeenCalledWith(3, 2); - }); - - it('Enter on the drag handle prevents default but does not call moveQueueItem', async () => { - render(QueueTrackRow, { props: { track: sampleTrack, index: 3, isCurrent: false } }); - const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: 'Enter' }); - expect(moveQueueItem).not.toHaveBeenCalled(); - }); - - it('Space on the drag handle prevents default but does not call moveQueueItem', async () => { - render(QueueTrackRow, { props: { track: sampleTrack, index: 3, isCurrent: false } }); - const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: ' ' }); - expect(moveQueueItem).not.toHaveBeenCalled(); + const notPrevented = await fireEvent.keyDown(handle, { key }); + expect(notPrevented).toBe(false); + if (move) expect(moveQueueItem).toHaveBeenCalledWith(...move); + else expect(moveQueueItem).not.toHaveBeenCalled(); }); // --- handle placement --- diff --git a/web/src/lib/components/StageBadge.test.ts b/web/src/lib/components/StageBadge.test.ts index c03536a3..08d4fa1a 100644 --- a/web/src/lib/components/StageBadge.test.ts +++ b/web/src/lib/components/StageBadge.test.ts @@ -2,30 +2,17 @@ import { describe, it, expect } from 'vitest'; import { render, screen } from '@testing-library/svelte'; import StageBadge from './StageBadge.svelte'; +// A stage at work or finished carries an icon; one waiting or skipped is a +// muted word alone. describe('StageBadge', () => { - it('renders Processing + spinner when state is in_progress', () => { - render(StageBadge, { props: { state: 'in_progress' } }); - expect(screen.getByText('Processing')).toBeInTheDocument(); - // The spinner is a lucide icon — just confirm a child SVG exists. - expect(document.querySelector('svg')).toBeTruthy(); - }); - - it('renders Done + check when state is done', () => { - render(StageBadge, { props: { state: 'done' } }); - expect(screen.getByText('Done')).toBeInTheDocument(); - expect(document.querySelector('svg')).toBeTruthy(); - }); - - it('renders Pending muted when state is pending', () => { - render(StageBadge, { props: { state: 'pending' } }); - expect(screen.getByText('Pending')).toBeInTheDocument(); - // No icon for the muted states. - expect(document.querySelector('svg')).toBeFalsy(); - }); - - it('renders Skipped muted when state is skipped', () => { - render(StageBadge, { props: { state: 'skipped' } }); - expect(screen.getByText('Skipped')).toBeInTheDocument(); - expect(document.querySelector('svg')).toBeFalsy(); + it.each([ + ['in_progress', 'Processing', true], + ['done', 'Done', true], + ['pending', 'Pending', false], + ['skipped', 'Skipped', false] + ] as const)('%s reads %s', (state, label, icon) => { + render(StageBadge, { props: { state } }); + expect(screen.getByText(label)).toBeInTheDocument(); + expect(!!document.querySelector('svg')).toBe(icon); }); }); diff --git a/web/src/lib/components/TrackRow.test.ts b/web/src/lib/components/TrackRow.test.ts index c8d86d68..0c8a4236 100644 --- a/web/src/lib/components/TrackRow.test.ts +++ b/web/src/lib/components/TrackRow.test.ts @@ -48,15 +48,9 @@ describe('TrackRow', () => { expect(playQueue).toHaveBeenCalledWith(tracks, 1, { source: undefined }); }); - test('Enter on the row activates play', async () => { + test.each([['Enter'], [' ']])('%s on the row activates play', async (key) => { render(TrackRow, { props: { tracks, index: 0 } }); - await fireEvent.keyDown(screen.getByRole('button', { name: 'So Then' }), { key: 'Enter' }); - expect(playQueue).toHaveBeenCalledWith(tracks, 0, { source: undefined }); - }); - - test('Space on the row activates play', async () => { - render(TrackRow, { props: { tracks, index: 0 } }); - await fireEvent.keyDown(screen.getByRole('button', { name: 'So Then' }), { key: ' ' }); + await fireEvent.keyDown(screen.getByRole('button', { name: 'So Then' }), { key }); expect(playQueue).toHaveBeenCalledWith(tracks, 0, { source: undefined }); }); diff --git a/web/src/lib/components/queue-row-math.test.ts b/web/src/lib/components/queue-row-math.test.ts index b31f032c..7975d210 100644 --- a/web/src/lib/components/queue-row-math.test.ts +++ b/web/src/lib/components/queue-row-math.test.ts @@ -1,40 +1,22 @@ import { describe, it, expect } from 'vitest'; import { offsetToDelta } from './queue-row-math'; +// A drag moves a row by the whole rows it crosses, counting half a row or +// more as one. A row of no height moves nothing. describe('offsetToDelta', () => { - it('returns 0 for zero offset', () => { - expect(offsetToDelta(0, 64)).toBe(0); - }); - - it('returns 1 for a full row down', () => { - expect(offsetToDelta(64, 64)).toBe(1); - }); - - it('rounds half-rows down (just under midpoint)', () => { - expect(offsetToDelta(31, 64)).toBe(0); - }); - - it('rounds half-rows up (at or past midpoint)', () => { - expect(offsetToDelta(32, 64)).toBe(1); - }); - - it('handles negative offsets symmetrically (drag up)', () => { - expect(offsetToDelta(-64, 64)).toBe(-1); - expect(offsetToDelta(-32, 64)).toBe(0); // Math.round(-0.5) === 0 in JS - }); - - it('handles multi-row offsets', () => { - expect(offsetToDelta(192, 64)).toBe(3); - expect(offsetToDelta(-128, 64)).toBe(-2); - }); - - it('returns 0 when rowHeight is non-positive (defensive)', () => { - expect(offsetToDelta(100, 0)).toBe(0); - expect(offsetToDelta(100, -1)).toBe(0); - }); - - it('respects the measured row height (e.g., h-14 = 56px)', () => { - expect(offsetToDelta(56, 56)).toBe(1); - expect(offsetToDelta(28, 56)).toBe(1); // 0.5 → 1 (half-up) + it.each([ + [0, 64, 0], + [64, 64, 1], + [31, 64, 0], + [32, 64, 1], + [28, 56, 1], + [192, 64, 3], + [-64, 64, -1], + [-32, 64, 0], // Math.round(-0.5) is 0 + [-128, 64, -2], + [100, 0, 0], + [100, -1, 0] + ])('%spx on %spx rows → %s', (offset, rowHeight, want) => { + expect(offsetToDelta(offset, rowHeight)).toBe(want); }); }); diff --git a/web/src/lib/example.test.ts b/web/src/lib/example.test.ts deleted file mode 100644 index 50cae2e6..00000000 --- a/web/src/lib/example.test.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -describe('scaffold smoke', () => { - it('runs vitest', () => { - expect(1 + 1).toBe(2); - }); -}); diff --git a/web/src/lib/media/duration.test.ts b/web/src/lib/media/duration.test.ts index 91427e32..aa4722f8 100644 --- a/web/src/lib/media/duration.test.ts +++ b/web/src/lib/media/duration.test.ts @@ -2,32 +2,19 @@ import { describe, expect, test } from 'vitest'; import { formatDuration } from './duration'; describe('formatDuration', () => { - test('under a minute renders 0:SS', () => { - expect(formatDuration(42)).toBe('0:42'); - expect(formatDuration(5)).toBe('0:05'); - }); - - test('under an hour renders M:SS', () => { - expect(formatDuration(242)).toBe('4:02'); - expect(formatDuration(600)).toBe('10:00'); - }); - - test('at or above an hour renders H:MM:SS', () => { - expect(formatDuration(3600)).toBe('1:00:00'); - expect(formatDuration(3723)).toBe('1:02:03'); - expect(formatDuration(36000)).toBe('10:00:00'); - }); - - test('zero renders 0:00', () => { - expect(formatDuration(0)).toBe('0:00'); - }); - - test('negative values clamp to 0:00', () => { - expect(formatDuration(-1)).toBe('0:00'); - expect(formatDuration(-100)).toBe('0:00'); - }); - - test('fractional seconds floor', () => { - expect(formatDuration(61.9)).toBe('1:01'); + test.each([ + [0, '0:00'], + [5, '0:05'], + [42, '0:42'], + [242, '4:02'], + [600, '10:00'], + [3600, '1:00:00'], + [3723, '1:02:03'], + [36000, '10:00:00'], + [61.9, '1:01'], // fractions floor + [-1, '0:00'], // negatives clamp + [-100, '0:00'] + ])('%s s → %s', (sec, want) => { + expect(formatDuration(sec)).toBe(want); }); }); diff --git a/web/src/lib/player/store.test.ts b/web/src/lib/player/store.test.ts index 6f125057..5221acc5 100644 --- a/web/src/lib/player/store.test.ts +++ b/web/src/lib/player/store.test.ts @@ -104,27 +104,17 @@ describe('player store — basic actions', () => { expect(player.position).toBe(180); }); - test('skipPrev with position<3 AND index>0: decrements index', () => { - playQueue([track('1'), track('2'), track('3')], 2); - reportTimeUpdate(2); + // Previous restarts a track already under way, and otherwise steps back; + // the first track has nowhere to step back to. + test.each([ + ['early in a later track steps back', 2, 2, 1], + ['well into a track restarts it', 1, 10, 1], + ['early in the first track restarts it', 0, 2, 0] + ])('skipPrev: %s', (_label, index, position, wantIndex) => { + playQueue([track('1'), track('2'), track('3')], index); + reportTimeUpdate(position); skipPrev(); - expect(player.index).toBe(1); - expect(player.position).toBe(0); - }); - - test('skipPrev with position>=3: seeks to 0, index unchanged', () => { - playQueue([track('1'), track('2')], 1); - reportTimeUpdate(10); - skipPrev(); - expect(player.index).toBe(1); - expect(player.position).toBe(0); - }); - - test('skipPrev at index=0: position=0, index stays', () => { - playQueue([track('1'), track('2')], 0); - reportTimeUpdate(2); - skipPrev(); - expect(player.index).toBe(0); + expect(player.index).toBe(wantIndex); expect(player.position).toBe(0); }); @@ -186,28 +176,15 @@ describe('player store — shuffle + repeat + audio reports', () => { expect(player.repeat).toBe('off'); }); - test('toggleShuffle randomizes queue[index+1..end], leaves current and earlier alone', () => { - // Deterministic RNG: always returns 0 so Fisher-Yates swaps each i with i - // itself → no change. Flip to always 0.999 to force swaps. - const seq = [0.999, 0.999, 0.999, 0.999, 0.999]; - let i = 0; - __setShuffleRng(() => seq[i++ % seq.length]); - - const tracks = [track('1'), track('2'), track('3'), track('4'), track('5')]; - playQueue(tracks, 1); + // Shuffle reorders only what is still to come. An rng of 0 swaps every + // slot it reaches with the first slot in its range, so a range that reached + // back to the current track or before would move it. + test('toggleShuffle reorders the tracks after the current one, and only those', () => { + __setShuffleRng(() => 0); + playQueue([track('1'), track('2'), track('3'), track('4'), track('5')], 1); toggleShuffle(); - expect(player.shuffle).toBe(true); - // Index 0 and 1 preserved: - expect(player.queue[0].id).toBe('1'); - expect(player.queue[1].id).toBe('2'); - // Index 2..4 reordered: because RNG = 0.999 always, Math.floor(rng() * - // (j+1)) === j for each, so swaps are with self — queue is unchanged. So - // validate that the IDs 3/4/5 are still the tail set, in any order, to - // tolerate future RNG semantics. - const tailIds = [player.queue[2].id, player.queue[3].id, player.queue[4].id].sort(); - expect(tailIds).toEqual(['3', '4', '5']); - + expect(player.queue.map((t) => t.id)).toEqual(['1', '2', '4', '5', '3']); __setShuffleRng(Math.random); }); @@ -229,62 +206,43 @@ describe('player store — shuffle + repeat + audio reports', () => { expect(player.position).toBe(120); }); - test('reportStateFromAudio("ended") with repeat="one": position=0, index unchanged, state=loading', () => { - playQueue([track('1'), track('2')], 0); - reportTimeUpdate(120); - cycleRepeat(); cycleRepeat(); // repeat=one - reportStateFromAudio('ended'); - expect(player.index).toBe(0); - expect(player.position).toBe(0); - expect(player.state).toBe('loading'); - }); - - test('reportStateFromAudio("ended") with repeat="all": wraps when at end', () => { - playQueue([track('1'), track('2')], 1); - cycleRepeat(); // repeat=all - reportStateFromAudio('ended'); - expect(player.index).toBe(0); - expect(player.state).toBe('loading'); - }); - - test('reportStateFromAudio("ended") with repeat="all" mid-queue: advances', () => { - playQueue([track('1'), track('2'), track('3')], 0); - cycleRepeat(); // repeat=all - reportStateFromAudio('ended'); - expect(player.index).toBe(1); - }); - - test('reportStateFromAudio("ended") with repeat="off" at end: paused', () => { - playQueue([track('1'), track('2')], 1); + // A track ending: repeat one plays it again, repeat all moves on and wraps, + // and with repeat off the last track stops at its end. + test.each([ + ['repeat one replays the track', 1, 2, 0, 0, 'loading', 0], + ['repeat all moves on', 2, 3, 0, 1, 'loading', 0], + ['repeat all wraps at the end', 2, 2, 1, 0, 'loading', 0], + ['repeat off stops at the end', 0, 2, 1, 1, 'paused', 180] + ] as const)('a track ending with %s', (_label, cycles, n, start, wantIndex, wantState, wantPos) => { + playQueue(Array.from({ length: n }, (_, i) => track(String(i + 1))), start); reportDuration(180); + reportTimeUpdate(120); + for (let i = 0; i < cycles; i++) cycleRepeat(); reportStateFromAudio('ended'); - expect(player.state).toBe('paused'); - expect(player.position).toBe(180); + expect(player.index).toBe(wantIndex); + expect(player.state).toBe(wantState); + expect(player.position).toBe(wantPos); }); - test('reportStateFromAudio("playing") sets state=playing, clears error', () => { + test.each([ + ['playing', 'playing'], + ['paused', 'paused'], + ['waiting', 'loading'] + ] as const)('the audio reporting %s puts the player in %s', (event, want) => { + playQueue([track('1'), track('2')]); + reportStateFromAudio('playing'); + reportStateFromAudio(event); + expect(player.state).toBe(want); + }); + + test('playing again clears the last error', () => { playQueue([track('1')]); reportStateFromAudio('error', 'boom'); expect(player.error).toBe('boom'); reportStateFromAudio('playing'); - expect(player.state).toBe('playing'); expect(player.error).toBeNull(); }); - test('reportStateFromAudio("paused") sets state=paused', () => { - playQueue([track('1')]); - reportStateFromAudio('playing'); - reportStateFromAudio('paused'); - expect(player.state).toBe('paused'); - }); - - test('reportStateFromAudio("waiting") sets state=loading', () => { - playQueue([track('1')]); - reportStateFromAudio('playing'); - reportStateFromAudio('waiting'); - expect(player.state).toBe('loading'); - }); - test('reportStateFromAudio("error", msg) sets state=error, error=msg', () => { playQueue([track('1')]); reportStateFromAudio('error', 'network lost'); @@ -534,62 +492,36 @@ describe('M4c radio auto-refresh at 80%', () => { }); describe('queue mutations', () => { - test('moveQueueItem reorders correctly when the playing track stays put', () => { - playQueue([track('a'), track('b'), track('c')], 0); - moveQueueItem(1, 2); - expect(player.queue.map((x) => x.id)).toEqual(['a', 'c', 'b']); - expect(player.index).toBe(0); + // A move keeps the index on the playing track wherever its row ends up; a + // move to the same place, or from or to outside the queue, changes nothing. + test.each([ + ['another row moves past the playing one', ['a', 'b', 'c'], 0, 1, 2, ['a', 'c', 'b'], 0], + ['the playing row moves', ['a', 'b', 'c'], 1, 1, 0, ['b', 'a', 'c'], 0], + ['a row moves from before to after the playing one', ['a', 'b', 'c', 'd'], 1, 0, 3, ['b', 'c', 'd', 'a'], 0], + ['a row moves onto itself', ['a', 'b', 'c'], 1, 1, 1, ['a', 'b', 'c'], 1], + ['from is out of range', ['a', 'b', 'c'], 0, -1, 1, ['a', 'b', 'c'], 0], + ['to is out of range', ['a', 'b', 'c'], 0, 0, 5, ['a', 'b', 'c'], 0] + ])('moveQueueItem: %s', (_label, ids, start, from, to, want, wantIndex) => { + playQueue(ids.map((id) => track(id)), start); + moveQueueItem(from, to); + expect(player.queue.map((x) => x.id)).toEqual(want); + expect(player.index).toBe(wantIndex); }); - test('moveQueueItem keeps _index pointing at the playing track when its row moves', () => { - playQueue([track('a'), track('b'), track('c')], 1); - moveQueueItem(1, 0); - expect(player.queue.map((x) => x.id)).toEqual(['b', 'a', 'c']); - expect(player.index).toBe(0); - }); - - test('moveQueueItem preserves _index logical pointer when other rows reorder around it', () => { - playQueue([track('a'), track('b'), track('c'), track('d')], 1); - moveQueueItem(0, 3); - expect(player.queue.map((x) => x.id)).toEqual(['b', 'c', 'd', 'a']); - expect(player.index).toBe(0); - }); - - test('moveQueueItem with from === to is a no-op', () => { - playQueue([track('a'), track('b'), track('c')], 1); - moveQueueItem(1, 1); - expect(player.queue.map((x) => x.id)).toEqual(['a', 'b', 'c']); - expect(player.index).toBe(1); - }); - - test('moveQueueItem with out-of-range from or to is a no-op', () => { - playQueue([track('a'), track('b'), track('c')], 0); - moveQueueItem(-1, 1); - expect(player.queue.map((x) => x.id)).toEqual(['a', 'b', 'c']); - moveQueueItem(0, 5); - expect(player.queue.map((x) => x.id)).toEqual(['a', 'b', 'c']); - }); - - test('removeFromQueue with idx < _index decrements _index', () => { - playQueue([track('a'), track('b'), track('c')], 2); - removeFromQueue(0); - expect(player.queue.map((x) => x.id)).toEqual(['b', 'c']); - expect(player.index).toBe(1); - }); - - test('removeFromQueue with idx > _index leaves _index unchanged', () => { - playQueue([track('a'), track('b'), track('c')], 0); - removeFromQueue(2); - expect(player.queue.map((x) => x.id)).toEqual(['a', 'b']); - expect(player.index).toBe(0); - }); - - test('removeFromQueue with idx === _index advances to next, sets state to loading', () => { - playQueue([track('a'), track('b'), track('c')], 1); - removeFromQueue(1); - expect(player.queue.map((x) => x.id)).toEqual(['a', 'c']); - expect(player.index).toBe(1); - expect(player.state).toBe('loading'); + // Removing a row keeps the index on the playing track. Removing the playing + // track itself plays the next, or pauses on the one before at the end; an + // emptied queue is idle. + test.each([ + ['a row before the playing one', 2, 0, ['b', 'c'], 1, 'loading'], + ['a row after the playing one', 0, 2, ['a', 'b'], 0, 'loading'], + ['the playing row', 1, 1, ['a', 'c'], 1, 'loading'], + ['the playing row at the end', 2, 2, ['a', 'b'], 1, 'paused'] + ] as const)('removeFromQueue: %s', (_label, start, idx, want, wantIndex, wantState) => { + playQueue([track('a'), track('b'), track('c')], start); + removeFromQueue(idx); + expect(player.queue.map((x) => x.id)).toEqual(want); + expect(player.index).toBe(wantIndex); + expect(player.state).toBe(wantState); }); test('removeFromQueue emptying the queue sets state to idle', () => { @@ -599,15 +531,6 @@ describe('queue mutations', () => { expect(player.state).toBe('idle'); }); - test('removeFromQueue of the currently-playing last track pauses on the previous track', () => { - playQueue([track('a'), track('b'), track('c')], 2); - removeFromQueue(2); - expect(player.queue.map((x) => x.id)).toEqual(['a', 'b']); - expect(player.index).toBe(1); - expect(player.state).toBe('paused'); - expect(player.position).toBe(0); - }); - test('playFromQueueIndex sets index, resets position, sets state to loading', () => { playQueue([track('a'), track('b'), track('c')], 0); playFromQueueIndex(2); @@ -624,19 +547,11 @@ describe('queue mutations', () => { expect(player.state).toBe(stateBefore); }); - test('toggleQueueDrawer flips _queueDrawerOpen', () => { + test('the queue drawer toggles, and close leaves it closed', () => { expect(player.queueDrawerOpen).toBe(false); toggleQueueDrawer(); expect(player.queueDrawerOpen).toBe(true); - toggleQueueDrawer(); - expect(player.queueDrawerOpen).toBe(false); - }); - - test('closeQueueDrawer is idempotent', () => { closeQueueDrawer(); - expect(player.queueDrawerOpen).toBe(false); - toggleQueueDrawer(); - expect(player.queueDrawerOpen).toBe(true); closeQueueDrawer(); expect(player.queueDrawerOpen).toBe(false); }); @@ -678,33 +593,23 @@ describe('queue mutations', () => { }); describe('crossfade', () => { - test('deriveFadeScalar returns 1 when crossfadeSec is 0', async () => { + // The volume ramps in over the first crossfade seconds and out over the + // last, and not at all when crossfade is off or the track is too short to + // fade both ways. + test.each([ + ['crossfade off', 50, 200, 0, 1], + ['crossfade off, at the start', 0, 200, 0, 1], + ['too short to fade twice', 0, 6, 4, 1], + ['too short, midway', 3, 6, 4, 1], + ['the first moment', 0, 60, 4, 0], + ['halfway in', 2, 60, 4, 0.5], + ['faded in', 4, 60, 4, 1], + ['before the fade out', 56, 60, 4, 1], + ['halfway out', 58, 60, 4, 0.5], + ['the end', 60, 60, 4, 0] + ])('deriveFadeScalar: %s', async (_label, pos, dur, fade, want) => { const { deriveFadeScalar } = await import('./store.svelte'); - expect(deriveFadeScalar(50, 200, 0)).toBe(1); - expect(deriveFadeScalar(0, 200, 0)).toBe(1); - expect(deriveFadeScalar(200, 200, 0)).toBe(1); - }); - - test('deriveFadeScalar returns 1 when track is too short to fade twice', async () => { - const { deriveFadeScalar } = await import('./store.svelte'); - // 6s track with 4s crossfade: 6 < 4*2, so no fade. - expect(deriveFadeScalar(0, 6, 4)).toBe(1); - expect(deriveFadeScalar(3, 6, 4)).toBe(1); - }); - - test('deriveFadeScalar ramps in over the leading X seconds', async () => { - const { deriveFadeScalar } = await import('./store.svelte'); - // 60s track, 4s crossfade. - expect(deriveFadeScalar(0, 60, 4)).toBe(0); - expect(deriveFadeScalar(2, 60, 4)).toBe(0.5); - expect(deriveFadeScalar(4, 60, 4)).toBe(1); - }); - - test('deriveFadeScalar ramps out over the trailing X seconds', async () => { - const { deriveFadeScalar } = await import('./store.svelte'); - expect(deriveFadeScalar(56, 60, 4)).toBe(1); - expect(deriveFadeScalar(58, 60, 4)).toBe(0.5); - expect(deriveFadeScalar(60, 60, 4)).toBe(0); + expect(deriveFadeScalar(pos, dur, fade)).toBe(want); }); test('setCrossfade clamps to [0, 12] and persists', async () => { diff --git a/web/src/routes/admin/admin.test.ts b/web/src/routes/admin/admin.test.ts index 3c8eaa43..cf26a270 100644 --- a/web/src/routes/admin/admin.test.ts +++ b/web/src/routes/admin/admin.test.ts @@ -41,22 +41,17 @@ describe('admin/+layout.ts load gate', () => { // The root layout signs the user in; parent() resolves once it has. const signedIn = { parent: async () => ({}) } as unknown as Parameters[0]; - test('non-admin user throws redirect to /', async () => { - userState.current = { id: 'u1', username: 'alice', is_admin: false }; + // Only an admin reaches an admin page; anyone else, signed in or not, is + // sent home. + test.each([ + ['a listener', { id: 'u1', username: 'alice', is_admin: false }, false], + ['nobody signed in', null, false], + ['an admin', { id: 'u1', username: 'root', is_admin: true }, true] + ])('%s', async (_label, who, passes) => { + userState.current = who; const { load } = await import('./+layout'); - await expect(load(signedIn)).rejects.toMatchObject({ status: 302, location: '/' }); - }); - - test('unauthenticated (null user) throws redirect to /', async () => { - userState.current = null; - const { load } = await import('./+layout'); - await expect(load(signedIn)).rejects.toMatchObject({ status: 302, location: '/' }); - }); - - test('admin user passes the gate', async () => { - userState.current = { id: 'u1', username: 'root', is_admin: true }; - const { load } = await import('./+layout'); - await expect(load(signedIn)).resolves.toEqual({}); + if (passes) await expect(load(signedIn)).resolves.toEqual({}); + else await expect(load(signedIn)).rejects.toMatchObject({ status: 302, location: '/' }); }); test('opening an admin page directly waits for sign-in instead of bouncing an admin', async () => { diff --git a/web/src/routes/playlists/[id]/playlist.test.ts b/web/src/routes/playlists/[id]/playlist.test.ts index 94862b9f..f3b3d499 100644 --- a/web/src/routes/playlists/[id]/playlist.test.ts +++ b/web/src/routes/playlists/[id]/playlist.test.ts @@ -154,46 +154,16 @@ describe('Playlist detail page', () => { await waitFor(() => expect(deletePlaylist).toHaveBeenCalledWith('p1')); }); - test('renders Refresh button on a refreshable system playlist', () => { - const discoverDetail: PlaylistDetail = { - ...ownDetail, - kind: 'system', - system_variant: 'discover', - refreshable: true - }; - mockedQuery.mockReturnValue(mockQuery({ data: discoverDetail })); + // Refresh is offered exactly when the server says the playlist can be + // rebuilt, whatever kind of mix it is. + test.each([ + ['a refreshable system mix', { kind: 'system', system_variant: 'discover', refreshable: true }, true], + ['a system mix that cannot be rebuilt', { kind: 'system', system_variant: 'songs_like_artist', refreshable: false }, false], + ["a listener's own playlist", {}, false] + ] as const)('Refresh on %s', (_label, over, shown) => { + mockedQuery.mockReturnValue(mockQuery({ data: { ...ownDetail, ...over } as PlaylistDetail })); render(PlaylistDetailPage); - expect(screen.getByLabelText(/refresh playlist/i)).toBeInTheDocument(); - }); - - test('renders Refresh button on For You too (also refreshable now)', () => { - const forYouDetail: PlaylistDetail = { - ...ownDetail, - kind: 'system', - system_variant: 'for_you', - refreshable: true - }; - mockedQuery.mockReturnValue(mockQuery({ data: forYouDetail })); - render(PlaylistDetailPage); - expect(screen.getByLabelText(/refresh playlist/i)).toBeInTheDocument(); - }); - - test('does not render Refresh on a non-refreshable system playlist', () => { - const songsLike: PlaylistDetail = { - ...ownDetail, - kind: 'system', - system_variant: 'songs_like_artist', - refreshable: false - }; - mockedQuery.mockReturnValue(mockQuery({ data: songsLike })); - render(PlaylistDetailPage); - expect(screen.queryByLabelText(/refresh playlist/i)).not.toBeInTheDocument(); - }); - - test('does not render Refresh button on user playlists', () => { - mockedQuery.mockReturnValue(mockQuery({ data: ownDetail })); - render(PlaylistDetailPage); - expect(screen.queryByLabelText(/refresh playlist/i)).not.toBeInTheDocument(); + expect(!!screen.queryByLabelText(/refresh playlist/i)).toBe(shown); }); test('Refresh button calls refreshSystem with the variant', async () => { diff --git a/web/src/routes/register/register.test.ts b/web/src/routes/register/register.test.ts index 0482e7a1..8e76ae2f 100644 --- a/web/src/routes/register/register.test.ts +++ b/web/src/routes/register/register.test.ts @@ -66,8 +66,13 @@ describe('/register page', () => { }); }); - test('shows error message for invite_invalid code', async () => { - (register as ReturnType).mockRejectedValue({ code: 'invite_invalid' }); + // Each refusal says what went wrong in words the visitor can act on. + test.each([ + ['invite_invalid', /invite token is invalid/i], + ['invite_required', /invite token is needed/i], + ['username_taken', /username is already taken/i] + ])('a refusal for %s says why', async (code, message) => { + (register as ReturnType).mockRejectedValue({ code }); render(RegisterPage); await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'newuser' } }); await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } }); @@ -75,33 +80,7 @@ describe('/register page', () => { await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } }); await fireEvent.click(screen.getByRole('button', { name: /create account/i })); await waitFor(() => { - expect(screen.getByRole('alert').textContent).toMatch(/invite token is invalid/i); - }); - }); - - test('shows error message for username_taken code', async () => { - (register as ReturnType).mockRejectedValue({ code: 'username_taken' }); - render(RegisterPage); - await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'existinguser' } }); - await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } }); - await fireEvent.input(screen.getByLabelText(/confirm password/i), { target: { value: 'abcd1234' } }); - await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } }); - await fireEvent.click(screen.getByRole('button', { name: /create account/i })); - await waitFor(() => { - expect(screen.getByRole('alert').textContent).toMatch(/username is already taken/i); - }); - }); - - test('shows error message for invite_required code', async () => { - (register as ReturnType).mockRejectedValue({ code: 'invite_required' }); - render(RegisterPage); - await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'newuser' } }); - await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } }); - await fireEvent.input(screen.getByLabelText(/confirm password/i), { target: { value: 'abcd1234' } }); - await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } }); - await fireEvent.click(screen.getByRole('button', { name: /create account/i })); - await waitFor(() => { - expect(screen.getByRole('alert').textContent).toMatch(/invite token/i); + expect(screen.getByRole('alert').textContent).toMatch(message); }); }); @@ -155,9 +134,7 @@ describe('/register page', () => { }); }); - test('login page has link to register', () => { - // The login page symmetrically has a "Register" link - tested here via the - // register page having a "Sign in" link back to /login. + test('links back to sign in', () => { render(RegisterPage); const link = screen.getByRole('link', { name: /sign in/i }); expect(link).toHaveAttribute('href', '/login'); diff --git a/web/src/routes/settings/appearance/appearance.test.ts b/web/src/routes/settings/appearance/appearance.test.ts index ef1b07c2..6249ae9c 100644 --- a/web/src/routes/settings/appearance/appearance.test.ts +++ b/web/src/routes/settings/appearance/appearance.test.ts @@ -15,17 +15,13 @@ describe('Settings › Appearance', () => { expect(screen.getAllByRole('radio').map((r) => r.parentElement?.textContent?.trim())).toEqual(['Dark', 'Light', 'System']); }); - test('choosing light stores it and sets data-theme', async () => { + test.each([ + ['Light', 'light'], + ['Dark', 'dark'] + ])('choosing %s stores it and sets data-theme', async (name, value) => { render(AppearancePage); - await fireEvent.click(screen.getByRole('radio', { name: 'Light' })); - expect(localStorage.getItem('minstrel:theme')).toBe('light'); - expect(document.documentElement.getAttribute('data-theme')).toBe('light'); - }); - - test('choosing dark stores it and sets data-theme', async () => { - render(AppearancePage); - await fireEvent.click(screen.getByRole('radio', { name: 'Dark' })); - expect(localStorage.getItem('minstrel:theme')).toBe('dark'); - expect(document.documentElement.getAttribute('data-theme')).toBe('dark'); + await fireEvent.click(screen.getByRole('radio', { name })); + expect(localStorage.getItem('minstrel:theme')).toBe(value); + expect(document.documentElement.getAttribute('data-theme')).toBe(value); }); });