chore: expand and generate specs for the frontend code section (#242)
* docs(plan): add frontend 90 coverage execution plan - Planning: - persist the frontend 90% coverage strategy under docs/plans for reuse across long-running execution and compaction events - capture the operating rules for the run, including per-bucket ordering, acceptance checks, and runtime-code-change policy - Workflow: - establish a durable in-repo reference that later progress updates can anchor to without re-deriving context * chore(testing): strengthen frontend coverage tooling - Harness: - consolidate the Vitest configuration Angular actually uses and add richer coverage reporters for iterative analysis - add browser-test dependencies for Angular Testing Library, MSW, Playwright, and canvas-aware DOM assertions - Workflow: - add just/package scripts for coverage summaries and browser-test setup so the coverage push can run through the repo command surface - expand test setup with stable browser shims needed by interactive frontend tests without touching runtime application code * fix(frontend): restore chart datalabel typings for test builds - Frontend build: - add a type-only declaration that imports `chartjs-plugin-datalabels` - restore the plugin's Chart.js option augmentation during Angular test compilation - Why: - `just ui test` and `just ui coverage` were blocked by stats chart option typing errors - this keeps the fix isolated from the new test work and does not change runtime behavior * test(auth): cover routing guards and login flows - Auth and routing: - add specs for the route table, auth guard, auth interceptor, and setup/login guards - cover token expiry, default-password redirects, refresh retry behavior, and setup redirects - Login surface: - add login component coverage for query-param messaging, local login outcomes, OIDC init, and forced OIDC mode - stabilize the Angular test harness for direct targeted Vitest runs with compiler/test setup support - Validation: - pass `just ui typecheck` - pass `just ui lint` - pass `just ui test` - pass `just ui coverage` * chore(testing): force frontend tests to run once * test(core-security): expand auth and oidc coverage * chore(frontend): refresh ui dependencies and dev stack - Frontend dependencies: - bump the Angular, Vitest, Testing Library, Playwright, linting, and related Yarn package ecosystem versions - regenerate the lockfile to keep the workspace aligned with the updated package set - Dev compose: - keep the database service on the existing `backend_db` name while retaining the frontend `node_modules` volume setup - remove the frontend-to-backend startup ordering dependency to avoid coupling container startup semantics unnecessarily - Lint compatibility: - rewrite the reading survival median-dropout branch to use a single derived constant instead of redundant assignment - simplify theme path replacement in the layout service so the updated lint rules pass without changing runtime behavior - Validation: - run `docker compose -f dev.docker-compose.yml config` - run `just ui lint` - run `just ui check` - run `just ui typecheck` - run `just ui test` * test(frontend): cover core and shared startup services - Core config: - add language initializer coverage for persisted, legacy, browser-locale, and english fallback paths - cover the auth initialization signal service state transition - Shared services: - add local storage, startup, and version service specs around parsing, error handling, token-gated startup, and HTTP requests - Testing: - keep the batch green under the Angular test harness and drop the brittle main bootstrap spec attempt for now * chore(testing): prepare frontend swarm controller - Planning: - rewrite the persistent frontend coverage plan around a controller branch with repo-local worktrees and bounded worker ownership - keep the swarm execution rules, integration order, and validation expectations in docs/plans/frontend-90-coverage-plan.md - Testing tooling: - harden the coverage summary script so it resolves reports from the frontend root and reports branch and line coverage correctly - simplify the secondary Vitest config so it cleanly inherits the Angular-backed base config - Repo hygiene: - reserve .worktrees/ as the only local worktree root and ignore it in the repository * test(frontend): cover author notebook and series services - Author browser: - cover cache patching, debounced scale persistence, and selection-range behavior - Notebook and series browser: - cover notebook query parameter construction and series service state/summary logic - add scale preference coverage for series browsing persistence - Validation: - ran just ui typecheck, just ui lint, and just ui test for the controller bucket * test(core): cover transloco and auth bootstrap branches - Core config: - add inline transloco loader coverage for english defaults, lazy language merges, and unsupported-language fallback - Core auth: - broaden auth initializer coverage across local auth, remote auth, missing settings, and remote login failure paths - add the missing OIDC discovery failure branch when the provider omits an authorization endpoint - Validation: - ran just ui typecheck, just ui lint, and just ui test in the f90-core-auth worktree * test(book): add service and helper coverage - Book query/cache surfaces: - expand invalidation coverage for list, detail, and recommendation query paths - cover cache patch helpers for metadata, field updates, and updater callbacks - cover empty delete-input handling - Book service/helper surfaces: - add query-key assertions for the primary book and library keys - cover navigation state transitions and derived computed state - cover read-status icon, class, tooltip, and visibility branches - cover sort service branches for no-sort, natural ordering, array comparisons, null handling, and unknown fields * test(shared): cover shared helpers and lightweight services - Utilities: - add direct tests for placeholder resolution and custom-font dropdown shaping - cover icon category list generation for deterministic shared metadata - Services: - verify the book metadata host subject publishes switch requests - exercise the menu source/reset subjects used by the shared layout shell - Scope: - keep the first shared bucket small and isolated from the heavier HTTP-backed service specs * fix(testing): restore targeted vitest setup - frontend: - restore the frontend Vitest wrapper config so direct targeted runs load `src/test-setup.ts` - keep the Angular base config as the shared source while preserving per-run spec discovery for local and worktree validation - workflow: - make worker branches able to validate narrow spec buckets without falling back to the full Angular test builder path * test(metadata): cover sidecar and review option flows - metadata services: - add HTTP contract coverage for sidecar fetch, sync, import, and export endpoints - metadata dialogs: - cover fetch option initialization and request submission behavior - cover provider field selection persistence and translation lookups - cover review dialog task loading, save progression, and close/error branches - validation: - exercise the first metadata bucket with a targeted Angular Vitest run plus frontend typecheck and lint * test(settings): cover core settings service branches - Settings services: - cover email provider and recipient CRUD flows, including defaults and deletions - cover email sending, OPDS user management, and content restriction CRUD - cover task scheduling, cron updates, task progress, and metadata refresh toast branches - Preferences components: - cover reader preference persistence with nested path updates and early-return behavior - Validation: - targeted settings test run via `ng test --runner vitest --include src/app/features/settings/**/*.spec.ts --watch=false` - `just ui typecheck` - `just ui lint` * test(settings): cover preference shell components - Reader preferences shell: - cover application-mode scope hydration and update forwarding for PDF, new PDF, EPUB, and CBX - Metadata center mode shell: - cover hydrated view-mode and series-view state plus save behavior for both user-present and user-missing branches - View preferences shell: - cover default sidebar width fallback and width persistence alongside the CSS variable update path - Validation: - settings subtree run via `ng test --runner vitest --include src/app/features/settings/**/*.spec.ts --watch=false` - `just ui typecheck` - `just ui lint` * test(readers): cover ebook bookmark and page decorator helpers - Reader bookmark service: - add deterministic coverage for missing-position handling, success toasts, default titles, duplicate conflicts, and generic failure resets - Page decoration: - add focused coverage for header and footer rendering across missing renderer state, single-column layout, multi-column layout, and theme-aware styling - Validation: - reran the exact small reader bucket alongside `just ui typecheck` and `just ui lint` to keep the first readers tranche green * test(book-browser): cover support service branches - Query-param orchestration: - cover explicit sort/filter parsing, legacy preference fallback, and default sort fallback - exercise query-param updates for view mode, sort, filter mode, filter sync, and series expansion detection - Browser preference services: - cover table column merging, visible-column ordering, and persistence skip/save branches - cover cover-scale loading, unchanged-scale bypass, debounce persistence, and error reporting - Validation: - run the book spec glob for the feature area - verify frontend typecheck and lint remain green * test(metadata): cover fetch option state branches - Metadata options: - add deterministic coverage for advanced fetch option hydration, submit validation, bulk provider assignment, and reset behavior - exercise the error toast path when enabled metadata fields are missing provider priorities - Multi-book fetch: - verify dialog initialization resolves the requested books and refresh type - cover signal-driven adoption of default metadata refresh options from app settings - Validation: - run targeted Angular metadata specs for sidecar, provider selector, fetch options, advanced fetch options, multi-book fetch, and review dialog - run just ui typecheck and just ui lint in the metadata worktree * test(metadata): cover sidecar viewer and reading sessions - Reading sessions: - add coverage for initial loading, book switches, formatting helpers, and progress or location display branches - verify failure handling clears loading without leaking stale session state - Sidecar viewer: - cover sync-status lookup, sidecar content loading, import/export success and failure toasts, and status label or severity mapping - suppress expected console noise in negative-path assertions while keeping the error branches exercised - Validation: - run targeted Angular metadata specs for sidecar viewer and book reading sessions - run just ui typecheck and just ui lint in the metadata worktree * test(metadata): cover manager aggregation and routing helpers - Metadata manager state: - cover effect-driven aggregation of authors, categories, moods, tags, series, publishers, and languages from loaded books - verify loading gating so metadata extraction waits for the shared book list to settle - Metadata manager routing and selection: - cover tab query-param handling, page-title updates, active-tab navigation, selection helpers, and filtered book navigation - exercise string matching and table filter plumbing without relying on template trivia - Validation: - run targeted Angular metadata spec for metadata manager - run just ui typecheck and just ui lint in the metadata worktree * test(metadata): cover picker review and save branches - Metadata picker: - cover provider-field visibility, suggestion filtering, metadata patching, review-state reset, and autocomplete or drag-drop helpers - exercise copied-value handling, locked-field warnings, save behavior, audible cover upload, lock toggles, hover state, and comic or format helper branches - Scope: - keep the bucket purely in metadata picker specs without runtime changes for testability - Validation: - run targeted Angular metadata spec for metadata picker - run just ui typecheck and just ui lint in the metadata worktree * test(stats): cover library filters and survival chart state - Cover library stats service behavior for empty libraries, translated fallbacks, selected-library filtering, and formatted totals - Cover user chart config state for load, toggle, reorder, reset, bulk enable/disable, and malformed storage fallback - Cover reading survival chart behavior for loading, empty, and populated source data paths - Validation: - targeted stats specs through the Angular Vitest harness - `just ui typecheck` - `just ui lint` * test(frontend): harvest worker coverage batches - Core and auth: - expand transloco, auth initialization, OIDC, interceptor, reuse strategy, and loading coverage without changing runtime code - repair merged worker specs so they stay compatible with the Angular test harness and repo lint rules - Book, settings, and app shell: - stabilize the harvested book-browser expectations, meta-center view-mode spec, and app component coverage additions - keep the merged batch green after pulling worker output onto the controller branch - Shared and readers: - add low-risk shared model, validator, and cache specs - pull in deterministic ebook and cbx reader service coverage from the closed worktrees - Validation: - run just ui typecheck - run just ui lint - run just ui test * test(frontend): expand browser and reader service coverage - Browser services: - strengthen author, series, notebook, and dashboard service specs to cover cache state, preferences, and supporting data flows - add book-browser service and filter specs for entity lookup, selection, scroll restoration, search normalization, sidebar filtering, and series collapse behavior - Reader services: - add ebook reader service coverage for annotation rendering, left-panel note/search state, and sidebar navigation, bookmarks, and annotation synchronization - Validation: - pass `just ui typecheck`, `just ui lint`, and `just ui test` * test(playwright): add port-safe smoke harness - Harness: - replace the ad hoc browser scaffold with an env-driven Playwright config that supports unique worker ports, per-port output directories, and non-watch dev-server startup - ignore Playwright output and browser cache artifacts so repeated smoke runs do not dirty the branch - Browser smoke baseline: - add a single canonical login-and-books scenario fixture with tightly scoped API mocks and auth seeding helpers - document the authoring rules for future browser scenarios so agents reuse the harness instead of inventing new configs and catch-all route shims - Planning and validation: - record the port-safe Playwright rules in the frontend coverage plan - pass `just ui typecheck`, `just ui lint`, `just ui test`, and `PLAYWRIGHT_PORT=4301 corepack yarn e2e playwright/login-and-books.spec.ts --list` * test(playwright): route browser commands through just - Harness: - add dedicated frontend Just recipes for Playwright server startup, single-spec execution, and test listing - switch the Playwright web server command to use the frontend Justfile instead of invoking Yarn directly - Docs: - update the Playwright README to document the Justfile entrypoints and the port-safe single-spec command - record the same Justfile rule in the frontend 90 percent coverage plan so future workers follow the same command surface - Validation: - ran `just ui typecheck` - ran `just ui lint` - ran `just ui test` - ran `just ui check` - ran `just --justfile frontend/Justfile --working-directory frontend e2e-list playwright/login-and-books.spec.ts` - ran `PLAYWRIGHT_PORT=4301 just --justfile frontend/Justfile --working-directory frontend e2e-file playwright/login-and-books.spec.ts` and confirmed the remaining failure is Chromium launch sandboxing, not port or watch configuration * docs(frontend): refresh 90 coverage execution state - Controller state: - replace the stale swarm assumptions with the current controller-driven launch record - record the repaired worktree layout, paused notifier state, and durable next actions - Incident tracking: - log the bad worktree setup, false-positive notification path, and rejected worker buckets - document why the book, metadata, readers, and shared lanes are not integration-ready - Coverage checkpoint: - capture the validated core lane totals and accepted candidate bucket - preserve the exact validation commands and commit proposal for the first integration step * test(core-auth-routes): add branch coverage for auth settings and route helpers - Core auth settings: - cover provider persistence, group sync, force-only handling, and mapping dialog flows - cover delete-group-mapping success and failure paths - Core utilities: - cover route reuse null-handle and missing scroll-position branches - cover secure image fallback and object URL cleanup - cover loading overlay custom-message and multi-loader cursor behavior - Validation: - `just ui typecheck` - `just ui lint` - `just ui test` - `just ui coverage` - `just ui coverage-summary` * test(bookdrop): cover file review selection flows - File review state: - cover default path derivation, selection counts, and finalize eligibility across current-page and select-all modes - cover selection toggles so cached UI state stays in sync with bulk selection state - Destructive action guards: - cover the reset, finalize, and delete warning paths when no files are selected - Validation: - `just ui typecheck` - `just ui lint` - `just ui test` - `just ui coverage` - `just ui coverage-summary` * test(readers): cover ebook selection state transitions - Reader selection state: - cover overlapping-annotation detection and popup state updates for text selections - cover preview, copy, search, and dismiss actions for the current selection - Reader annotation flows: - cover annotation creation, ignored deletion responses, and preview cleanup on hide - Validation: - `just ui typecheck` - `just ui lint` - `just ui test` - `just ui coverage` - `just ui coverage-summary` * docs(frontend): record controller checkpoint after worktree recovery Capture the current root truth after stop-all review and lane recovery. - Root is at 6c78b1de and ahead of origin by 4 commits. - Integrated buckets: core/auth/routes, bookdrop, and readers(selection-service only). - Current combined coverage: statements 21.62%, branches 16.57%, functions 18.31%, lines 37.45%. - Notification handling is paused behind the single local loop using /tmp/f90-status-loop.lock and local-scripts/.f90-status-loop.pid. - Shared batch was discarded; metadata, readers, and shared worktrees were cleaned and recreated for restart. - Next action is to restart one clean high-yield lane, starting with metadata + settings + stats if it remains test-only. * test(metadata-viewer): cover metadata viewer branches Add the accepted metadata viewer spec batch in the root checkout. - Owns only frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts. - Validation already passed in root: focused spec, typecheck, lint, test, coverage, and coverage-summary. - Coverage impact from the accepted batch: metadata-viewer.component.ts reached 38.28% branch coverage and the metadata/settings/stats lane moved to 13.08% branch coverage. * docs(frontend): record metadata viewer integration checkpoint Refresh the durable frontend coverage plan after integrating the accepted metadata viewer batch. - Root HEAD is now d3f05207 after the metadata viewer spec commit. - Current root coverage checkpoint: statements 23.00%, branches 17.94%, functions 19.49%, lines 38.37%. - Metadata-viewer.component.ts reached 38.28% branch coverage, and the metadata/settings/stats lane moved to 13.08% branches (464/3548). - Next recommended lane remains metadata/settings/stats, starting with metadata-searcher if it can stay test-only; otherwise pivot to the book/author/series/notebook lane. * test(readers): stabilize ebook event service spec - Replace the brittle spy typing with a plain callable function type. - Use a deterministic test document defaultView so selection and frame-element behavior are stable. - Adjust the click and popup expectations to match the service's actual reader behavior. - Verify the readers lane with just ui typecheck, just ui lint, and just ui test. * test(book): cover book card decision paths - Add focused book-card coverage for derived display state and progress rendering. - Exercise forced ebook reads, display-format resolution, and guarded card selection. - Cover series routing and metadata-center dialog behavior without touching runtime code. - Verify the root frontend gates with `just ui typecheck`, `just ui lint`, and `just ui test`. * test(shared): cover url helper routing fallbacks - Cover tokenized thumbnail and audiobook URL generation paths. - Exercise unsupported primary-reading fallbacks and supported reader routing. - Verify series and generic filter URL construction without changing runtime code. - Verify the root frontend gates with just ui typecheck, just ui lint, and just ui test. * test(author-browser): cover author service control flow - Cover metadata-search query param branching and quick-match region defaults. - Exercise SSE auto-match parsing and error propagation paths. - Cover token-dependent author media URL generation without touching runtime code. - Verify the root frontend gates with just ui typecheck, just ui lint, and just ui test. * docs(frontend): record post-lane integration checkpoint - Record the current root HEAD and integration state after the readers, book, and shared root-side commits. - Capture the latest coverage-summary output: statements 24.75%, branches 19.73%, functions 20.24%, lines 38.79%. - Preserve the metadata-viewer checkpoint as historical context while noting the current root tip and next lane recommendation. - Keep the restart lanes and notifier pause state visible for the next controller wave. * test(settings): cover task management control flow - Add focused task-management coverage for load failures, progress updates, and stale rerun gating. - Exercise async queueing, sync completion and failure handling, cancel flows, and cron validation paths. - Cover helper methods and task metadata behavior without touching runtime code. - Verify the frontend gates with just ui typecheck, just ui lint, just ui test, and just ui coverage-summary. * test(frontend): add todo stubs for missing spec files - Frontend test scaffolding: - add 267 missing sibling spec files under `frontend/src/app` - use skipped Vitest placeholders so every stub is explicitly non-executing coverage scaffolding - include a `TODO(frontend-coverage)` marker and a matching test-level TODO in each new spec - Coverage workflow: - make the remaining unowned frontend surfaces visible in the test tree without inventing runtime changes - create a consistent place for future targeted coverage work across core, features, and shared lanes - Validation: - run `just ui typecheck` - run `just ui lint` - run `just ui test` - run `just ui check` * test(frontend): cover pure models and config contracts - Coverage: add type-level specs for pure frontend config, model, and enum surfaces under core, author-browser, book, metadata, readers, and shared. - Intent: replace placeholder specs with cheap deterministic assertions that lock down static contract behavior without runtime seams. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover request payload and contract models - Coverage: add specs for additional book, metadata, notebook, readers, series-browser, and shared request or model contracts. - Intent: keep the stub-replacement pass moving through deterministic type-bearing files before shifting into heavier service and component surfaces. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover query keys and barrel exports - Coverage: add tests for shared and settings query keys, email contracts, metadata exports, and audiobook barrel exports. - Intent: close out low-risk placeholder specs where real value comes from locking contract shape and export stability. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover larger model defaults and dashboard contracts - Coverage: add specs for the main app-settings, dashboard, and book models. - Intent: finish the remaining pure model stubs before shifting toward control-flow and service behavior. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover setup and guard utilities - Coverage: add deterministic tests for setup services, setup guards, security guards, websocket helpers, and small filter helpers. - Intent: replace placeholder coverage with branch-bearing guard and bootstrap assertions that do not require runtime code changes. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover lightweight shared services - Coverage: add tests for page title, settings helper, icon picker, metadata-match weights, and notification event services. - Intent: convert low-friction service placeholders into real control-flow coverage before moving to HTTP-heavy wrappers. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover shared HTTP service wrappers - Coverage: add request and response tests for shared annotation, note, bookmark, reading-session, websocket, and group-mapping services. - Intent: replace generic HTTP-wrapper stubs with real endpoint-shape coverage that can fail honestly when request contracts drift. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover metadata utilities and book HTTP helpers - Coverage: add tests for metadata form and utility services, file operations, book cover helpers, metadata progress, and metadata-task behavior. - Intent: push coverage into utility and helper layers that affect metadata control flow without needing heavy component harnesses. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover shared utilities and document seam-heavy specs - Coverage: add real tests for theme, PDF annotation, audiobook session, and config helpers while converting the remaining runtime-heavy shared stubs into explicit seam notes. - Intent: separate deterministic coverage wins from surfaces that still need browser or runtime harnesses later. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover layout upload and reader-session services - Coverage: add real tests for layout service, background upload, audiobook service, icon service, and reading-session behavior. - Intent: grow coverage through shared layout and reader utilities without changing runtime code. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover lightweight settings wrappers - Coverage: add tests for directory-picker utilities, audit-log service behavior, and the low-friction library-loading path. - Intent: keep the pass focused on cheap deterministic seams while documenting the remaining dynamic component seam explicitly. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover book service control flow - Coverage: add real service tests for CBX reader and book patch flows and replace the user-service placeholder with a seam-aware spec. - Intent: increase branch coverage in book service layers while acknowledging the query-heavy user-service runtime boundary. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover small shared standalone components - Coverage: add direct component behavior tests for external links, empty states, and tag rendering. - Intent: clear straightforward standalone component stubs without spending time on decorative template-only churn. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover library loading and local shared components - Coverage: add tests for library-loading, live-notification, and directory-picker components using mocked local dependencies. - Intent: pick off component surfaces that have real behavior but do not require heavy application orchestration. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): document shared runtime seams - Coverage: replace remaining shared and library runtime-heavy placeholders with explicit seam-noted skipped specs. - Intent: make the remaining blocker surfaces auditable instead of leaving generic TODO stubs behind. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): document layout shell seams - Coverage: convert layout-heavy shell placeholders into seam-specific skipped specs. - Intent: record the need for mounted layout harnesses without spending time on brittle shallow shell tests. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover shared forms and dialogs - Coverage: add real tests for shared standalone form and dialog components with direct control-flow assertions. - Intent: capture meaningful component behavior where the harness cost is still low enough to justify real tests. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover progress and stats wrappers - Coverage: add real tests for a shared progress widget and a stats HTTP wrapper while documenting heavier query-driven seams. - Intent: keep coverage growth honest by splitting easy wrappers from runtime-heavy component and service surfaces. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover bookdrop API branches - Coverage: add bookdrop API and control-flow coverage and replace the remaining menu-command-heavy service stub with a seam note. - Intent: grow branch coverage in bookdrop services while avoiding low-yield template churn. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover shared utility components - Coverage: add real tests for shared utility components and convert heavier reader or chart placeholders into explicit seam-noted skips. - Intent: continue replacing generic placeholders while keeping runtime-heavy chart and reader shells out of the main path. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover book cache and series card behavior - Coverage: add real tests for book cache and control-flow services plus the series-card component, and document the remaining query-runtime seams. - Intent: prioritize behavior-bearing book surfaces instead of spreading effort over decorative render-only coverage. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover reader preference settings flows - Coverage: add real tests for reader-preference and naming settings while replacing browser-heavy settings shells and dialogs with seam notes. - Intent: move settings coverage upward without inventing runtime seams for the stubborn UI-heavy surfaces. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): document dashboard and stats visualization seams - Coverage: replace dashboard and stats visualization placeholders with explicit chart, canvas, scroll, and orchestration seam notes. - Intent: make the expensive visualization blockers explicit instead of keeping them as generic unowned TODO stubs. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): document remaining user stats chart seams - Coverage: convert another wave of user-stats chart placeholders into explicit runtime seam notes. - Intent: keep the coverage pass honest by documenting chart-runtime blockers without pretending that render smoke tests would help. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): document author-browser and dialog seams - Coverage: replace author-browser, book-dialog, user-management, and additional stats placeholders with routed dialog or widget seam notes. - Intent: record the real blocker surfaces cleanly and avoid low-yield retries on complex dialog stacks. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover reader dialogs and note library-stats seams - Coverage: add real tests for simple reader dialogs and header behavior and document the remaining library-stats, reader-shell, and bookdrop orchestration seams. - Intent: combine cheap reader wins with explicit notes for surfaces that still need mounted runtime harnesses. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): document remaining library stats and reader shell seams - Coverage: replace the remaining library-stats chart placeholders and ebook or CBX shell stubs with explicit chart and runtime seam notes. - Intent: finish the chart-heavy placeholder cleanup in a durable, auditable way. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): document settings and metadata shell seams - Coverage: convert another wave of settings, book, metadata, and stats shells from generic TODO stubs into explicit seam-documented specs. - Intent: keep the pass moving through high-friction surfaces without faking useful coverage. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover deterministic settings services - Coverage: add real tests for KOReader and metadata settings surfaces where the behavior is deterministic, and document the remaining dialog-heavy seams. - Intent: take the cheap service and settings wins while isolating the harder modal and query-driven blockers. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover selected reader and settings widgets - Coverage: add real tests for a simple dialog, the CBX footer, kobo settings service behavior, public review settings, and book-card-lite. - Intent: harvest another set of low-friction component and service wins while documenting the surrounding reader and email shell seams. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): cover book helper and review services - Coverage: add real tests for book review, dialog helper, orchestration, and overlay-preference services, and convert the remaining book browser and upload shells into explicit seam notes. - Intent: push branch coverage into real book control flow instead of spreading effort over decorative component smoke tests. - Validation: run just ui typecheck, just ui lint, and just ui test. * test(frontend): finish replacing generic spec stubs - Coverage: close out the remaining generic TODO stubs with real HTTP or class-level specs where cheap, and explicit seam-noted skipped specs where heavier Angular, PrimeNG, or reader-shell harnesses are still required. - Result: bring the generic TODO stub count under frontend src app to zero while preserving the no-runtime-change rule. - Validation: run just ui typecheck, just ui lint, just ui test, and finish with just ui check. * docs(frontend): record stub fill batches and commit plan - Tracking: capture the single-thread frontend stub fill batches in a durable log with scope, validation, and file lists. - Commit Plan: add Conventional Commit shapes for each batch so the work can be replayed or audited without rebuilding the grouping logic. - Validation: reflect the final frontend gate set of just ui typecheck, just ui lint, just ui test, and just ui check. * test(frontend): bootstrap coverage harness canaries - Plan: - add a new phase plan document for the supervised swarm rollout - record the bootstrap checkpoint, worker contract, package posture, and validation gates - Harnesses: - add shared query, chart, and dialog testing helpers for Angular Query, non-rendering chart assertions, and PrimeNG dialog seams - bring in `ng-mocks` as part of the test-only toolchain for the next coverage lane - Canaries: - convert the app settings and library service seam docs into executable coverage canaries - convert the genre stats chart and author photo search seam docs into active specs using the new helpers - Validation: - prove the bootstrap with focused vitest canaries and the broader `just ui typecheck`, `just ui lint`, `just ui test`, `just ui coverage`, and `just ui coverage-summary` gates * docs(plans): add phase 3 lieutenant swarm plan - Execution model: - define the controller, gitops lieutenant, notify lieutenant, and bounded worker roles for the next coverage push - record the new covswarm worktree scheme and the rule to preserve legacy f90 worktrees without reusing them - Operations: - capture the notification cadence, heartbeat contract, worker health gate, and seam-valuation rules for lane execution - define when the swarm widens from the first stats lane into query and dialog lanes - Baseline: - record the current frontend coverage totals, skipped-spec distribution, and bootstrap handoff state after commit 111466b5 * test(frontend): cover personal rating chart stats (cherry picked from commit b1ea299adc1622ab87a3e4e83d88270e785b7b08) * test(frontend): fix personal rating chart spec lint (cherry picked from commit a4b9f5fcff46a12820292ac827c48768a8499624) * test(frontend): cover shelf service query spec (cherry picked from commit 07c33f70fe93c313dab33e28680aaeb0503f0ecd) * test(frontend): cover user service query spec (cherry picked from commit d7b8047acb824c2dbf2a823a6808a0a2f6a16d7c) * test(frontend): fix user service helper typing (cherry picked from commit 5e905879b7bdbd493394f060045a5a77b71ac9d8) * test(frontend): align bulk edit dialog apply expectation (cherry picked from commit 5048aa2ac632348f5baf718a15fb2998ddb6f98f) * test(frontend): harden user service buildUser overrides (cherry picked from commit 985087df1b35ebfae1983af1615b2f6d56dc3e40) * test(frontend): cover magic shelf service spec (cherry picked from commit 594723fe76090b262229fd8610d85bb66aefa88d) * test(frontend): cover lock metadata dialog spec (cherry picked from commit d534f0116496181785371fe302fd01456114ac69) * test(shelf-edit-dialog): cover dialog spec behaviors - ShelfEditDialogComponent: - replace the skipped seam placeholder with a real injection-context harness - cover shelf hydration, icon selection, save success, save failure, and cancel flows - Validation: - preserve the worker's targeted Vitest coverage for the dialog spec batch (cherry picked from commit 488e1b1e9be7edc308a3e26f88fe679ffa6f7b63) * test(language-chart): cover non-rendering chart logic - LanguageChartComponent: - replace the skipped seam placeholder with deterministic signal-backed spec coverage - verify language normalization, top-language chart data, and tooltip formatting without a live Chart.js render - Validation: - preserve the worker's targeted Vitest coverage for the language-chart spec batch (cherry picked from commit c645a3bb73fe5b03f906a0a9e87b493d8f78e882) * test(sidebar-sorting-preferences): use angular change detection in spec - SidebarSortingPreferencesComponent: - replace the manual ngOnInit call with fixture.detectChanges so the test uses the standard Angular fixture lifecycle - preserve the validated fix for the recursive NG0101 failure in the focused spec run - Validation: - passed env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/settings/view-preferences-parent/sidebar-sorting-preferences/sidebar-sorting-preferences.component.spec.ts (cherry picked from commit 5653c92d6a1a3e0ef6b7e53f0218a0c8ad1d00ef) * test(stats): cover metadata score chart bucketing - Metadata score chart: - replace the skipped seam placeholder with focused spec coverage for score bucketing, average-score calculation, and selected-library filtering - assert deterministic doughnut chart labels, dataset values, and tooltip formatting without depending on a live Chart.js instance - Validation: - preserve the targeted Vitest pass previously reported for metadata-score-chart.component.spec.ts with 1 file passed and 3 tests passed (cherry picked from commit 0191fb93fe0273ff655ecf387f952c360216eab2) * test(book): cover query-backed book service state - Book service: - replace the skipped placeholder with focused specs for eager fetch behavior, auth-token-gated loading, and query-backed error and loading state - cover unique metadata derivation, shelf removal cache updates, and books-query removal when the auth token is cleared - Validation: - preserve the targeted Vitest pass previously reported for book.service.spec.ts with 1 file passed and 5 tests passed (cherry picked from commit 1f6a1da1830251280f8e578eebad99f98d403116) * test(stats): cover book formats chart aggregation - Book formats chart: - replace the skipped placeholder with focused specs for selected-library filtering and format aggregation - assert deterministic chart labels, dataset values, color selection including fallback colors, and direct tooltip callback output - Validation: - preserve the targeted Vitest pass previously reported for book-formats-chart.component.spec.ts with 1 file passed and 3 tests passed (cherry picked from commit 9ee15f88cad8b9f57f7b29413791baa528c01d78) * test(settings): cover create email provider dialog flows - Create email provider dialog: - replace the skipped placeholder with focused specs for validator state, invalid warn handling, and service mutation payloads on success - cover translated success and error toast branches, fallback error detail behavior, and explicit dialog close behavior - Validation: - preserve the targeted Vitest pass previously reported for create-email-provider-dialog.component.spec.ts with 1 file passed and 6 tests passed (cherry picked from commit 10760860cdb6344a3fb8d5eed4623a55734c3bee) * test(settings): stabilize sidebar sorting preferences spec - Sidebar sorting preferences: - replace the default Transloco test module setup with reRenderOnLangChange disabled to avoid recursive NG0101 behavior in the focused spec runtime - Validation: - preserve the focused rootfix2 Vitest pass for sidebar-sorting-preferences.component.spec.ts - keep the validated rerun free of recursive NG0101 stderr (cherry picked from commit 484a95ed3c40ecff7f379b43eefab82c5f0618a3) * test(author-browser): cover author match component flows - Author match component: - replace the skipped placeholder with class-only, provider-driven specs for search bootstrapping, canSearch gating, search result replacement, and translated toast handling - cover match request shaping, success emission, and failure reporting without coupling the spec to the Prime form runtime - Validation: - preserve the focused author worktree Vitest pass for author-match.component.spec.ts with 1 file passed and 6 tests passed (cherry picked from commit e5df9291648386e49236b6378bab37f73fc3f11b) * test(book): cover book notes component flows Add focused coverage for BookNotesComponent load, create, update, delete, and cancel paths. Validate the note sorting and toast behavior through service and confirmation doubles so the deferred book-components lane can land as an isolated replay batch. * test(author-browser): cover author editor component flows Add focused coverage for author editor form initialization, save payload shaping, photo dialog refresh, and upload handlers. Land the deferred author-browser lane as a single replay batch without touching runtime code. * test(book): cover shelf creator component flows Add dialog-focused coverage for ShelfCreatorComponent icon selection, cancel behavior, create payload shaping, and error handling. Replay the deferred book-components shelf-creator batch into root without carrying worktree repair residue. * test(book): cover book file service flows Add focused HTTP and query-cache coverage for BookFileService downloads, uploads, detach, attach, and delete flows. Replay the deferred query lane as a single book-service batch with no runtime changes. * test(stats): cover page count chart bucketing Add non-rendering chart coverage for PageCountChartComponent bucket aggregation, library filtering, and tooltip callbacks. Replay the deferred stats batch into root as a single isolated commit. * test(author-browser): cover author card component flows Add focused AuthorCardComponent coverage for reset behavior, click-mode branching, menu handling, and quick-match paths. * test(book): cover shelf assigner component flows Add dialog-driven ShelfAssignerComponent coverage for filtering, sorting, payload shaping, and success and failure branches. * test(author-browser): cover author detail component flows Add AuthorDetailComponent coverage for loading, overflow state, quick-match updates, and author refresh handling. * test(book): cover add physical book dialog flows Add AddPhysicalBookDialogComponent coverage for metadata hydration, selection behavior, create gating, and success and failure paths. * test(book): cover book sender component flows Add BookSenderComponent coverage for recipient and provider mapping, validation failures, and send success and error behavior. * test(stats): cover language chart aggregation Add non-rendering LanguageChartComponent coverage for aggregation, filtering, shaping, and tooltip behavior. * test(stats): cover metadata score chart states Add MetadataScoreChartComponent coverage for empty and loading states alongside aggregation and tooltip assertions. * test(book): cover book reviews component flows Add BookReviewsComponent coverage for loading, refresh, delete, lock, spoiler, sorting, and helper behavior. * test(book): cover book file attacher flows Add BookFileAttacherComponent coverage for bootstrap, filtering, display helpers, attach behavior, and close paths. * test(stats): cover reading progress chart bucketing Add non-rendering ReadingProgressChartComponent coverage for precedence rules, progress buckets, and tooltip behavior. * test(frontend): fix replay lint and typing cleanup Tighten the replayed specs so the wider frontend lint, typecheck, and test gates pass on the full branch. This keeps the replay window self-contained instead of leaving post-merge cleanup behind. * docs(plans): refresh phase 3 replay ledger Record the replay-window checkpoint, queued worktree batches, and the next accumulation lanes so the coverage swarm can resume cleanly after this cycle. * test(frontend): align stale specs with current behavior - Author card specs: - remove assertions against the deleted `isImageLoaded` state so the tests reflect the component's current photo handling contract - Routing specs: - update series navigation expectations to use raw route segments instead of pre-encoded values, matching the current Angular router usage in both the URL helper and book card flows - Validation: - run targeted Vitest coverage for the touched specs - rerun `just ui typecheck`, `just ui test`, and `just ui check` to confirm the frontend surface is green again * fix(security): align functional guard signatures - Guard contracts: - update the functional auth and permission guards to accept Angular's `CanActivateFn` route and state parameters explicitly - mark the unused parameters with `void` so the implementations stay lint-clean while matching the router contract - Review follow-up: - resolve the PR feedback around superfluous trailing arguments without breaking the existing spec call sites - keep the tests and runtime signatures aligned so the guard family reads consistently across the security surface - Validation: - run `corepack yarn ng test --watch=false --include='src/app/core/security/**/*.spec.ts'` - run `just ui check`, `just ui typecheck`, and `just ui test`
This commit is contained in:
@@ -45,6 +45,9 @@ local-scripts/
|
||||
### Dev config, books, and data ###
|
||||
booklore-ui/test-results/
|
||||
frontend/test-results/
|
||||
frontend/output/
|
||||
frontend/playwright-report/
|
||||
frontend/.playwright-browsers/
|
||||
frontend/node_modules/
|
||||
booklore-api/src/main/resources/application-local.yaml
|
||||
/shared/
|
||||
@@ -54,3 +57,4 @@ booklore-api/src/main/resources/application-local.yaml
|
||||
/frontend/.yarn/
|
||||
/tools/release/node_modules
|
||||
/tools/release/.yarn/
|
||||
.worktrees/
|
||||
|
||||
+14
-20
@@ -29,7 +29,19 @@ services:
|
||||
- ./shared/data:/app/data
|
||||
- ./shared/books:/books
|
||||
- ./shared/bookdrop:/bookdrop
|
||||
|
||||
frontend:
|
||||
image: node:24-alpine
|
||||
command: sh -c "cd /angular-app && corepack enable && corepack yarn install --immutable && corepack yarn ng serve --host 0.0.0.0 --watch --configuration development"
|
||||
environment:
|
||||
- NODE_ENV=development
|
||||
stdin_open: true
|
||||
tty: true
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- './frontend:/angular-app'
|
||||
- node_modules:/angular-app/node_modules
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-4200}:4200"
|
||||
backend_db:
|
||||
image: mariadb:11.4
|
||||
container_name: backend_db
|
||||
@@ -44,28 +56,10 @@ services:
|
||||
ports:
|
||||
- "${DB_PORT:-3366}:3306"
|
||||
healthcheck:
|
||||
test: [ "CMD", "mariadb-admin", "ping", "-h", "localhost", "-uroot", "-pgrimmory" ]
|
||||
test: ["CMD", "mariadb-admin", "ping", "-h", "localhost", "-uroot", "-pgrimmory"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
ui:
|
||||
image: node:24-alpine
|
||||
command: sh -c "cd /angular-app && corepack enable && corepack yarn install --immutable && corepack yarn ng serve --host 0.0.0.0 --watch --configuration development"
|
||||
environment:
|
||||
- NODE_ENV=development
|
||||
stdin_open: true
|
||||
tty: true
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- './frontend:/angular-app'
|
||||
|
||||
# you can have node_modules in a volume. however, if you enable this, expect trouble in some IDEs, as the deps are not available anymore
|
||||
# - node_modules:/angular-app/node_modules
|
||||
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-4200}:4200"
|
||||
|
||||
volumes:
|
||||
node_modules:
|
||||
backend_db:
|
||||
|
||||
@@ -0,0 +1,506 @@
|
||||
# Frontend 90% Coverage Controller Plan
|
||||
|
||||
## Summary
|
||||
|
||||
Drive the frontend to an honest `>=90%` on statements, branches, functions, and lines by attacking the coldest branch-deficit areas first.
|
||||
|
||||
Current baseline on `chore/expand-frontend-tests` after `just ui typecheck`, `just ui lint`, `just ui test`, `just ui coverage`, and `just ui coverage-summary`:
|
||||
- Global: statements `19.98%`, branches `15.25%`, functions `16.57%`, lines `36.00%`
|
||||
- Lane ranking by uncovered branches:
|
||||
- `metadata + settings + stats`: `3200`
|
||||
- `book + author + series + notebook`: `2194`
|
||||
- `readers`: `904`
|
||||
- `shared`: `640`
|
||||
- `core/auth/routes`: `51`
|
||||
|
||||
Operating rules:
|
||||
- No Playwright during the main coverage push
|
||||
- No runtime code changes unless explicitly escalated as a narrow exception
|
||||
- Test workers do not perform Git operations
|
||||
- A dedicated Git/integration worker owns all Git and plan-doc mutations
|
||||
- A dedicated notifier agent owns Pushover notifications
|
||||
- The controller is orchestration-only: it does not generate tests, edit code, commit, integrate changes, or send notifications
|
||||
- Progress toward branch coverage is the primary metric; low-yield churn is grounds for stopping and reassigning work
|
||||
|
||||
## Roles
|
||||
|
||||
### Controller
|
||||
Owns orchestration only:
|
||||
- run pre-flight checks
|
||||
- spawn workers
|
||||
- assign or reassign lanes and target files
|
||||
- poll status
|
||||
- detect anomalies
|
||||
- order stop-all reviews
|
||||
- decide whether a bucket is accepted, narrowed, restarted, or discarded
|
||||
- set coordination flags consumed by the notifier agent
|
||||
|
||||
The controller does not:
|
||||
- edit tests
|
||||
- edit runtime code
|
||||
- update the plan doc directly
|
||||
- run Git commands
|
||||
- salvage large weak buckets by hand
|
||||
- call the Pushover helper directly
|
||||
|
||||
### Git/Integration Worker
|
||||
Owns all repo mutations outside test generation:
|
||||
- create and maintain `.worktrees/`
|
||||
- create worker branches and worktrees
|
||||
- keep `.worktrees/` ignored if needed
|
||||
- update `docs/plans/frontend-90-coverage-plan.md`
|
||||
- inspect `git status`, `git diff --stat`, and worktree health across all worker trees
|
||||
- integrate accepted buckets one at a time
|
||||
- create controller-approved commits with Conventional Commit messages and grouped markdown bodies
|
||||
- prune or recreate discarded worktrees when instructed
|
||||
|
||||
### Notifier Agent
|
||||
Owns all watch/phone notifications through the `pushover-notify` skill:
|
||||
- validate Pushover delivery in pre-flight
|
||||
- send a periodic high-level status summary every 5 minutes
|
||||
- send immediate human-needed alerts only when the controller explicitly marks the run as requiring the user to return
|
||||
- never send noisy per-test spam
|
||||
- never inspect or mutate Git state directly
|
||||
- repeating summary and escalation behavior should be driven by one controller-owned loop, not repeated per-agent commands; use a temporary local script under `local-scripts/` when a cadence is needed
|
||||
|
||||
### Test Workers
|
||||
Own one lane each and only touch tests plus test-local helpers within owned paths unless explicitly escalated:
|
||||
1. `core/auth/routes`
|
||||
2. `book + author + series + notebook`
|
||||
3. `metadata + settings + stats`
|
||||
4. `readers`
|
||||
5. `shared`
|
||||
|
||||
Test workers do not:
|
||||
- run Git commands
|
||||
- edit the plan doc
|
||||
- integrate other workers’ work
|
||||
- drift into Playwright or harness churn
|
||||
|
||||
## Pre-Flight Phase
|
||||
|
||||
Before any worker launch, the controller must prove the run can proceed unattended.
|
||||
|
||||
### Pre-flight checks
|
||||
1. Confirm the branch and repo state are readable and sane.
|
||||
- `git -C /Users/james/Projects/grimmory/grimmory status --short --branch`
|
||||
- `git -C /Users/james/Projects/grimmory/grimmory worktree list`
|
||||
- record any pre-existing untracked or unrelated files so they are not mistaken for worker drift
|
||||
|
||||
2. Confirm the durable plan path exists.
|
||||
- `docs/plans/frontend-90-coverage-plan.md` must be present and writable by the Git/integration worker
|
||||
|
||||
3. Confirm worktree support is usable.
|
||||
- `.gitignore` must contain `.worktrees/`
|
||||
- if `.worktrees/` does not yet exist, that is acceptable; the Git worker creates it later
|
||||
|
||||
4. Confirm Git capabilities are available without interactive approval.
|
||||
- repo-local `git -C /Users/james/Projects/grimmory/grimmory ...` commands must succeed
|
||||
- if branch creation or worktree creation requires approval, do not launch workers
|
||||
|
||||
5. Confirm the frontend command surface is usable.
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- `just ui coverage`
|
||||
- `just ui coverage-summary`
|
||||
- any failure here blocks launch until the controller re-baselines and updates the plan
|
||||
|
||||
6. Confirm coordination transport is available.
|
||||
- preferred: `valkey-cli ping` must return `PONG`
|
||||
- fallback: if Valkey is unavailable, switch to controller polling via agent messages only
|
||||
- if neither Valkey nor reliable agent polling is available, do not launch unattended
|
||||
|
||||
7. Confirm notifier capability is available and working.
|
||||
- `PUSHOVER_APP_TOKEN` and `PUSHOVER_USER_KEY` must be present
|
||||
- notifier agent runs the skill-local helper once with `--dry-run`
|
||||
- notifier agent then sends one real low-noise pre-flight notification
|
||||
- if real delivery cannot be confirmed, unattended launch is blocked
|
||||
|
||||
8. Confirm worker lanes are disjoint and target lists are current.
|
||||
- regenerate the branch-deficit ranking from current coverage output
|
||||
- verify each initial target file belongs to exactly one lane
|
||||
|
||||
9. Confirm the Git/integration worker can own the repo-mutating path end to end.
|
||||
- create worktrees
|
||||
- inspect diffs
|
||||
- update plan doc
|
||||
- commit accepted buckets
|
||||
- if any of these are uncertain, do not start the swarm
|
||||
|
||||
### Pre-flight output
|
||||
The controller must produce a launch record in the plan doc via the Git/integration worker containing:
|
||||
- timestamp
|
||||
- baseline coverage totals
|
||||
- lane ranking by uncovered branches
|
||||
- capability results for Git, Just, Valkey, and Pushover
|
||||
- known pre-existing repo noise
|
||||
- explicit `launch approved` or `launch blocked`
|
||||
|
||||
### Launch blockers
|
||||
Do not launch workers if any of the following are true:
|
||||
- Git repo-local commands are not usable without approval
|
||||
- the plan doc cannot be updated
|
||||
- frontend baseline commands are failing
|
||||
- coordination transport is unavailable
|
||||
- Pushover delivery cannot be validated
|
||||
- lane ownership is ambiguous
|
||||
- current repo state is too noisy to distinguish worker drift from pre-existing changes
|
||||
|
||||
## Launch Record
|
||||
|
||||
- Status: pre-flight completed, swarm narrowed after incident review
|
||||
- Branch: `chore/expand-frontend-tests`
|
||||
- Repo state: root currently carries the metadata-viewer integration checkpoint and this plan-doc refresh draft
|
||||
- Current HEAD: `97019536`
|
||||
- Prior metadata checkpoint HEAD: `d3f05207`
|
||||
- Worktree list:
|
||||
- `/Users/james/Projects/grimmory/grimmory`
|
||||
- `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-book-author-series-notebook`
|
||||
- `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-core-auth-routes`
|
||||
- `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-metadata-settings-stats`
|
||||
- `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-readers`
|
||||
- `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-shared`
|
||||
- `.worktrees/` ignore rule: present in `.gitignore`
|
||||
- Historical pre-existing repo noise to record: `booklore-ui-migration-prompt.md`
|
||||
- Notification state: paused pending the single local loop restart; the loop uses `/tmp/f90-status-loop.lock` and `local-scripts/.f90-status-loop.pid`
|
||||
- Root integration state:
|
||||
- HEAD `97019536`
|
||||
- ahead of `origin/chore/expand-frontend-tests` by 11 commits
|
||||
- integrated buckets: `core/auth/routes`, `bookdrop`, `readers(selection-service only)`, `metadata-viewer`, `book-card`, `shared(url-helper)`, `author-browser`
|
||||
- Current combined root coverage checkpoint:
|
||||
- global: statements `24.75%`, branches `19.73%`, functions `20.24%`, lines `38.79%`
|
||||
- Recent root-side batch:
|
||||
- `bedcc3b0` `test(readers): stabilize ebook event service spec`
|
||||
- `9e20879e` `test(book): cover book card decision paths`
|
||||
- `e4a37866` `test(shared): cover url helper routing fallbacks`
|
||||
- Current coverage-summary highlights:
|
||||
- `features/metadata`: statements `42.87%`, branches `23.68%`, functions `34.48%`, lines `45.4%`
|
||||
- `features/readers`: statements `33.5%`, branches `26.88%`, functions `31.74%`, lines `44.37%`
|
||||
- `features/book`: statements `21.86%`, branches `19%`, functions `15.3%`, lines `51.63%`
|
||||
- `shared`: statements `22.96%`, branches `13.28%`, functions `19.9%`, lines `54.75%`
|
||||
- `features/author-browser`: statements `7.86%`, branches `2.96%`, functions `7.59%`, lines `8.58%`
|
||||
- Metadata batch acceptance:
|
||||
- accepted file: `frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts`
|
||||
- measured lane branch movement: `metadata + settings + stats` to `13.08%` branches (`464/3548`), `3084` uncovered
|
||||
- measured file branch movement: `metadata-viewer.component.ts` to `38.28%` branches (`116/303`)
|
||||
- Restart lanes available for the next wave:
|
||||
- `metadata + settings + stats`
|
||||
- `readers`
|
||||
- `shared`
|
||||
|
||||
### Incident Log
|
||||
|
||||
- A nonstandard initial worktree setup was detected during launch prep.
|
||||
- The root checkout remained normal throughout the incident and was not modified outside standard repo-local git operations.
|
||||
- Malformed `.worktrees/` admin copies were removed safely.
|
||||
- The lane worktrees were recreated successfully with standard `git worktree add` flows under `/Users/james/Projects/grimmory/grimmory/.worktrees/`.
|
||||
- The first notifier path generated false-positive "return to machine" alerts; notifications are paused until the single local loop is restarted.
|
||||
- The shared lane polluted the root checkout with untracked shared specs, so that batch was discarded.
|
||||
- The broken `metadata`, `readers`, and `shared` lane worktrees were cleaned and recreated from the current root HEAD for restart.
|
||||
- The preserved `core/auth` worktree edits remain available for later integration.
|
||||
- The accepted metadata viewer batch was then integrated directly in the root checkout and recorded as the current integration checkpoint.
|
||||
- The root-side readers/book/shared batch was then committed in sequence from the root checkout and the plan checkpoint refreshed again afterward.
|
||||
|
||||
### Stop-All Review
|
||||
|
||||
- Malformed initial worktree setup incident: nonstandard `.worktrees/` admin copies were detected and repaired before lane launch continued.
|
||||
- Second incident: shared lane edits landed in the root checkout instead of the shared worktree, which polluted the root with untracked shared specs.
|
||||
- Decision:
|
||||
- discard the shared batch
|
||||
- preserve the core/auth worktree edits for later integration
|
||||
- keep the broken metadata/readers/shared worktrees cleaned and recreated for restart
|
||||
- restart later only with stricter worktree-path instructions, tighter drift checks, and the notifier still paused unless the local loop is explicitly started
|
||||
|
||||
## Current Integration Checkpoint
|
||||
|
||||
- Root HEAD: `97019536`
|
||||
- Root branch status: ahead of `origin/chore/expand-frontend-tests` by 11 commits
|
||||
- Integrated and validated buckets so far:
|
||||
- `core/auth/routes`
|
||||
- `bookdrop`
|
||||
- `readers(selection-service only)`
|
||||
- `metadata-viewer`
|
||||
- Recent root-side commits:
|
||||
- `bedcc3b0` `test(readers): stabilize ebook event service spec`
|
||||
- `9e20879e` `test(book): cover book card decision paths`
|
||||
- `e4a37866` `test(shared): cover url helper routing fallbacks`
|
||||
- Root tip also includes:
|
||||
- `97019536` `test(author-browser): cover author service control flow`
|
||||
- Accepted metadata batch checkpoint:
|
||||
- commit: `d3f05207` `test(metadata-viewer): cover metadata viewer branches`
|
||||
- changed file: `frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts`
|
||||
- validation already completed in root: focused spec, typecheck, lint, test, coverage, coverage-summary
|
||||
- Measured metadata movement:
|
||||
- global: statements `23.00%`, branches `17.94%`, functions `19.49%`, lines `38.37%`
|
||||
- `metadata-viewer.component.ts`: branches `38.28%` (`116/303`)
|
||||
- `metadata/settings/stats`: branches `13.08%` (`464/3548`), uncovered `3084`
|
||||
- Current combined root coverage checkpoint:
|
||||
- statements `24.75%`
|
||||
- branches `19.73%`
|
||||
- functions `20.24%`
|
||||
- lines `38.79%`
|
||||
- Recreated restart lanes:
|
||||
- `metadata + settings + stats`
|
||||
- `readers`
|
||||
- `shared`
|
||||
- Notification state:
|
||||
- single local loop is the only allowed status/notification driver
|
||||
- lock file: `/tmp/f90-status-loop.lock`
|
||||
- pid file: `local-scripts/.f90-status-loop.pid`
|
||||
- notifications remain paused until the loop is deliberately restarted
|
||||
- Next immediate action:
|
||||
- restart the `book + author + series + notebook` lane on `author-browser` next, since coverage-summary still shows that bucket as the coldest branch surface; if that proves too broad, fall back to `metadata + settings + stats` starting at `metadata-searcher.component.ts`
|
||||
|
||||
## Lane Ownership And First Targets
|
||||
|
||||
### `metadata + settings + stats`
|
||||
Highest-yield first wave.
|
||||
Primary targets:
|
||||
- `features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts`
|
||||
- `features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts`
|
||||
- `features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts`
|
||||
- `features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.ts`
|
||||
- `features/settings/task-management/task-management.component.ts`
|
||||
- `features/stats/component/user-stats/charts/series-progress-chart/series-progress-chart.component.ts`
|
||||
- `features/stats/component/library-stats/charts/author-universe-chart/author-universe-chart.component.ts`
|
||||
- `features/settings/view-preferences-parent/view-preferences/view-preferences.component.ts`
|
||||
|
||||
### `book + author + series + notebook`
|
||||
Includes book-adjacent cold areas.
|
||||
Primary targets:
|
||||
- `features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.ts`
|
||||
- `features/book/components/book-browser/book-card/book-card.component.ts`
|
||||
- `features/author-browser/components/author-browser/author-browser.component.ts`
|
||||
- `features/book/components/book-browser/book-browser.component.ts`
|
||||
- `features/book/components/series-page/series-page.component.ts`
|
||||
- `features/book/components/book-browser/book-table/book-table.component.ts`
|
||||
- `features/library-creator/library-creator.component.ts`
|
||||
|
||||
### `readers`
|
||||
Prioritize control-flow-heavy reader surfaces before shallow shells.
|
||||
Primary targets:
|
||||
- `features/readers/cbx-reader/cbx-reader.component.ts`
|
||||
- `features/readers/audiobook-player/audiobook-player.component.ts`
|
||||
- `features/readers/ebook-reader/core/event.service.ts`
|
||||
- `features/readers/ebook-reader/ebook-reader.component.ts`
|
||||
- `features/readers/ebook-reader/features/selection/selection.service.ts`
|
||||
- `features/readers/pdf-reader/pdf-reader.component.ts`
|
||||
|
||||
### `shared`
|
||||
Keep as an explicit lane because it is still materially behind.
|
||||
Primary targets:
|
||||
- `shared/components/file-mover/file-mover-component.ts`
|
||||
- `shared/components/book-uploader/book-uploader.component.ts`
|
||||
- `shared/layout/component/layout-menu/app.menu.component.ts`
|
||||
- `shared/service/url-helper.service.ts`
|
||||
- `shared/components/icon-picker/icon-picker-component.ts`
|
||||
- `shared/service/reading-session.service.ts`
|
||||
- `shared/service/audiobook-session.service.ts`
|
||||
|
||||
### `core/auth/routes`
|
||||
Smallest lane, good candidate for an early clean win.
|
||||
Primary targets:
|
||||
- `core/security/oauth2-management/authentication-settings.component.ts`
|
||||
- any remaining branch gaps in `core/custom-reuse-strategy.ts`
|
||||
- any remaining branch gaps in `core/services/loading.service.ts`
|
||||
- any remaining branch gaps in `core/security/auth-interceptor.service.ts`
|
||||
- any remaining branch gaps in `core/security/secure-src.directive.ts`
|
||||
|
||||
## Status And Communication Protocol
|
||||
|
||||
Use a controller-visible heartbeat protocol so unattended runs can be supervised without passive waiting.
|
||||
|
||||
### Status transport
|
||||
Default:
|
||||
- each test worker writes heartbeat and progress records to Valkey using a finite TTL namespace like `codex:grimmory:f90:<lane>:status`
|
||||
- the Git/integration worker writes per-worktree Git snapshots to `codex:grimmory:f90:git:<lane>`
|
||||
- the controller writes orchestration state to keys like:
|
||||
- `codex:grimmory:f90:controller:summary`
|
||||
- `codex:grimmory:f90:controller:human_needed`
|
||||
- `codex:grimmory:f90:controller:launch_state`
|
||||
- the notifier agent reads only those shared coordination keys plus lane summaries
|
||||
- if periodic polling or notification must run continuously, prefer a single controller-owned temporary script over repeated agent shell calls
|
||||
|
||||
Fallback if Valkey is unavailable:
|
||||
- workers send progress messages to the controller thread and the controller relays summary state to the notifier agent through direct agent messages
|
||||
|
||||
### Test worker heartbeat payload
|
||||
Emit on start, after target selection, after each meaningful test batch, after each validation run, on block, and before handoff.
|
||||
Required fields:
|
||||
- `lane`
|
||||
- `owned_paths`
|
||||
- `current_targets`
|
||||
- `state`: one of `surveying`, `writing_tests`, `running_targeted`, `running_validation`, `ready_for_handoff`, `blocked`, `aborted`
|
||||
- `spec_files_touched`
|
||||
- `last_targeted_command`
|
||||
- `last_targeted_result`
|
||||
- `last_validation_commands`
|
||||
- `last_validation_results`
|
||||
- `latest_observed_coverage_signal`
|
||||
- `residual_risks`
|
||||
- `updated_at`
|
||||
|
||||
Coverage signal should be lightweight and frequent:
|
||||
- at minimum, report target-file count and targeted-test pass/fail
|
||||
- after any substantial batch, report owned-file coverage movement from local coverage output if available
|
||||
- do not run expensive full coverage repeatedly just to emit heartbeats
|
||||
|
||||
### Git worker snapshot payload
|
||||
Emit on a fixed polling cadence for every worktree.
|
||||
Required fields:
|
||||
- `lane`
|
||||
- `worktree_path`
|
||||
- `branch`
|
||||
- `git_status_short`
|
||||
- `diff_stat`
|
||||
- `changed_files`
|
||||
- `plan_doc_state`
|
||||
- `updated_at`
|
||||
|
||||
### Notifier behavior
|
||||
Periodic summary:
|
||||
- every 5 minutes
|
||||
- low-noise, high-level only
|
||||
- include current global coverage if available, active lanes, lanes ready for handoff, stalled lanes, and whether the run is healthy or in review
|
||||
- prefer compact multiline messages through stdin; use `--title "Codex"` and `--monospace` when formatting helps
|
||||
|
||||
Immediate human-needed alerts:
|
||||
- send only when the controller explicitly marks `human_needed=true`
|
||||
- examples:
|
||||
- pre-flight blocked
|
||||
- notification path broken
|
||||
- Git/worktree operations unexpectedly require approval
|
||||
- ambiguous repo state needs human judgment
|
||||
- all viable lanes stalled after stop-all review
|
||||
- a runtime-code exception appears necessary
|
||||
- use a more attention-grabbing notification than the periodic summary, but do not use emergency retry mode unless absolutely necessary
|
||||
|
||||
### Polling cadence
|
||||
- Controller polls heartbeats every 5 minutes
|
||||
- Git worker snapshots each worktree every 3 to 5 minutes
|
||||
- Notifier agent sends a periodic summary every 5 minutes
|
||||
- Any worker heartbeat older than 10 minutes is stale
|
||||
- Any lane with repeated stale heartbeats triggers review
|
||||
|
||||
## Acceptance Criteria Per Test Worker Bucket
|
||||
|
||||
A bucket is handoff-ready only if all conditions hold:
|
||||
- touched files stay within owned lane
|
||||
- no runtime code change unless explicitly escalated and isolated
|
||||
- targeted tests for the owned area pass via the Just command surface
|
||||
- `just ui typecheck` passes
|
||||
- `just ui lint` passes
|
||||
- `just ui test` passes
|
||||
- worker emits final handoff payload including:
|
||||
- changed files
|
||||
- commands run and results
|
||||
- residual risks or known gaps
|
||||
- proposed Conventional Commit subject
|
||||
- proposed grouped markdown commit body
|
||||
|
||||
Test workers should prefer root commands:
|
||||
- `just ui ...`
|
||||
Or, when working inside the frontend subtree:
|
||||
- `just --justfile frontend/Justfile --working-directory frontend ...`
|
||||
|
||||
No direct Yarn commands in worker instructions.
|
||||
|
||||
## Controller Intervention Rules
|
||||
|
||||
The controller should over-index on intervention rather than waiting for an unobtainable goal.
|
||||
|
||||
Trigger a stop-all review when any of these occur:
|
||||
- a worker heartbeat goes stale
|
||||
- Git snapshot shows cross-lane file drift
|
||||
- a worker accumulates a large diff without passing validation
|
||||
- a worker reports repeated validation failures on the same bucket
|
||||
- a worker has multiple test batches with no credible coverage movement
|
||||
- Git state looks anomalous or inconsistent across worktrees
|
||||
- a worker starts chasing decorative render coverage instead of branch-bearing logic
|
||||
|
||||
Default low-yield threshold:
|
||||
- if two successive meaningful batches do not materially reduce the lane’s target-file branch deficit, stop and review
|
||||
- “materially” means visible improvement in the current target cluster, not just more tests added
|
||||
|
||||
Stop-all review sequence:
|
||||
1. Controller interrupts all test workers.
|
||||
2. Git worker captures final status and diff snapshots for every worktree.
|
||||
3. Controller classifies each lane as:
|
||||
- `keep and integrate`
|
||||
- `keep but narrow`
|
||||
- `restart with new targets`
|
||||
- `discard`
|
||||
4. Git worker updates the plan doc with the review outcome.
|
||||
5. Controller updates the shared summary state.
|
||||
6. Notifier agent sends the next periodic summary reflecting the review outcome.
|
||||
7. If human judgment is required, controller sets `human_needed=true` and notifier sends an immediate alert.
|
||||
8. Controller restarts only the lanes that still have a defensible next move.
|
||||
|
||||
Throwing away weak progress is acceptable. Avoid salvage rabbit holes.
|
||||
|
||||
## Integration Workflow
|
||||
|
||||
The Git/integration worker, under controller direction, performs all integration.
|
||||
|
||||
Per accepted bucket:
|
||||
1. verify handoff payload completeness
|
||||
2. inspect worktree Git state and changed-file scope
|
||||
3. integrate one bucket only
|
||||
4. create one Conventional Commit for that bucket
|
||||
5. run:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
6. after every two integrations, or sooner for a large bucket, run:
|
||||
- `just ui coverage`
|
||||
- `just ui coverage-summary`
|
||||
7. update `docs/plans/frontend-90-coverage-plan.md` with:
|
||||
- current totals
|
||||
- lane totals
|
||||
- accepted bucket
|
||||
- discarded or restarted buckets
|
||||
- next target shortlist
|
||||
8. publish the updated high-level status for the notifier agent
|
||||
|
||||
Default integration order by expected branch gain:
|
||||
1. `metadata + settings + stats`
|
||||
2. `book + author + series + notebook`
|
||||
3. `readers`
|
||||
4. `shared`
|
||||
5. `core/auth/routes`
|
||||
|
||||
## Plan Doc Requirements
|
||||
|
||||
The plan doc is durable session state and must always be resumable without ambiguity.
|
||||
|
||||
After baseline, after pre-flight, and after every accepted integration or stop-all review, it must contain:
|
||||
- latest global coverage numbers
|
||||
- latest lane ranking by uncovered branches
|
||||
- active workers and owned paths
|
||||
- current top target files per lane
|
||||
- accepted buckets and commit subjects
|
||||
- rejected buckets and why they were rejected
|
||||
- open blockers and whether any runtime exception was approved
|
||||
- latest launch record
|
||||
- latest notification state
|
||||
- next immediate actions
|
||||
|
||||
The Git/integration worker owns these updates. The controller decides the content.
|
||||
|
||||
## Next Immediate Actions
|
||||
|
||||
1. Restart the `book + author + series + notebook` lane on `author-browser` next, since coverage-summary still shows that bucket as the coldest branch surface; if that proves too broad, fall back to `metadata + settings + stats` starting at `metadata-searcher.component.ts`.
|
||||
2. Keep the notifier paused until the single local loop is deliberately restarted with tighter incident-only thresholds.
|
||||
3. Re-rank the remaining cold lanes from the current coverage totals, still prioritizing branch deficit first.
|
||||
4. Preserve the clean worktrees as the new controller baseline and keep the discarded shared batch out of rotation.
|
||||
5. Commit this durable plan checkpoint after the metadata batch integration so later sessions can resume from the updated root truth.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The new `default.rules` entries are sufficient for repo-local Git operations under `git -C /Users/james/Projects/grimmory/grimmory`
|
||||
- No escalated privileges will be available during the unattended run
|
||||
- Test workers can rely on Just-based validation only
|
||||
- Valkey is preferred for transient coordination and is currently available
|
||||
- The `pushover-notify` skill helper is available and Pushover credentials are present in the environment
|
||||
- The controller remains orchestration-only for the full run, including during failures and reviews
|
||||
@@ -0,0 +1,266 @@
|
||||
# Frontend Coverage Phase 2: Harness-First Supervised Swarm
|
||||
|
||||
## Summary
|
||||
|
||||
Drive the next frontend coverage phase from reusable test harnesses instead of one-off spec rescue work.
|
||||
|
||||
Validated baseline on `chore/expand-frontend-tests`:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- `just ui coverage-summary`
|
||||
|
||||
Current baseline:
|
||||
- statements `32.84%`
|
||||
- branches `24.95%`
|
||||
- functions `28.56%`
|
||||
- lines `48.10%`
|
||||
|
||||
Current skipped-spec distribution:
|
||||
- `features/stats`: `32`
|
||||
- `features/settings`: `26`
|
||||
- `features/book`: `25`
|
||||
- `features/readers`: `15`
|
||||
- `shared`: `12`
|
||||
- `features/metadata`: `7`
|
||||
- `features/author-browser`: `6`
|
||||
|
||||
Operating rules for this phase:
|
||||
- no runtime code changes without explicit approval
|
||||
- solve the next wave in the test harness first
|
||||
- git operations stay in one thread only
|
||||
- the controller is orchestration-only
|
||||
- branch coverage gain is the primary metric
|
||||
- mature packages are preferred when they clearly replace bespoke harness code
|
||||
|
||||
## Step 0
|
||||
|
||||
This file is the new execution plan for the phase.
|
||||
|
||||
Do not mutate `docs/plans/frontend-90-coverage-plan.md` except for cross-reference or historical context.
|
||||
|
||||
Each execution checkpoint appended here must record:
|
||||
- timestamp
|
||||
- current branch totals from `just ui coverage-summary`
|
||||
- accepted harness families
|
||||
- worker roster and lane ownership
|
||||
- accepted bucket list
|
||||
- blocked seam list
|
||||
|
||||
## Checkpoints
|
||||
|
||||
### 2026-03-27 16:36:07 CDT
|
||||
|
||||
Current branch totals from `just ui coverage-summary`:
|
||||
- statements `33.60%`
|
||||
- branches `25.28%`
|
||||
- functions `29.59%`
|
||||
- lines `48.65%`
|
||||
|
||||
Accepted harness families:
|
||||
- query/auth/signal bootstrap via `createQueryClientHarness()` and `createAuthServiceStub(...)`
|
||||
- non-rendering chart bootstrap via `nextChartEmission(...)` and `fakeChartTooltipContext(...)`
|
||||
- dialog/form bootstrap via `createDynamicDialogHarness(...)` and message-service helpers
|
||||
|
||||
Worker roster and lane ownership for this bootstrap run:
|
||||
- controller: local single-owner execution only
|
||||
- harness lane: `frontend/src/app/core/testing/{query-testing,chart-testing,dialog-testing}.ts`
|
||||
- query/service canaries: `AppSettingsService`, `LibraryService`
|
||||
- chart canary: `GenreStatsChartComponent`
|
||||
- dialog canary: `AuthorPhotoSearchComponent`
|
||||
|
||||
Accepted bucket list:
|
||||
- add `ng-mocks`
|
||||
- publish shared bootstrap helpers for query, chart, and dialog seams
|
||||
- convert four skipped canaries into active specs
|
||||
- validate with `just ui typecheck`, `just ui lint`, `just ui test`, `just ui coverage`, and `just ui coverage-summary`
|
||||
|
||||
Blocked seam list:
|
||||
- none in the accepted bootstrap set
|
||||
|
||||
## Harness Families
|
||||
|
||||
### 1. Query/Auth/Signal Harness
|
||||
|
||||
Purpose:
|
||||
- cover eager `injectQuery(...)`
|
||||
- control auth-token enablement
|
||||
- assert computed loading and error state
|
||||
- assert cache invalidation and token-cleared removal
|
||||
|
||||
Shared helpers:
|
||||
- `createQueryClientHarness()`
|
||||
- `createAuthServiceStub(initialToken)`
|
||||
- `flushSignalAndQueryEffects()`
|
||||
- `createSignalFacade(...)`
|
||||
|
||||
First canaries:
|
||||
- `AppSettingsService`
|
||||
- `LibraryService`
|
||||
|
||||
### 2. Non-Rendering Chart Harness
|
||||
|
||||
Purpose:
|
||||
- assert derived chart datasets
|
||||
- assert summary fields
|
||||
- assert tooltip and label callbacks
|
||||
- avoid live chart rendering as the main assertion surface
|
||||
|
||||
Shared helpers:
|
||||
- `createChartTranslocoStub()`
|
||||
- `nextChartEmission(...)`
|
||||
- `fakeChartTooltipContext(...)`
|
||||
|
||||
First canary:
|
||||
- `GenreStatsChartComponent`
|
||||
|
||||
### 3. Dialog/Form Harness
|
||||
|
||||
Purpose:
|
||||
- standardize `DynamicDialogConfig` and `DynamicDialogRef`
|
||||
- standardize message and confirmation spies
|
||||
- standardize PrimeNG event payload stubs
|
||||
- standardize fake-timer flows for dialog lifecycle
|
||||
|
||||
Shared helpers:
|
||||
- `createDynamicDialogHarness(data)`
|
||||
- `createMessageServiceSpy()`
|
||||
- `createConfirmServiceSpy()`
|
||||
|
||||
First canary:
|
||||
- `AuthorPhotoSearchComponent`
|
||||
|
||||
### 4. Route/Timer/Host-Event Harness
|
||||
|
||||
Purpose:
|
||||
- query-param syncing
|
||||
- router navigation doubles
|
||||
- debounced search
|
||||
- document click and host-listener control
|
||||
|
||||
### 5. Reader Wrapper Harness
|
||||
|
||||
Purpose:
|
||||
- cover reader header, sidebar, panel, quick-settings, and settings wrappers
|
||||
- explicitly exclude full reader runtimes
|
||||
|
||||
## Package Posture
|
||||
|
||||
Default package stance:
|
||||
- use mature libraries when they directly match the seam and reduce bespoke mocking
|
||||
- use repo-local helpers only for repo-specific state wiring and tiny adapter glue
|
||||
|
||||
Immediate package decisions:
|
||||
- standardize `@testing-library/angular`
|
||||
- standardize `@testing-library/user-event`
|
||||
- keep `jsdom`
|
||||
- keep `vitest-canvas-mock`
|
||||
- keep `msw` as secondary, not primary, for Angular service flows
|
||||
- add `ng-mocks` early for standalone and PrimeNG-heavy shell work
|
||||
|
||||
## Attack Order
|
||||
|
||||
1. `features/stats`
|
||||
- highest branch upside with one reusable chart family
|
||||
- hold plugin and imperative canvas outliers until later
|
||||
2. query-backed services across `shared`, `features/settings`, `features/book`, and `features/magic-shelf`
|
||||
3. dialog and form specs across `features/book`, `features/bookdrop`, `features/author-browser`, and selected `features/metadata`
|
||||
4. reader wrapper specs only
|
||||
5. settings and shared shells that can reuse the proven signal and route harnesses
|
||||
|
||||
Deferred hold bucket:
|
||||
- shared layout and menu shells
|
||||
- author-browser page shell
|
||||
- full reader runtimes
|
||||
- view-manager and similar runtime seams
|
||||
|
||||
## Worker Model
|
||||
|
||||
Phase 0:
|
||||
- one harness owner only
|
||||
- no swarm until the controller accepts the shared conventions
|
||||
|
||||
Phase 1:
|
||||
- one controller
|
||||
- one git and integration lieutenant
|
||||
- one notify lieutenant
|
||||
- one harness-generation worker
|
||||
- up to three spec-generation workers
|
||||
|
||||
Hard rules:
|
||||
- only git and integration runs git commands
|
||||
- only notify uses Pushover
|
||||
- only harness-generation edits shared helper files
|
||||
- spec workers consume published harnesses and do not invent competing ones
|
||||
|
||||
## Communication Spec
|
||||
|
||||
The controller is assertive and supervises every worker, including git and notify.
|
||||
|
||||
Worker heartbeat:
|
||||
- target every `2-3` minutes
|
||||
- absolute maximum `5` minutes
|
||||
- immediate extra message on `start`, `blocked`, `handoff`, `needs-decision`, `done`, or `drift-detected`
|
||||
|
||||
Worker status format:
|
||||
- `state | owned_paths | current_target | last_result | blocker | next_10m`
|
||||
|
||||
Allowed `state` values:
|
||||
- `bootstrapping`
|
||||
- `implementing`
|
||||
- `validating`
|
||||
- `blocked`
|
||||
- `handoff-ready`
|
||||
- `stopped`
|
||||
|
||||
Controller reply format:
|
||||
- `decision | scope | priority | continue_until | stop_condition`
|
||||
|
||||
The controller interrupts immediately when:
|
||||
- a heartbeat exceeds `5` minutes
|
||||
- a status report is vague
|
||||
- a worker touches unowned paths
|
||||
- a worker proposes runtime edits without approval
|
||||
- a worker continues low-yield work after a stop signal
|
||||
|
||||
## Stop and Recovery Rules
|
||||
|
||||
Harness canary window:
|
||||
- `15-20` minutes maximum per family
|
||||
|
||||
Stop a harness spike when:
|
||||
- it does not unlock one real spec and one near-neighbor candidate inside the window
|
||||
|
||||
Stop a lane when:
|
||||
- two consecutive specs need bespoke lane-only mocks
|
||||
- the worker edits outside the owned write set
|
||||
- the worker reports no branch-relevant progress for one heartbeat cycle
|
||||
- the worker proposes runtime changes without escalation
|
||||
|
||||
Recovery:
|
||||
- classify the blocker as `blocked-by-harness`, `blocked-by-runtime-seam`, or `blocked-by-package-gap`
|
||||
- record the exact seam here
|
||||
- let git and integration quarantine or discard the batch
|
||||
- do not let the controller salvage the bucket by doing implementation work
|
||||
|
||||
## Validation
|
||||
|
||||
Per bootstrap canary:
|
||||
- focused spec
|
||||
- `just ui typecheck`
|
||||
|
||||
Per accepted bucket:
|
||||
- focused spec slice
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui coverage-summary`
|
||||
|
||||
Checkpoint gates:
|
||||
- `just ui test`
|
||||
|
||||
Phase close:
|
||||
- `just ui coverage`
|
||||
- `just ui coverage-summary`
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
@@ -0,0 +1,383 @@
|
||||
# Frontend Coverage Phase 3: Lieutenants Swarm
|
||||
|
||||
## Summary
|
||||
|
||||
This phase moves from bootstrap into supervised multi-lane execution.
|
||||
|
||||
Operating model:
|
||||
- controller: orchestration only
|
||||
- gitops lieutenant: all git, worktrees, staging, commits, and integration
|
||||
- notify lieutenant: all Pushover communication through `$pushover-notify`
|
||||
- workers: tightly bounded lane work only
|
||||
|
||||
Current baseline at phase start on `chore/expand-frontend-tests` (`HEAD 111466b5`):
|
||||
- statements `33.60%`
|
||||
- branches `25.28%`
|
||||
- functions `29.59%`
|
||||
- lines `48.65%`
|
||||
|
||||
Current skipped-spec distribution:
|
||||
- `features/stats`: `31`
|
||||
- `features/settings`: `26`
|
||||
- `features/book`: `24`
|
||||
- `features/readers`: `15`
|
||||
- `shared`: `11`
|
||||
- `features/metadata`: `7`
|
||||
- `features/author-browser`: `5`
|
||||
- `features/bookdrop`: `4`
|
||||
|
||||
Hard constraints:
|
||||
- no runtime code changes without explicit approval
|
||||
- git operations stay in one thread only
|
||||
- notifications are mandatory and plain English
|
||||
- workers may do seam work, but only within a short, high-yield budget
|
||||
- branch coverage gain is the primary metric
|
||||
|
||||
## Step 0
|
||||
|
||||
This file is the execution artifact for the lieutenants swarm phase.
|
||||
|
||||
Do not reuse:
|
||||
- `docs/plans/frontend-90-coverage-plan.md`
|
||||
- `docs/plans/frontend-coverage-phase-2-supervised-swarm.md`
|
||||
|
||||
Every checkpoint appended here must record:
|
||||
- timestamp
|
||||
- active lanes
|
||||
- accepted batch
|
||||
- coverage totals
|
||||
- bucket-level movement
|
||||
- worker stop or replacement events
|
||||
- blocked seams
|
||||
|
||||
## Worktree Model
|
||||
|
||||
Use a new worktree prefix for this phase:
|
||||
- `.worktrees/covswarm-stats`
|
||||
- `.worktrees/covswarm-query`
|
||||
- `.worktrees/covswarm-dialog`
|
||||
- `.worktrees/covswarm-harness` only if a dedicated shared-helper lane becomes necessary
|
||||
|
||||
Legacy `f90-*` worktrees:
|
||||
- preserve and ignore
|
||||
- snapshot their status once during pre-flight
|
||||
- do not edit them
|
||||
- do not clean them up during this phase
|
||||
|
||||
## Role Contract
|
||||
|
||||
### Controller
|
||||
|
||||
Responsibilities:
|
||||
- launch and stop agents
|
||||
- assign lanes and write scopes
|
||||
- enforce heartbeats
|
||||
- accept or reject worker batches
|
||||
- tell gitops when to integrate
|
||||
- tell notify when to send normal and urgent messages
|
||||
|
||||
Not allowed:
|
||||
- no code edits
|
||||
- no git
|
||||
- no notifications
|
||||
|
||||
### Gitops Lieutenant
|
||||
|
||||
Responsibilities:
|
||||
- verify git write access before lane launch
|
||||
- create and manage `covswarm-*` branches and worktrees
|
||||
- snapshot root and legacy worktree state
|
||||
- stage accepted lane changes
|
||||
- create conventional commits
|
||||
- integrate accepted lane commits into the root branch
|
||||
- quarantine or discard failed lane worktrees
|
||||
|
||||
Not allowed:
|
||||
- no test implementation
|
||||
- no runtime code edits
|
||||
- no notifications
|
||||
|
||||
### Notify Lieutenant
|
||||
|
||||
Responsibilities:
|
||||
- verify Pushover credentials
|
||||
- run `$pushover-notify --dry-run` pre-flight
|
||||
- send all progress and escalation messages
|
||||
|
||||
Normal-priority events:
|
||||
- swarm launch
|
||||
- bootstrap handoff
|
||||
- lane launch
|
||||
- worker stopped or replaced
|
||||
- checkpoint update
|
||||
- integration complete
|
||||
- coverage moved
|
||||
- final completion
|
||||
|
||||
Urgent events:
|
||||
- blocker requiring a decision
|
||||
- runtime change would be needed
|
||||
- permission problem stops the swarm
|
||||
- repeated worker-runtime failure
|
||||
- controller halts the swarm
|
||||
|
||||
Cadence:
|
||||
- never more often than every `2` minutes
|
||||
- target every `2-3` minutes when meaningful progress exists
|
||||
- always at least once every `5` minutes while work is ongoing
|
||||
- urgent alerts break through immediately
|
||||
|
||||
### Workers
|
||||
|
||||
Responsibilities:
|
||||
- operate only inside assigned lane paths
|
||||
- consume existing shared harnesses and packages
|
||||
- run targeted tests only for touched specs
|
||||
- report on cadence
|
||||
|
||||
Not allowed:
|
||||
- no git
|
||||
- no notifications
|
||||
- no package changes
|
||||
- no docs changes
|
||||
- no shared harness edits unless explicitly assigned as a harness worker
|
||||
|
||||
Required status line:
|
||||
- `state | owned_paths | current_target | last_result | blocker | next_10m`
|
||||
|
||||
Allowed states:
|
||||
- `bootstrapping`
|
||||
- `implementing`
|
||||
- `validating`
|
||||
- `blocked`
|
||||
- `handoff-ready`
|
||||
- `stopped`
|
||||
|
||||
## Pre-Flight
|
||||
|
||||
Gitops pre-flight:
|
||||
- confirm root checkout is clean except accepted baseline commits
|
||||
- confirm `.worktrees/` exists and remains ignored
|
||||
- snapshot root `git status`
|
||||
- snapshot `git worktree list`
|
||||
- snapshot status for each legacy `f90-*` worktree
|
||||
- create fresh `covswarm-*` worktrees from current root `HEAD`
|
||||
|
||||
Notify pre-flight:
|
||||
- confirm `PUSHOVER_APP_TOKEN` and `PUSHOVER_USER_KEY`
|
||||
- run `$pushover-notify --dry-run`
|
||||
- send one real normal-priority launch update after dry-run success
|
||||
|
||||
Worker runtime health gate:
|
||||
- first useful status required within `2-3` minutes
|
||||
- no heartbeat may exceed `5` minutes
|
||||
- prompt contamination or silent workers fail the gate
|
||||
|
||||
Failure handling:
|
||||
1. interrupt once for status
|
||||
2. replace once with a stronger model if needed
|
||||
3. if replacement also fails, pause that lane and either narrow it or run it locally
|
||||
4. notify sends normal replacement update and urgent alert only if the swarm is blocked
|
||||
|
||||
## Lane Order
|
||||
|
||||
### Lane 1: Stats
|
||||
|
||||
Scope:
|
||||
- `frontend/src/app/features/stats/**` spec files only
|
||||
|
||||
Goal:
|
||||
- convert the next `2-4` high-yield stats specs using the non-rendering chart harness
|
||||
|
||||
Acceptance gate before opening lane 2:
|
||||
- targeted Vitest for touched stats specs
|
||||
- gitops integrates the accepted lane batch
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- `just ui coverage-summary`
|
||||
- controller confirms real `features/stats` branch movement
|
||||
|
||||
### Lane 2: Query/Signal
|
||||
|
||||
Start as soon as lane 1 passes its first acceptance gate.
|
||||
|
||||
Priority order:
|
||||
1. `frontend/src/app/features/book/service/shelf.service.spec.ts`
|
||||
2. `frontend/src/app/features/settings/user-management/user.service.spec.ts`
|
||||
3. `frontend/src/app/features/magic-shelf/service/magic-shelf.service.spec.ts`
|
||||
|
||||
Deferred:
|
||||
- `frontend/src/app/shared/service/custom-font.service.spec.ts`
|
||||
- needs a separate browser-font seam family
|
||||
|
||||
### Lane 3: Dialog/Overlay
|
||||
|
||||
Start once either:
|
||||
- lane 1 reaches its second healthy checkpoint, or
|
||||
- lane 2 reaches its first healthy checkpoint after launch
|
||||
|
||||
Priority order:
|
||||
1. `frontend/src/app/features/bookdrop/component/bookdrop-bulk-edit-dialog/bookdrop-bulk-edit-dialog.component.spec.ts`
|
||||
2. `frontend/src/app/features/book/components/book-browser/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component.spec.ts`
|
||||
3. `frontend/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.spec.ts`
|
||||
|
||||
Deferred:
|
||||
- full reader runtimes
|
||||
- mixed query-heavy dialog seams until the relevant lane is ready
|
||||
|
||||
Concurrency rule:
|
||||
- start with lane 1 only
|
||||
- expand to two active implementation lanes immediately after the first accepted stats batch
|
||||
- expand to three only if heartbeat discipline and gitops throughput remain healthy
|
||||
|
||||
## Seam Valuation
|
||||
|
||||
Good seam work:
|
||||
- reusing an existing shared harness
|
||||
- small lane-local adapters that stay inside a spec file
|
||||
- thin glue around an approved helper
|
||||
- mature package usage instead of custom mocking
|
||||
|
||||
Borderline seam work:
|
||||
- one lane-local helper reused across `2+` specs in the same lane
|
||||
- one small signal/effect flush or callback adapter
|
||||
- one thin branch-enabling stub that does not spill into other lanes
|
||||
|
||||
Bad seam work:
|
||||
- inventing a new shared harness inside a worker lane
|
||||
- reproducing package behavior with custom test infrastructure
|
||||
- broad browser-runtime emulation for one spec
|
||||
- `15-20` minutes of seam work without unlocking a real spec
|
||||
- two consecutive candidate specs requiring bespoke seam rescue
|
||||
|
||||
Rule:
|
||||
- each lane gets one short seam spike
|
||||
- if it does not unlock a real spec, stop and escalate
|
||||
- if the helper would serve multiple lanes, it becomes a dedicated harness task rather than silent worker drift
|
||||
|
||||
## Validation
|
||||
|
||||
Per worker batch:
|
||||
- targeted Vitest on touched files
|
||||
|
||||
Per integrated lane batch:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- `just ui coverage-summary`
|
||||
|
||||
Major checkpoints:
|
||||
- `just ui coverage`
|
||||
|
||||
## Checkpoints
|
||||
|
||||
### 2026-03-27 bootstrap handoff
|
||||
|
||||
Accepted baseline:
|
||||
- bootstrap commit `111466b5`
|
||||
- shared query/chart/dialog helpers landed
|
||||
- `ng-mocks` added
|
||||
- four canary specs activated
|
||||
|
||||
Current coverage totals:
|
||||
- statements `33.60%`
|
||||
- branches `25.28%`
|
||||
- functions `29.59%`
|
||||
- lines `48.65%`
|
||||
|
||||
Current blocked seams:
|
||||
- browser-font-specific service testing
|
||||
- full reader runtime seams
|
||||
|
||||
### 2026-03-28 replay window 1
|
||||
|
||||
Accepted replay batches:
|
||||
- `2a3b82b6` `test(author-browser): cover author match component flows`
|
||||
- `152ee9a0` `test(book): cover book notes component flows`
|
||||
- `fadf732a` `test(author-browser): cover author editor component flows`
|
||||
- `bf3c5fc0` `test(book): cover shelf creator component flows`
|
||||
- `6fc5a42d` `test(book): cover book file service flows`
|
||||
- `32c1de1d` `test(stats): cover page count chart bucketing`
|
||||
|
||||
Replay status:
|
||||
- deferred queue drained into root
|
||||
- root frontend gates passing after replay:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- `just ui coverage`
|
||||
- `just ui coverage-summary`
|
||||
|
||||
Current coverage totals:
|
||||
- statements `37.50%`
|
||||
- branches `27.59%`
|
||||
- functions `34.66%`
|
||||
- lines `51.74%`
|
||||
|
||||
Highest-value bucket movement this cycle:
|
||||
- `features/author-browser` branches `5.19% -> 14.81%`
|
||||
- `features/book` branches `27.62% -> 29.68%`
|
||||
- `features/stats` branches `8.40% -> 9.44%`
|
||||
|
||||
Current queued accumulation batches:
|
||||
- `covswarm-author3`
|
||||
- file: `frontend/src/app/features/author-browser/components/author-card/author-card.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/author-browser/components/author-card/author-card.component.spec.ts`
|
||||
- result: `1` file passed, `8` tests passed
|
||||
- proposed subject: `test(author-browser): cover author card component flows`
|
||||
- `covswarm-bookcomp3`
|
||||
- file: `frontend/src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts`
|
||||
- result: `1` file passed, `7` tests passed
|
||||
- proposed subject: `test(book): cover shelf assigner component flows`
|
||||
- `covswarm-author4`
|
||||
- file: `frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts`
|
||||
- result: `1` file passed, `8` tests passed
|
||||
- proposed subject: `test(author-browser): cover author detail component flows`
|
||||
- `covswarm-bookcomp4`
|
||||
- file: `frontend/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn --cwd frontend vitest run src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts --config vitest.config.ts`
|
||||
- result: `1` file passed, `10` tests passed
|
||||
- proposed subject: `test(book): cover add physical book dialog flows`
|
||||
- `covswarm-bookcomp5`
|
||||
- file: `frontend/src/app/features/book/components/book-sender/book-sender.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn ng test --watch=false --include src/app/features/book/components/book-sender/book-sender.component.spec.ts`
|
||||
- result: `1` file passed, `6` tests passed
|
||||
- proposed subject: `test(book): cover book sender component flows`
|
||||
- `covswarm-stats2`
|
||||
- file: `frontend/src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts`
|
||||
- result: `1` file passed, `4` tests passed
|
||||
- proposed subject: `test(stats): cover language chart aggregation`
|
||||
- `covswarm-stats3`
|
||||
- file: `frontend/src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts --config vitest.config.ts`
|
||||
- result: `1` file passed, `4` tests passed
|
||||
- proposed subject: `test(stats): cover metadata score chart states`
|
||||
- `covswarm-bookcomp6`
|
||||
- file: `frontend/src/app/features/book/components/book-reviews/book-reviews.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/book/components/book-reviews/book-reviews.component.spec.ts --config vitest.config.ts`
|
||||
- result: `1` file passed, `10` tests passed
|
||||
- proposed subject: `test(book): cover book reviews component flows`
|
||||
- `covswarm-bookcomp7`
|
||||
- file: `frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts`
|
||||
- targeted validation: `yarn vitest run src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts`
|
||||
- result: `1` file passed, `8` tests passed
|
||||
- proposed subject: `test(book): cover book file attacher flows`
|
||||
- `covswarm-stats4`
|
||||
- file: `frontend/src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts`
|
||||
- targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts`
|
||||
- result: `1` file passed, `5` tests passed
|
||||
- proposed subject: `test(stats): cover reading progress chart bucketing`
|
||||
|
||||
Next accumulation lanes:
|
||||
- `features/stats/component/user-stats/charts/read-status-chart/read-status-chart.component.spec.ts`
|
||||
- `features/stats/component/library-stats/charts/publication-trend-chart/publication-trend-chart.component.spec.ts`
|
||||
- `features/book/components/duplicate-merger/duplicate-merger.component.spec.ts`
|
||||
|
||||
Current blocked seams:
|
||||
- full `author-browser.component` shell remains high-risk and deferred
|
||||
- browser-font-specific service testing remains deferred
|
||||
- full reader runtime seams remain deferred
|
||||
@@ -0,0 +1,799 @@
|
||||
# Frontend Stub Fill Log
|
||||
|
||||
Single-threaded pass to replace generic TODO spec stubs under `frontend/src/app`.
|
||||
|
||||
Rules for this pass:
|
||||
- No runtime code changes.
|
||||
- Replace generic stubs with real specs where possible.
|
||||
- If a real spec would need a new runtime seam, keep the spec skipped and state the seam explicitly.
|
||||
- Commits are optional; this log is the durable grouping record.
|
||||
|
||||
## 2026-03-26
|
||||
|
||||
### Batch 1
|
||||
- Scope: initial pure/type-bearing frontend files.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/core/config/api-config.spec.ts`
|
||||
- `frontend/src/app/features/author-browser/model/author.model.spec.ts`
|
||||
- `frontend/src/app/features/author-browser/service/author-query-keys.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-filter/book-filter.config.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts`
|
||||
- `frontend/src/app/features/book/model/library.model.spec.ts`
|
||||
- `frontend/src/app/features/book/service/library-query-keys.spec.ts`
|
||||
- `frontend/src/app/features/metadata/model/request/metadata-refresh-type.enum.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/state/themes.constant.spec.ts`
|
||||
- `frontend/src/app/shared/constants/reset-progress-type.spec.ts`
|
||||
- `frontend/src/app/shared/model/app-state.model.spec.ts`
|
||||
- `frontend/src/app/shared/websocket/model/log-notification.model.spec.ts`
|
||||
|
||||
### Batch 2
|
||||
- Scope: additional pure models, enums, and type-only request payloads.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/book/model/sort.model.spec.ts`
|
||||
- `frontend/src/app/features/book/model/shelf.model.spec.ts`
|
||||
- `frontend/src/app/features/metadata/model/request/fetch-metadata-request.model.spec.ts`
|
||||
- `frontend/src/app/features/metadata/model/request/metadata-refresh-options.model.spec.ts`
|
||||
- `frontend/src/app/features/metadata/model/request/metadata-refresh-request.model.spec.ts`
|
||||
- `frontend/src/app/features/notebook/model/notebook.model.spec.ts`
|
||||
- `frontend/src/app/features/readers/audiobook-player/audiobook.model.spec.ts`
|
||||
- `frontend/src/app/features/series-browser/model/series.model.spec.ts`
|
||||
- `frontend/src/app/shared/layout/api/menuchangeevent.spec.ts`
|
||||
- `frontend/src/app/shared/model/oidc-group-mapping.model.spec.ts`
|
||||
- `frontend/src/app/shared/models/api-exception.model.spec.ts`
|
||||
|
||||
### Batch 3
|
||||
- Scope: remaining pure query keys, settings/email contracts, and light index exports.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/service/app-settings-query-keys.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-management/user-query-keys.spec.ts`
|
||||
- `frontend/src/app/features/settings/email-v2/email-provider.model.spec.ts`
|
||||
- `frontend/src/app/features/settings/email-v2/email-recipient.model.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-management/content-restriction.model.spec.ts`
|
||||
- `frontend/src/app/shared/metadata/metadata-field.config.spec.ts`
|
||||
- `frontend/src/app/shared/metadata/embeddable-fields.config.spec.ts`
|
||||
- `frontend/src/app/shared/metadata/index.spec.ts`
|
||||
- `frontend/src/app/features/readers/audiobook-player/index.spec.ts`
|
||||
|
||||
### Batch 4
|
||||
- Scope: larger pure models and default config exports.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/model/app-settings.model.spec.ts`
|
||||
- `frontend/src/app/features/dashboard/models/dashboard-config.model.spec.ts`
|
||||
- `frontend/src/app/features/book/model/book.model.spec.ts`
|
||||
|
||||
### Batch 5
|
||||
- Scope: guards, setup flows, and small websocket/helper utilities that do not need runtime seams.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/core/testing/transloco-testing.spec.ts`
|
||||
- `frontend/src/app/core/security/guards/manage-library.guard.spec.ts`
|
||||
- `frontend/src/app/core/security/guards/bookdrop.guard.spec.ts`
|
||||
- `frontend/src/app/core/security/guards/library-stats.guard.spec.ts`
|
||||
- `frontend/src/app/core/security/guards/user-stats.guard.spec.ts`
|
||||
- `frontend/src/app/core/security/guards/edit-metdata.guard.spec.ts`
|
||||
- `frontend/src/app/shared/components/setup/setup.service.spec.ts`
|
||||
- `frontend/src/app/shared/components/setup/setup.guard.spec.ts`
|
||||
- `frontend/src/app/shared/components/setup/login.guard.spec.ts`
|
||||
- `frontend/src/app/shared/components/setup/setup-redirect.guard.spec.ts`
|
||||
- `frontend/src/app/shared/websocket/rx-stomp.config.spec.ts`
|
||||
- `frontend/src/app/shared/websocket/rx-stomp-service-factory.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/filter-label.helper.spec.ts`
|
||||
|
||||
### Batch 6
|
||||
- Scope: lightweight services and observables that can be exercised without runtime code seams.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/service/page-title.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/settings-helper.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/icon-picker.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/metadata-match-weights.service.spec.ts`
|
||||
- `frontend/src/app/shared/websocket/notification-event.service.spec.ts`
|
||||
|
||||
### Batch 7
|
||||
- Scope: shared HTTP-wrapper services with straightforward request/response contracts.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/service/oidc-group-mapping.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/book-note.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/book-note-v2.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/book-mark.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/annotation.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/reading-session-api.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/file-download.service.spec.ts`
|
||||
- `frontend/src/app/shared/websocket/rx-stomp.service.spec.ts`
|
||||
- `frontend/src/app/shared/services/dialog-launcher.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/app-settings.service.spec.ts`
|
||||
|
||||
### Batch 8
|
||||
- Scope: metadata utilities and lightweight shared/book HTTP services.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/services/book-cover.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/file-operations.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/metadata-task.spec.ts`
|
||||
- `frontend/src/app/shared/metadata/metadata-utils.service.spec.ts`
|
||||
- `frontend/src/app/shared/metadata/metadata-form.builder.spec.ts`
|
||||
- `frontend/src/app/shared/service/metadata-progress.service.spec.ts`
|
||||
|
||||
### Batch 9
|
||||
- Scope: shared utility services, theme helpers, and seam-documented runtime-heavy specs.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/layout/component/theme-palette-extend.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/theme-configurator/favicon-service.spec.ts`
|
||||
- `frontend/src/app/shared/service/pdf-annotation.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/audiobook-session.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/custom-font.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/app-config.service.spec.ts`
|
||||
|
||||
### Batch 10
|
||||
- Scope: shared layout, upload, icon, and reader-session services with real browser/service coverage.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/theme-configurator/background-upload.service.spec.ts`
|
||||
- `frontend/src/app/features/readers/audiobook-player/audiobook.service.spec.ts`
|
||||
- `frontend/src/app/shared/services/icon.service.spec.ts`
|
||||
- `frontend/src/app/shared/service/reading-session.service.spec.ts`
|
||||
|
||||
### Batch 11
|
||||
- Scope: low-friction shared/settings service wrappers plus one explicit dynamic-component seam.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/components/directory-picker/utility.service.spec.ts`
|
||||
- `frontend/src/app/features/settings/audit-logs/audit-log.service.spec.ts`
|
||||
- `frontend/src/app/features/library-creator/library-loading.service.spec.ts`
|
||||
|
||||
### Batch 12
|
||||
- Scope: book service control-flow surfaces and a query-heavy user-service seam note.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/book/service/cbx-reader.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/book-patch.service.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-management/user.service.spec.ts`
|
||||
|
||||
### Batch 13
|
||||
- Scope: small shared standalone components with direct behavior or render assertions.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/components/external-doc-link/external-doc-link.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/empty/empty.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/tag/tag.component.spec.ts`
|
||||
|
||||
### Batch 14
|
||||
- Scope: one pure library-loading component plus local shared components with mocked dialog and websocket behavior.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/library-creator/library-loading/library-loading.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/directory-picker/directory-picker.component.spec.ts`
|
||||
|
||||
### Batch 15
|
||||
- Scope: runtime-heavy shared and library flows converted from generic placeholders to seam-specific skipped specs.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/magic-shelf/service/magic-shelf.service.spec.ts`
|
||||
- `frontend/src/app/features/library-creator/library-creator.component.spec.ts`
|
||||
|
||||
### Batch 28
|
||||
- Scope: next settings, book, metadata, and stats shells converted from generic TODO stubs to explicit seam-documented specs.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Remaining generic TODO stubs: `59`
|
||||
- Files:
|
||||
- `frontend/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/view-preferences-parent/filter-preferences/filter-preferences.component.spec.ts`
|
||||
- `frontend/src/app/features/book/service/book-menu.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/book-file.service.spec.ts`
|
||||
- `frontend/src/app/features/settings/settings.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/device-settings/device-settings-component.spec.ts`
|
||||
- `frontend/src/app/features/bookdrop/component/bookdrop-file-metadata-picker/bookdrop-file-metadata-picker.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-dna-chart/reading-dna-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/metadata/component/cover-search/cover-search.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-notes/book-notes-component.spec.ts`
|
||||
|
||||
### Batch 29
|
||||
- Scope: KOReader and metadata settings received real coverage where the surfaces were deterministic; the remaining dialog/query-heavy files were converted to explicit seam notes.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Remaining generic TODO stubs: `49`
|
||||
- Files:
|
||||
- `frontend/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.spec.ts`
|
||||
- `frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts`
|
||||
- `frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.spec.ts`
|
||||
- `frontend/src/app/features/metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component.spec.ts`
|
||||
- `frontend/src/app/features/metadata/component/bulk-metadata-update/bulk-metadata-update-component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-sender/book-sender.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/series-page/series-page.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/metadata-settings/metadata-settings-component.spec.ts`
|
||||
- `frontend/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.spec.ts`
|
||||
|
||||
### Batch 30
|
||||
- Scope: simple dialog, reader footer, kobo settings, public review settings, and book-card-lite now have real tests; the surrounding shell-heavy reader/email/file-attach surfaces were converted to explicit seam notes.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Remaining generic TODO stubs: `39`
|
||||
- Files:
|
||||
- `frontend/src/app/features/bookdrop/component/bookdrop-finalize-result-dialog/bookdrop-finalize-result-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts`
|
||||
- `frontend/src/app/features/settings/metadata-settings/public-reviews-settings/public-reviews-settings-component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-card-lite/book-card-lite-component.spec.ts`
|
||||
- `frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/layout-topbar/app.topbar.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/book-uploader/book-uploader.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/custom-fonts/custom-fonts.component.spec.ts`
|
||||
|
||||
### Batch 16
|
||||
- Scope: layout-heavy shells converted from generic placeholders to seam-specific skipped specs.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/layout/component/theme-configurator/theme-configurator.component.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/layout-main/app.layout.component.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/layout-sidebar/app.sidebar.component.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/layout-menu/app.menu.component.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/layout-menu/app.menuitem.component.spec.ts`
|
||||
|
||||
### Batch 17
|
||||
- Scope: real coverage for shared standalone form and dialog components with direct control-flow assertions.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/components/change-password/change-password.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/icon-display/icon-display.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/setup/setup.component.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/theme-configurator/upload-dialog/upload-dialog.component.spec.ts`
|
||||
- `frontend/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.spec.ts`
|
||||
|
||||
### Batch 18
|
||||
- Scope: one real shared progress widget, one real stats HTTP wrapper, and seam-specific replacements for query-runtime-heavy services/components.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-management/user-stats.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/shelf.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/library.service.spec.ts`
|
||||
- `frontend/src/app/shared/components/icon-picker/icon-picker-component.spec.ts`
|
||||
|
||||
### Batch 19
|
||||
- Scope: bookdrop API/control-flow coverage plus one seam-specific replacement for a menu-command-heavy service.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/bookdrop/service/bookdrop-file-api.service.spec.ts`
|
||||
- `frontend/src/app/features/bookdrop/service/bookdrop-file.service.spec.ts`
|
||||
- `frontend/src/app/features/bookdrop/service/bookdrop.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/book-metadata.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts`
|
||||
|
||||
### Batch 20
|
||||
- Scope: shared utility components with real coverage plus seam-specific replacements for reader/chart-heavy surfaces that still lack clean injectable seams.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/shared/components/cover-generator/cover-generator.component.spec.ts`
|
||||
- `frontend/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.spec.ts`
|
||||
- `frontend/src/app/shared/components/file-mover/file-mover-component.spec.ts`
|
||||
- `frontend/src/app/features/readers/pdf-reader/pdf-reader.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/cbx-reader/cbx-reader.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/audiobook-player/audiobook-player.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/genre-stats-chart/genre-stats-chart.component.spec.ts`
|
||||
|
||||
### Batch 21
|
||||
- Scope: book cache/control-flow services with real coverage, one real series-card component spec, and seam-specific replacements for query-runtime and invalid-template surfaces.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/book/service/book-socket.service.spec.ts`
|
||||
- `frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts`
|
||||
- `frontend/src/app/features/series-browser/components/series-card/series-card.component.spec.ts`
|
||||
- `frontend/src/app/features/book/service/book.service.spec.ts`
|
||||
- `frontend/src/app/features/series-browser/components/series-scroller/series-scroller.component.spec.ts`
|
||||
|
||||
### Batch 22
|
||||
- Scope: reader-preference and naming settings with real control-flow coverage, plus seam-specific replacements for browser-heavy settings shells and dialogs.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.spec.ts`
|
||||
- `frontend/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.spec.ts`
|
||||
- `frontend/src/app/features/settings/file-naming-pattern/file-naming-pattern.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.spec.ts`
|
||||
- `frontend/src/app/features/settings/view-preferences-parent/sidebar-sorting-preferences/sidebar-sorting-preferences.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/global-preferences/global-preferences.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/audit-logs/audit-logs.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.spec.ts`
|
||||
|
||||
### Batch 23
|
||||
- Scope: dashboard and stats visualization surfaces converted from generic placeholders to explicit seam notes where real coverage would require chart, canvas, scroll, or dashboard orchestration adapters.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.spec.ts`
|
||||
- `frontend/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.spec.ts`
|
||||
- `frontend/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-session-timeline/reading-session-timeline.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/favorite-days-chart/favorite-days-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/completion-timeline-chart/completion-timeline-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/peak-hours-chart/peak-hours-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-session-heatmap/reading-session-heatmap.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/read-status-chart/read-status-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/notebook/components/notebook/notebook.component.spec.ts`
|
||||
|
||||
### Batch 24
|
||||
- Scope: additional user-stats chart placeholders converted into explicit seam notes for chart-runtime, effect, callback, and aggregation boundaries instead of generic TODO stubs.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/page-turner-chart/page-turner-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/completion-race-chart/completion-race-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/rating-taste-chart/rating-taste-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-clock-chart/reading-clock-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/personal-rating-chart/personal-rating-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-heatmap-chart/reading-heatmap-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-habits-chart/reading-habits-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/series-progress-chart/series-progress-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/book-length-chart/book-length-chart.component.spec.ts`
|
||||
|
||||
### Batch 25
|
||||
- Scope: author-browser, book dialog, user-management, and additional stats surfaces converted from generic placeholders into explicit seam notes where real coverage would require routed dialog stacks, Prime widget runtime, or chart adapters.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.spec.ts`
|
||||
- `frontend/src/app/features/author-browser/components/author-card/author-card.component.spec.ts`
|
||||
- `frontend/src/app/features/author-browser/components/author-browser/author-browser.component.spec.ts`
|
||||
- `frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts`
|
||||
- `frontend/src/app/features/author-browser/components/author-editor/author-editor.component.spec.ts`
|
||||
- `frontend/src/app/features/author-browser/components/author-match/author-match.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-searcher/book-searcher.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/duplicate-merger/duplicate-merger.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-management/user-management.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-management/create-user-dialog/create-user-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.spec.ts`
|
||||
|
||||
### Batch 26
|
||||
- Scope: simple reader dialogs and header upgraded to real specs, while library-stats, reader-shell, and bookdrop orchestration placeholders were replaced with seam-specific notes.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/readers/cbx-reader/dialogs/cbx-shortcuts-help.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/cbx-reader/dialogs/cbx-note-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/library-stats.component.spec.ts`
|
||||
- `frontend/src/app/features/bookdrop/component/bookdrop-bulk-edit-dialog/bookdrop-bulk-edit-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/series-browser/components/series-browser/series-browser.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/bookdrop/component/bookdrop-files-widget/bookdrop-files-widget.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/ebook-reader.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/book-formats-chart/book-formats-chart.component.spec.ts`
|
||||
|
||||
### Batch 27
|
||||
- Scope: remaining library-stats chart placeholders plus ebook and CBX shell surfaces converted from generic TODO stubs into explicit chart/runtime seam notes.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Files:
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/top-items-chart/top-items-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/page-count-chart/page-count-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/publication-timeline-chart/publication-timeline-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/reading-journey-chart/reading-journey-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/author-universe-chart/author-universe-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/library-stats/charts/publication-trend-chart/publication-trend-chart.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/dialogs/shortcuts-help.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/layout/header/header.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.component.spec.ts`
|
||||
|
||||
### Batch 31
|
||||
- Scope: branch-heavy book helper/services upgraded to real specs, while book filter/table and upload dialog placeholders were replaced with explicit component seam notes.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Remaining generic TODO stubs after batch: `29`
|
||||
- Files:
|
||||
- `frontend/src/app/features/book/components/book-reviews/book-review-service.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-filter-orchestration.service.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-card-overlay-preference.service.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-filter/book-filter.service.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-filter/book-filter.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-reviews/book-reviews.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.spec.ts`
|
||||
|
||||
### Batch 32
|
||||
- Scope: finished the remaining generic frontend coverage stubs by adding direct class or HTTP tests for the cheap service surfaces and replacing the heavy Angular or PrimeNG or reader-shell placeholders with explicit seam-noted skipped specs.
|
||||
- Status: completed.
|
||||
- Validation:
|
||||
- `just ui typecheck`
|
||||
- `just ui lint`
|
||||
- `just ui test`
|
||||
- Remaining generic TODO stubs after batch: `0`
|
||||
- Files:
|
||||
- `frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/features/annotations/annotation.service.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/index.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/shared/icon.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/reader-preferences/reader-preferences.component.spec.ts`
|
||||
- `frontend/src/app/features/stats/component/user-stats/user-stats.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/book-browser/sorting/multi-sort-popover/multi-sort-popover.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/shelf-creator/shelf-creator.component.spec.ts`
|
||||
- `frontend/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.spec.ts`
|
||||
- `frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.spec.ts`
|
||||
- `frontend/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.spec.ts`
|
||||
- `frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/core/view-manager.service.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/layout/footer/footer.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/layout/panel/panel.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.spec.ts`
|
||||
- `frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts`
|
||||
- `frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts`
|
||||
- `frontend/src/app/features/settings/email-v2/create-email-provider-dialog/create-email-provider-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/email-v2/create-email-recipient-dialog/create-email-recipient-dialog.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/email-v2/email-v2.component.spec.ts`
|
||||
- `frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts`
|
||||
- `frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.spec.ts`
|
||||
|
||||
## Proposed Commit Shapes
|
||||
|
||||
These are controller-friendly Conventional Commit shapes for the logged batches. Each body is grouped markdown that can be used directly or merged into larger follow-up commits.
|
||||
|
||||
### Batch 1
|
||||
- Subject: `test(frontend): cover pure models and config contracts`
|
||||
- Body:
|
||||
- `- Coverage: add type-level specs for pure frontend config, model, and enum surfaces under core, author-browser, book, metadata, readers, and shared.`
|
||||
- `- Intent: replace placeholder specs with cheap deterministic assertions that lock down static contract behavior without runtime seams.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 2
|
||||
- Subject: `test(frontend): cover request payload and contract models`
|
||||
- Body:
|
||||
- `- Coverage: add specs for additional book, metadata, notebook, readers, series-browser, and shared request or model contracts.`
|
||||
- `- Intent: keep the stub-replacement pass moving through deterministic type-bearing files before shifting into heavier service and component surfaces.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 3
|
||||
- Subject: `test(frontend): cover query keys and barrel exports`
|
||||
- Body:
|
||||
- `- Coverage: add tests for shared and settings query keys, email contracts, metadata exports, and audiobook barrel exports.`
|
||||
- `- Intent: close out low-risk placeholder specs where real value comes from locking contract shape and export stability.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 4
|
||||
- Subject: `test(frontend): cover larger model defaults and dashboard contracts`
|
||||
- Body:
|
||||
- `- Coverage: add specs for the main app-settings, dashboard, and book models.`
|
||||
- `- Intent: finish the remaining pure model stubs before shifting toward control-flow and service behavior.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 5
|
||||
- Subject: `test(frontend): cover setup and guard utilities`
|
||||
- Body:
|
||||
- `- Coverage: add deterministic tests for setup services, setup guards, security guards, websocket helpers, and small filter helpers.`
|
||||
- `- Intent: replace placeholder coverage with branch-bearing guard and bootstrap assertions that do not require runtime code changes.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 6
|
||||
- Subject: `test(frontend): cover lightweight shared services`
|
||||
- Body:
|
||||
- `- Coverage: add tests for page title, settings helper, icon picker, metadata-match weights, and notification event services.`
|
||||
- `- Intent: convert low-friction service placeholders into real control-flow coverage before moving to HTTP-heavy wrappers.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 7
|
||||
- Subject: `test(frontend): cover shared HTTP service wrappers`
|
||||
- Body:
|
||||
- `- Coverage: add request and response tests for shared annotation, note, bookmark, reading-session, websocket, and group-mapping services.`
|
||||
- `- Intent: replace generic HTTP-wrapper stubs with real endpoint-shape coverage that can fail honestly when request contracts drift.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 8
|
||||
- Subject: `test(frontend): cover metadata utilities and book HTTP helpers`
|
||||
- Body:
|
||||
- `- Coverage: add tests for metadata form and utility services, file operations, book cover helpers, metadata progress, and metadata-task behavior.`
|
||||
- `- Intent: push coverage into utility and helper layers that affect metadata control flow without needing heavy component harnesses.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 9
|
||||
- Subject: `test(frontend): cover shared utilities and document seam-heavy specs`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for theme, PDF annotation, audiobook session, and config helpers while converting the remaining runtime-heavy shared stubs into explicit seam notes.`
|
||||
- `- Intent: separate deterministic coverage wins from surfaces that still need browser or runtime harnesses later.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 10
|
||||
- Subject: `test(frontend): cover layout upload and reader-session services`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for layout service, background upload, audiobook service, icon service, and reading-session behavior.`
|
||||
- `- Intent: grow coverage through shared layout and reader utilities without changing runtime code.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 11
|
||||
- Subject: `test(frontend): cover lightweight settings wrappers`
|
||||
- Body:
|
||||
- `- Coverage: add tests for directory-picker utilities, audit-log service behavior, and the low-friction library-loading path.`
|
||||
- `- Intent: keep the pass focused on cheap deterministic seams while documenting the remaining dynamic component seam explicitly.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 12
|
||||
- Subject: `test(frontend): cover book service control flow`
|
||||
- Body:
|
||||
- `- Coverage: add real service tests for CBX reader and book patch flows and replace the user-service placeholder with a seam-aware spec.`
|
||||
- `- Intent: increase branch coverage in book service layers while acknowledging the query-heavy user-service runtime boundary.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 13
|
||||
- Subject: `test(frontend): cover small shared standalone components`
|
||||
- Body:
|
||||
- `- Coverage: add direct component behavior tests for external links, empty states, and tag rendering.`
|
||||
- `- Intent: clear straightforward standalone component stubs without spending time on decorative template-only churn.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 14
|
||||
- Subject: `test(frontend): cover library loading and local shared components`
|
||||
- Body:
|
||||
- `- Coverage: add tests for library-loading, live-notification, and directory-picker components using mocked local dependencies.`
|
||||
- `- Intent: pick off component surfaces that have real behavior but do not require heavy application orchestration.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 15
|
||||
- Subject: `test(frontend): document shared runtime seams`
|
||||
- Body:
|
||||
- `- Coverage: replace remaining shared and library runtime-heavy placeholders with explicit seam-noted skipped specs.`
|
||||
- `- Intent: make the remaining blocker surfaces auditable instead of leaving generic TODO stubs behind.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 16
|
||||
- Subject: `test(frontend): document layout shell seams`
|
||||
- Body:
|
||||
- `- Coverage: convert layout-heavy shell placeholders into seam-specific skipped specs.`
|
||||
- `- Intent: record the need for mounted layout harnesses without spending time on brittle shallow shell tests.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 17
|
||||
- Subject: `test(frontend): cover shared forms and dialogs`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for shared standalone form and dialog components with direct control-flow assertions.`
|
||||
- `- Intent: capture meaningful component behavior where the harness cost is still low enough to justify real tests.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 18
|
||||
- Subject: `test(frontend): cover progress and stats wrappers`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for a shared progress widget and a stats HTTP wrapper while documenting heavier query-driven seams.`
|
||||
- `- Intent: keep coverage growth honest by splitting easy wrappers from runtime-heavy component and service surfaces.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 19
|
||||
- Subject: `test(frontend): cover bookdrop API branches`
|
||||
- Body:
|
||||
- `- Coverage: add bookdrop API and control-flow coverage and replace the remaining menu-command-heavy service stub with a seam note.`
|
||||
- `- Intent: grow branch coverage in bookdrop services while avoiding low-yield template churn.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 20
|
||||
- Subject: `test(frontend): cover shared utility components`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for shared utility components and convert heavier reader or chart placeholders into explicit seam-noted skips.`
|
||||
- `- Intent: continue replacing generic placeholders while keeping runtime-heavy chart and reader shells out of the main path.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 21
|
||||
- Subject: `test(frontend): cover book cache and series card behavior`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for book cache and control-flow services plus the series-card component, and document the remaining query-runtime seams.`
|
||||
- `- Intent: prioritize behavior-bearing book surfaces instead of spreading effort over decorative render-only coverage.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 22
|
||||
- Subject: `test(frontend): cover reader preference settings flows`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for reader-preference and naming settings while replacing browser-heavy settings shells and dialogs with seam notes.`
|
||||
- `- Intent: move settings coverage upward without inventing runtime seams for the stubborn UI-heavy surfaces.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 23
|
||||
- Subject: `test(frontend): document dashboard and stats visualization seams`
|
||||
- Body:
|
||||
- `- Coverage: replace dashboard and stats visualization placeholders with explicit chart, canvas, scroll, and orchestration seam notes.`
|
||||
- `- Intent: make the expensive visualization blockers explicit instead of keeping them as generic unowned TODO stubs.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 24
|
||||
- Subject: `test(frontend): document remaining user stats chart seams`
|
||||
- Body:
|
||||
- `- Coverage: convert another wave of user-stats chart placeholders into explicit runtime seam notes.`
|
||||
- `- Intent: keep the coverage pass honest by documenting chart-runtime blockers without pretending that render smoke tests would help.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 25
|
||||
- Subject: `test(frontend): document author-browser and dialog seams`
|
||||
- Body:
|
||||
- `- Coverage: replace author-browser, book-dialog, user-management, and additional stats placeholders with routed dialog or widget seam notes.`
|
||||
- `- Intent: record the real blocker surfaces cleanly and avoid low-yield retries on complex dialog stacks.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 26
|
||||
- Subject: `test(frontend): cover reader dialogs and note library-stats seams`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for simple reader dialogs and header behavior and document the remaining library-stats, reader-shell, and bookdrop orchestration seams.`
|
||||
- `- Intent: combine cheap reader wins with explicit notes for surfaces that still need mounted runtime harnesses.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 27
|
||||
- Subject: `test(frontend): document remaining library stats and reader shell seams`
|
||||
- Body:
|
||||
- `- Coverage: replace the remaining library-stats chart placeholders and ebook or CBX shell stubs with explicit chart and runtime seam notes.`
|
||||
- `- Intent: finish the chart-heavy placeholder cleanup in a durable, auditable way.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 28
|
||||
- Subject: `test(frontend): document settings and metadata shell seams`
|
||||
- Body:
|
||||
- `- Coverage: convert another wave of settings, book, metadata, and stats shells from generic TODO stubs into explicit seam-documented specs.`
|
||||
- `- Intent: keep the pass moving through high-friction surfaces without faking useful coverage.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 29
|
||||
- Subject: `test(frontend): cover deterministic settings services`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for KOReader and metadata settings surfaces where the behavior is deterministic, and document the remaining dialog-heavy seams.`
|
||||
- `- Intent: take the cheap service and settings wins while isolating the harder modal and query-driven blockers.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 30
|
||||
- Subject: `test(frontend): cover selected reader and settings widgets`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for a simple dialog, the CBX footer, kobo settings service behavior, public review settings, and book-card-lite.`
|
||||
- `- Intent: harvest another set of low-friction component and service wins while documenting the surrounding reader and email shell seams.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 31
|
||||
- Subject: `test(frontend): cover book helper and review services`
|
||||
- Body:
|
||||
- `- Coverage: add real tests for book review, dialog helper, orchestration, and overlay-preference services, and convert the remaining book browser and upload shells into explicit seam notes.`
|
||||
- `- Intent: push branch coverage into real book control flow instead of spreading effort over decorative component smoke tests.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, and just ui test.`
|
||||
|
||||
### Batch 32
|
||||
- Subject: `test(frontend): finish replacing generic spec stubs`
|
||||
- Body:
|
||||
- `- Coverage: close out the remaining generic TODO stubs with real HTTP or class-level specs where cheap, and explicit seam-noted skipped specs where heavier Angular, PrimeNG, or reader-shell harnesses are still required.`
|
||||
- `- Result: bring the generic TODO stub count under frontend src app to zero while preserving the no-runtime-change rule.`
|
||||
- `- Validation: run just ui typecheck, just ui lint, just ui test, and finish with just ui check.`
|
||||
+25
-1
@@ -36,7 +36,31 @@ test:
|
||||
|
||||
# Run the frontend tests with a coverage report.
|
||||
coverage:
|
||||
{{ yarn }} ng test --coverage
|
||||
{{ yarn }} coverage
|
||||
|
||||
# Summarize the latest frontend coverage report by global and feature buckets.
|
||||
coverage-summary:
|
||||
{{ yarn }} coverage:summary
|
||||
|
||||
# Install the Chromium browser used by the frontend Playwright suite.
|
||||
e2e-install:
|
||||
{{ yarn }} e2e:install
|
||||
|
||||
# Run the frontend Playwright suite.
|
||||
e2e:
|
||||
{{ yarn }} e2e
|
||||
|
||||
# Run a single frontend Playwright spec file.
|
||||
e2e-file spec:
|
||||
{{ yarn }} e2e {{ spec }}
|
||||
|
||||
# List the tests contained in a single frontend Playwright spec file.
|
||||
e2e-list spec:
|
||||
{{ yarn }} e2e {{ spec }} --list
|
||||
|
||||
# Start the Angular dev server for Playwright against a fixed host and port.
|
||||
e2e-dev host='127.0.0.1' port='4301':
|
||||
{{ yarn }} ng serve --host {{ host }} --port {{ port }} --configuration development --watch=false
|
||||
|
||||
# Run the frontend linter.
|
||||
lint:
|
||||
|
||||
+44
-31
@@ -9,7 +9,11 @@
|
||||
"build:prod": "ng build --configuration production",
|
||||
"dev": "ng serve --open --watch --configuration development",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test",
|
||||
"test": "ng test --watch=false",
|
||||
"coverage": "ng test --watch=false --coverage",
|
||||
"coverage:summary": "node ./scripts/coverage-summary.mjs",
|
||||
"e2e": "playwright test",
|
||||
"e2e:install": "playwright install chromium",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.app.json",
|
||||
"lint": "yarn lint:eslint && yarn lint:styles",
|
||||
"lint:eslint": "ng lint",
|
||||
@@ -18,28 +22,28 @@
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^21.2.4",
|
||||
"@angular/cdk": "^21.2.0",
|
||||
"@angular/common": "^21.2.4",
|
||||
"@angular/compiler": "^21.2.4",
|
||||
"@angular/core": "^21.2.4",
|
||||
"@angular/forms": "^21.2.4",
|
||||
"@angular/platform-browser": "^21.2.4",
|
||||
"@angular/platform-browser-dynamic": "^21.2.4",
|
||||
"@angular/router": "^21.2.4",
|
||||
"@angular/service-worker": "^21.2.4",
|
||||
"@angular/animations": "^21.2.6",
|
||||
"@angular/cdk": "^21.2.4",
|
||||
"@angular/common": "^21.2.6",
|
||||
"@angular/compiler": "^21.2.6",
|
||||
"@angular/core": "^21.2.6",
|
||||
"@angular/forms": "^21.2.6",
|
||||
"@angular/platform-browser": "^21.2.6",
|
||||
"@angular/platform-browser-dynamic": "^21.2.6",
|
||||
"@angular/router": "^21.2.6",
|
||||
"@angular/service-worker": "^21.2.6",
|
||||
"@iharbeck/ngx-virtual-scroller": "^20.0.0",
|
||||
"@jsverse/transloco": "^8.2.1",
|
||||
"@primeuix/themes": "^2.0.3",
|
||||
"@stomp/rx-stomp": "^2.3.0",
|
||||
"@stomp/stompjs": "^7.3.0",
|
||||
"@tanstack/angular-query-experimental": "5.90.26",
|
||||
"@tanstack/angular-query-experimental": "5.95.2",
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
"chart.js": "^4.5.1",
|
||||
"chartjs-chart-matrix": "^3.0.0",
|
||||
"chartjs-plugin-datalabels": "^2.2.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.3.1",
|
||||
"dompurify": "^3.3.3",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"ng-lazyload-image": "^9.1.3",
|
||||
"ng2-charts": "^8.0.0",
|
||||
@@ -47,35 +51,44 @@
|
||||
"ngx-infinite-scroll": "^21.0.0",
|
||||
"ngx-sse-client": "^20.0.1",
|
||||
"primeicons": "^7.0.0",
|
||||
"primeng": "^21.1.1",
|
||||
"primeng": "^21.1.3",
|
||||
"rxjs": "^7.8.2",
|
||||
"showdown": "^2.1.0",
|
||||
"tslib": "^2.8.1",
|
||||
"uuid": "^11.0.0",
|
||||
"ws": "^8.19.0",
|
||||
"ws": "^8.20.0",
|
||||
"zone.js": "^0.16.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@analogjs/vite-plugin-angular": "^2.3.0",
|
||||
"@analogjs/vitest-angular": "^2.3.0",
|
||||
"@angular-devkit/architect": "0.2102.0",
|
||||
"@angular-devkit/schematics": "21.2.0",
|
||||
"@angular/build": "^21.2.0",
|
||||
"@angular/cli": "^21.2.0",
|
||||
"@angular/compiler-cli": "^21.2.4",
|
||||
"@analogjs/vite-plugin-angular": "^2.3.1",
|
||||
"@analogjs/vitest-angular": "^2.3.1",
|
||||
"@angular-devkit/architect": "0.2102.4",
|
||||
"@angular-devkit/schematics": "21.2.4",
|
||||
"@angular/build": "^21.2.4",
|
||||
"@angular/cli": "^21.2.4",
|
||||
"@angular/compiler-cli": "^21.2.6",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@playwright/test": "^1.58.2",
|
||||
"@testing-library/angular": "^19.2.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/dompurify": "^3.2.0",
|
||||
"@types/node": "^25.3.2",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/showdown": "^2.0.6",
|
||||
"@vitest/coverage-v8": "^4.0.17",
|
||||
"@vitest/coverage-v8": "^4.1.2",
|
||||
"angular-eslint": "^21.3.1",
|
||||
"eslint": "^9.39.3",
|
||||
"jsdom": "^28.1.0",
|
||||
"postcss": "^8.5.6",
|
||||
"stylelint": "^16.25.0",
|
||||
"stylelint-config-standard-scss": "^16.0.0",
|
||||
"eslint": "^10.1.0",
|
||||
"jsdom": "^29.0.1",
|
||||
"msw": "^2.12.14",
|
||||
"ng-mocks": "^14.15.2",
|
||||
"postcss": "^8.5.8",
|
||||
"stylelint": "^17.6.0",
|
||||
"stylelint-config-standard-scss": "^17.0.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.56.1",
|
||||
"vitest": "^4.0.17"
|
||||
"typescript-eslint": "^8.57.2",
|
||||
"vitest": "^4.1.2",
|
||||
"vitest-canvas-mock": "^1.1.4"
|
||||
},
|
||||
"overrides": {
|
||||
"minimatch": "^10.2.1",
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import {defineConfig, devices} from '@playwright/test';
|
||||
|
||||
const host = process.env.PLAYWRIGHT_HOST ?? '127.0.0.1';
|
||||
const port = Number(process.env.PLAYWRIGHT_PORT ?? '4301');
|
||||
const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? `http://${host}:${port}`;
|
||||
const startServer = process.env.PLAYWRIGHT_START_SERVER !== 'false';
|
||||
const reuseExistingServer = process.env.PLAYWRIGHT_REUSE_SERVER === 'true';
|
||||
const outputDir = process.env.PLAYWRIGHT_OUTPUT_DIR ?? `output/playwright-${port}`;
|
||||
const workers = Number(process.env.PLAYWRIGHT_WORKERS ?? '1');
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './playwright',
|
||||
fullyParallel: false,
|
||||
workers,
|
||||
outputDir,
|
||||
reporter: [['list']],
|
||||
retries: process.env.CI ? 1 : 0,
|
||||
use: {
|
||||
baseURL,
|
||||
trace: 'on-first-retry',
|
||||
screenshot: 'only-on-failure',
|
||||
video: 'retain-on-failure',
|
||||
},
|
||||
webServer: startServer ? {
|
||||
command: `just e2e-dev ${host} ${port}`,
|
||||
url: baseURL,
|
||||
reuseExistingServer,
|
||||
timeout: 180000,
|
||||
} : undefined,
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: {...devices['Desktop Chrome']},
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
## Playwright Harness Rules
|
||||
|
||||
This directory is the browser-test harness for the frontend. Treat it as a
|
||||
strictly controlled surface.
|
||||
|
||||
### Execution rules
|
||||
|
||||
- Never hard-code port `4200` in specs or fixtures.
|
||||
- In parallel runs, every worker must set a unique `PLAYWRIGHT_PORT`.
|
||||
- Use `PLAYWRIGHT_BASE_URL` only when attaching to an already-running app.
|
||||
- Default local command:
|
||||
|
||||
```bash
|
||||
PLAYWRIGHT_PORT=4301 just --justfile frontend/Justfile --working-directory frontend e2e-file playwright/login-and-books.spec.ts
|
||||
```
|
||||
|
||||
### Authoring rules
|
||||
|
||||
- Start from the existing scenario fixture instead of creating ad hoc route
|
||||
handlers inside a spec.
|
||||
- Keep one scenario fixture per spec file. Do not build one giant catch-all fake
|
||||
backend for unrelated areas.
|
||||
- Mock only the endpoints required by the scenario. Unexpected API calls should
|
||||
fail fast.
|
||||
- Prefer role, label, placeholder, and stable text selectors. Use CSS classes
|
||||
only when the UI has no better semantic hook.
|
||||
- Do not add reader/browser flows until they have their own dedicated scenario
|
||||
fixture and port-safe validation command.
|
||||
|
||||
### Agent rules
|
||||
|
||||
- Do not invent a new Playwright config per worker.
|
||||
- Do not change the web server port in code for one-off runs; use env vars.
|
||||
- Do not add browser specs that depend on broad route shims copied from other
|
||||
scenarios.
|
||||
- Use the `frontend/Justfile` entrypoints for browser install, server startup,
|
||||
and spec execution. Do not invoke Yarn directly from docs or ad hoc commands.
|
||||
@@ -0,0 +1,245 @@
|
||||
import type {Page, Route} from '@playwright/test';
|
||||
|
||||
const tinyPng = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4//8/AwAI/AL+Nf8zAAAAAElFTkSuQmCC',
|
||||
'base64'
|
||||
);
|
||||
|
||||
type LoginAndBooksScenario = {
|
||||
publicSettings: Record<string, unknown>;
|
||||
appSettings: Record<string, unknown>;
|
||||
user: Record<string, unknown>;
|
||||
libraries: Array<Record<string, unknown>>;
|
||||
shelves: Array<Record<string, unknown>>;
|
||||
magicShelves: Array<Record<string, unknown>>;
|
||||
books: Array<Record<string, unknown>>;
|
||||
};
|
||||
|
||||
function createJwt(expSeconds = 4_102_444_800): string {
|
||||
const header = Buffer.from(JSON.stringify({alg: 'none', typ: 'JWT'})).toString('base64url');
|
||||
const payload = Buffer.from(JSON.stringify({exp: expSeconds, sub: '1'})).toString('base64url');
|
||||
return `${header}.${payload}.`;
|
||||
}
|
||||
|
||||
function asJson(route: Route, body: unknown, status = 200): Promise<void> {
|
||||
return route.fulfill({
|
||||
status,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
function isThumbnailRequest(pathname: string): boolean {
|
||||
return pathname.startsWith('/api/v1/media/book/') && pathname.includes('/thumbnail');
|
||||
}
|
||||
|
||||
export function createLoginAndBooksScenario(): LoginAndBooksScenario {
|
||||
return {
|
||||
publicSettings: {
|
||||
oidcEnabled: false,
|
||||
remoteAuthEnabled: false,
|
||||
oidcProviderDetails: null,
|
||||
oidcForceOnlyMode: false,
|
||||
},
|
||||
appSettings: {
|
||||
remoteAuthEnabled: false,
|
||||
oidcEnabled: false,
|
||||
oidcProviderDetails: null,
|
||||
oidcForceOnlyMode: false,
|
||||
opdsServerEnabled: false,
|
||||
komgaApiEnabled: false,
|
||||
metadataProviderSettings: {},
|
||||
metadataMatchWeights: {},
|
||||
maxFileUploadSizeInMb: 128,
|
||||
},
|
||||
user: {
|
||||
id: 1,
|
||||
username: 'tester',
|
||||
name: 'Test Reader',
|
||||
email: 'tester@example.com',
|
||||
assignedLibraries: [{id: 1, name: 'Main Library'}],
|
||||
permissions: {
|
||||
admin: true,
|
||||
canManageLibrary: true,
|
||||
canUpload: true,
|
||||
canAccessBookdrop: true,
|
||||
canAccessLibraryStats: true,
|
||||
canAccessUserStats: true,
|
||||
canManageGlobalPreferences: true,
|
||||
demoUser: false,
|
||||
},
|
||||
userSettings: {
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'ASC',
|
||||
view: 'GRID',
|
||||
coverSize: 100,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: false,
|
||||
},
|
||||
overrides: [],
|
||||
},
|
||||
tableColumnPreference: [{field: 'title', visible: true, order: 0}],
|
||||
dashboardConfig: {scrollers: []},
|
||||
visibleFilters: ['author', 'series', 'bookType'],
|
||||
visibleSortFields: ['title', 'addedOn', 'lastReadTime'],
|
||||
filterMode: 'and',
|
||||
},
|
||||
},
|
||||
libraries: [],
|
||||
shelves: [],
|
||||
magicShelves: [],
|
||||
books: [
|
||||
{
|
||||
id: 1,
|
||||
libraryId: 1,
|
||||
libraryName: 'Main Library',
|
||||
fileName: 'the-mock-epub.epub',
|
||||
primaryFile: {
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
bookType: 'EPUB',
|
||||
fileName: 'the-mock-epub.epub',
|
||||
filePath: '/books/the-mock-epub.epub',
|
||||
},
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'The Mock EPUB',
|
||||
authors: ['A. Author'],
|
||||
seriesName: 'Smoke Series',
|
||||
seriesNumber: 1,
|
||||
language: 'en',
|
||||
},
|
||||
shelves: [{id: 101, name: 'Featured'}],
|
||||
readStatus: 'UNREAD',
|
||||
addedOn: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
libraryId: 1,
|
||||
libraryName: 'Main Library',
|
||||
fileName: 'the-mock-comic.cbz',
|
||||
primaryFile: {
|
||||
id: 21,
|
||||
bookId: 2,
|
||||
bookType: 'CBX',
|
||||
fileName: 'the-mock-comic.cbz',
|
||||
filePath: '/books/the-mock-comic.cbz',
|
||||
},
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'The Mock Comic',
|
||||
authors: ['B. Artist'],
|
||||
seriesName: 'Comic Smoke Series',
|
||||
seriesNumber: 7,
|
||||
language: 'en',
|
||||
},
|
||||
shelves: [],
|
||||
readStatus: 'READING',
|
||||
addedOn: '2025-01-03T00:00:00Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export async function seedAuthenticatedSession(page: Page): Promise<void> {
|
||||
const accessToken = createJwt();
|
||||
const refreshToken = 'refresh-token';
|
||||
|
||||
await page.addInitScript(
|
||||
({accessTokenValue, refreshTokenValue}) => {
|
||||
localStorage.setItem('accessToken_Internal', accessTokenValue);
|
||||
localStorage.setItem('refreshToken_Internal', refreshTokenValue);
|
||||
},
|
||||
{accessTokenValue: accessToken, refreshTokenValue: refreshToken}
|
||||
);
|
||||
}
|
||||
|
||||
export async function installLoginAndBooksRoutes(
|
||||
page: Page,
|
||||
scenario = createLoginAndBooksScenario()
|
||||
): Promise<void> {
|
||||
await page.route('**/api/**', async route => {
|
||||
const request = route.request();
|
||||
const url = new URL(request.url());
|
||||
const {pathname} = url;
|
||||
const method = request.method();
|
||||
|
||||
if (pathname === '/api/public/settings' && method === 'HEAD') {
|
||||
await route.fulfill({status: 200, body: ''});
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/setup/status' && method === 'GET') {
|
||||
await asJson(route, {data: true});
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/public-settings' && method === 'GET') {
|
||||
await asJson(route, scenario.publicSettings);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/settings' && method === 'GET') {
|
||||
await asJson(route, scenario.appSettings);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/auth/login' && method === 'POST') {
|
||||
await asJson(route, {
|
||||
accessToken: createJwt(),
|
||||
refreshToken: 'refresh-token',
|
||||
isDefaultPassword: 'false',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/auth/refresh' && method === 'POST') {
|
||||
await asJson(route, {
|
||||
accessToken: createJwt(),
|
||||
refreshToken: 'refresh-token',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/users/me' && method === 'GET') {
|
||||
await asJson(route, scenario.user);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/libraries' && method === 'GET') {
|
||||
await asJson(route, scenario.libraries);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/shelves' && method === 'GET') {
|
||||
await asJson(route, scenario.shelves);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/magic-shelves' && method === 'GET') {
|
||||
await asJson(route, scenario.magicShelves);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/books' && method === 'GET') {
|
||||
await asJson(route, scenario.books);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isThumbnailRequest(pathname) && method === 'GET') {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'image/png',
|
||||
body: tinyPng,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unhandled login-and-books route: ${method} ${pathname}`);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {expect, test} from '@playwright/test';
|
||||
import {
|
||||
createLoginAndBooksScenario,
|
||||
installLoginAndBooksRoutes,
|
||||
seedAuthenticatedSession
|
||||
} from './login-and-books.fixture';
|
||||
|
||||
test.describe('login and book browser smoke', () => {
|
||||
test('local login reaches the dashboard welcome state', async ({page}) => {
|
||||
await installLoginAndBooksRoutes(page, createLoginAndBooksScenario());
|
||||
|
||||
await page.goto('/login');
|
||||
await expect(page.locator('#username')).toBeVisible();
|
||||
await page.locator('#username').fill('tester');
|
||||
await page.locator('#password input').fill('secret-password');
|
||||
await page.getByRole('button', {name: /sign in/i}).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/dashboard$/);
|
||||
await expect(page.getByRole('button', {name: /create library/i})).toBeVisible();
|
||||
});
|
||||
|
||||
test('authenticated users can open the all books browser', async ({page}) => {
|
||||
const scenario = createLoginAndBooksScenario();
|
||||
await seedAuthenticatedSession(page);
|
||||
await installLoginAndBooksRoutes(page, scenario);
|
||||
|
||||
await page.goto('/all-books');
|
||||
|
||||
await expect(page).toHaveURL(/\/all-books$/);
|
||||
await expect(page.getByText('The Mock EPUB')).toBeVisible();
|
||||
await expect(page.getByText('The Mock Comic')).toBeVisible();
|
||||
await expect(page.locator('input[placeholder]')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import {readFileSync} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
|
||||
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const frontendRoot = path.resolve(scriptDir, '..');
|
||||
const reportPath = path.resolve(frontendRoot, 'coverage/grimmory/coverage-final.json');
|
||||
const rootPrefix = path.resolve(frontendRoot, 'src/app') + path.sep;
|
||||
const report = JSON.parse(readFileSync(reportPath, 'utf8'));
|
||||
|
||||
function summarizeCounts(counts) {
|
||||
if (!counts) {
|
||||
return {covered: 0, total: 0, pct: 100};
|
||||
}
|
||||
const values = Object.values(counts);
|
||||
const covered = values.filter(value => value > 0).length;
|
||||
const total = values.length;
|
||||
|
||||
return {covered, total, pct: total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))};
|
||||
}
|
||||
|
||||
function summarizeBranches(branches) {
|
||||
if (!branches) {
|
||||
return {covered: 0, total: 0, pct: 100};
|
||||
}
|
||||
|
||||
const values = Object.values(branches).flatMap(branchHits => Array.isArray(branchHits) ? branchHits : []);
|
||||
const covered = values.filter(value => value > 0).length;
|
||||
const total = values.length;
|
||||
|
||||
return {covered, total, pct: total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))};
|
||||
}
|
||||
|
||||
function summarizeLines(entry) {
|
||||
const lineKeys = new Set();
|
||||
const coveredLineKeys = new Set();
|
||||
|
||||
for (const [statementId, location] of Object.entries(entry.statementMap ?? {})) {
|
||||
for (let line = location.start.line; line <= location.end.line; line += 1) {
|
||||
lineKeys.add(line);
|
||||
if ((entry.s?.[statementId] ?? 0) > 0) {
|
||||
coveredLineKeys.add(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const total = lineKeys.size;
|
||||
const covered = coveredLineKeys.size;
|
||||
|
||||
return {covered, total, pct: total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))};
|
||||
}
|
||||
|
||||
function summarizeFile(entry) {
|
||||
return {
|
||||
statements: summarizeCounts(entry.s),
|
||||
branches: summarizeBranches(entry.b),
|
||||
functions: summarizeCounts(entry.f),
|
||||
lines: summarizeLines(entry),
|
||||
};
|
||||
}
|
||||
|
||||
const buckets = new Map();
|
||||
const worstFiles = [];
|
||||
let totals = {
|
||||
statements: {covered: 0, total: 0},
|
||||
branches: {covered: 0, total: 0},
|
||||
functions: {covered: 0, total: 0},
|
||||
lines: {covered: 0, total: 0},
|
||||
};
|
||||
|
||||
for (const [absolutePath, entry] of Object.entries(report)) {
|
||||
if (!absolutePath.startsWith(rootPrefix) || absolutePath.endsWith('.spec.ts')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = absolutePath.slice(rootPrefix.length).replaceAll(path.sep, '/');
|
||||
const [topLevel, featureName] = relativePath.split('/');
|
||||
const bucketName = topLevel === 'features'
|
||||
? `features/${featureName}`
|
||||
: ['core', 'shared'].includes(topLevel)
|
||||
? topLevel
|
||||
: 'app-root';
|
||||
const fileSummary = summarizeFile(entry);
|
||||
|
||||
worstFiles.push({path: relativePath, branchPct: fileSummary.branches.pct});
|
||||
|
||||
for (const metric of ['statements', 'branches', 'functions', 'lines']) {
|
||||
totals[metric].covered += fileSummary[metric].covered;
|
||||
totals[metric].total += fileSummary[metric].total;
|
||||
}
|
||||
|
||||
const bucket = buckets.get(bucketName) ?? {
|
||||
statements: {covered: 0, total: 0},
|
||||
branches: {covered: 0, total: 0},
|
||||
functions: {covered: 0, total: 0},
|
||||
lines: {covered: 0, total: 0},
|
||||
files: 0,
|
||||
};
|
||||
|
||||
for (const metric of ['statements', 'branches', 'functions', 'lines']) {
|
||||
bucket[metric].covered += fileSummary[metric].covered;
|
||||
bucket[metric].total += fileSummary[metric].total;
|
||||
}
|
||||
bucket.files += 1;
|
||||
|
||||
buckets.set(bucketName, bucket);
|
||||
}
|
||||
|
||||
function toPct({covered, total}) {
|
||||
return total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2));
|
||||
}
|
||||
|
||||
console.log('Global coverage');
|
||||
for (const metric of ['statements', 'branches', 'functions', 'lines']) {
|
||||
console.log(`- ${metric}: ${toPct(totals[metric])}% (${totals[metric].covered}/${totals[metric].total})`);
|
||||
}
|
||||
|
||||
console.log('\nCoverage by bucket');
|
||||
for (const [bucketName, bucket] of [...buckets.entries()].sort((a, b) => toPct(a[1].branches) - toPct(b[1].branches))) {
|
||||
console.log(
|
||||
`- ${bucketName}: statements ${toPct(bucket.statements)}%, branches ${toPct(bucket.branches)}%, functions ${toPct(bucket.functions)}% across ${bucket.files} files`
|
||||
+ `, lines ${toPct(bucket.lines)}%`
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\nWorst files by branch coverage');
|
||||
for (const file of worstFiles.sort((a, b) => a.branchPct - b.branchPct).slice(0, 15)) {
|
||||
console.log(`- ${file.path}: ${file.branchPct}%`);
|
||||
}
|
||||
@@ -1,111 +1,247 @@
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {signal} from '@angular/core';
|
||||
import {AppComponent} from './app.component';
|
||||
import {AuthInitializationService} from './core/security/auth-initialization-service';
|
||||
import {of} from 'rxjs';
|
||||
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||
import {BookService} from './features/book/service/book.service';
|
||||
import {NotificationEventService} from './shared/websocket/notification-event.service';
|
||||
import {AppConfigService} from './shared/service/app-config.service';
|
||||
import {MetadataProgressService} from './shared/service/metadata-progress.service';
|
||||
import {BookdropFileService} from './features/bookdrop/service/bookdrop-file.service';
|
||||
import {TaskService} from './features/settings/task-management/task.service';
|
||||
import {LibraryService} from './features/book/service/library.service';
|
||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
|
||||
import {TranslocoTestingModule} from '@jsverse/transloco';
|
||||
import {AuthService} from './shared/service/auth.service';
|
||||
import { signal } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { TranslocoTestingModule } from "@jsverse/transloco";
|
||||
import { Subject } from "rxjs";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
describe('AppComponent offline detection', () => {
|
||||
import { AppComponent } from "./app.component";
|
||||
import { AuthInitializationService } from "./core/security/auth-initialization-service";
|
||||
import { RxStompService } from "./shared/websocket/rx-stomp.service";
|
||||
import { BookService } from "./features/book/service/book.service";
|
||||
import { NotificationEventService } from "./shared/websocket/notification-event.service";
|
||||
import { AppConfigService } from "./shared/service/app-config.service";
|
||||
import { MetadataProgressService } from "./shared/service/metadata-progress.service";
|
||||
import { BookdropFileService } from "./features/bookdrop/service/bookdrop-file.service";
|
||||
import { TaskService } from "./features/settings/task-management/task.service";
|
||||
import { LibraryService } from "./features/book/service/library.service";
|
||||
import { LibraryHealthService } from "./features/book/service/library-health.service";
|
||||
import { LibraryLoadingService } from "./features/library-creator/library-loading.service";
|
||||
import { AuthService } from "./shared/service/auth.service";
|
||||
import { ConfirmationService } from "primeng/api";
|
||||
import { MessageService } from "primeng/api";
|
||||
|
||||
interface StompMessage {
|
||||
body: string;
|
||||
}
|
||||
|
||||
describe("AppComponent", () => {
|
||||
let fixture: ComponentFixture<AppComponent>;
|
||||
let component: AppComponent;
|
||||
let topics: Map<string, Subject<StompMessage>>;
|
||||
let rxStompService: { watch: ReturnType<typeof vi.fn> };
|
||||
let bookService: {
|
||||
handleNewlyCreatedBook: ReturnType<typeof vi.fn>;
|
||||
handleBookUpdate: ReturnType<typeof vi.fn>;
|
||||
handleMultipleBookCoverPatches: ReturnType<typeof vi.fn>;
|
||||
handleRemovedBookIds: ReturnType<typeof vi.fn>;
|
||||
handleMultipleBookUpdates: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let notificationEventService: {
|
||||
handleNewNotification: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let metadataProgressService: {
|
||||
handleIncomingProgress: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookdropFileService: { handleIncomingFile: ReturnType<typeof vi.fn> };
|
||||
let taskService: { handleTaskProgress: ReturnType<typeof vi.fn> };
|
||||
let libraryHealthService: { initialize: ReturnType<typeof vi.fn> };
|
||||
let libraryLoadingService: {
|
||||
showBookLoadingProgress: ReturnType<typeof vi.fn>;
|
||||
hide: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let authService: { forceLogout: ReturnType<typeof vi.fn> };
|
||||
let libraryService: {
|
||||
largeLibraryLoading: ReturnType<typeof signal>;
|
||||
setLargeLibraryLoading: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function createTopicStream(topic: string): Subject<StompMessage> {
|
||||
const stream = new Subject<StompMessage>();
|
||||
topics.set(topic, stream);
|
||||
return stream;
|
||||
}
|
||||
|
||||
function configureComponent(
|
||||
authReady = true,
|
||||
largeLibraryLoading = { isLoading: false, expectedCount: 0 },
|
||||
): void {
|
||||
topics = new Map();
|
||||
rxStompService = {
|
||||
watch: vi.fn((topic: string) =>
|
||||
(topics.get(topic) ?? createTopicStream(topic)).asObservable(),
|
||||
),
|
||||
};
|
||||
bookService = {
|
||||
handleNewlyCreatedBook: vi.fn(),
|
||||
handleBookUpdate: vi.fn(),
|
||||
handleMultipleBookCoverPatches: vi.fn(),
|
||||
handleRemovedBookIds: vi.fn(),
|
||||
handleMultipleBookUpdates: vi.fn(),
|
||||
};
|
||||
notificationEventService = { handleNewNotification: vi.fn() };
|
||||
metadataProgressService = { handleIncomingProgress: vi.fn() };
|
||||
bookdropFileService = { handleIncomingFile: vi.fn() };
|
||||
taskService = { handleTaskProgress: vi.fn() };
|
||||
libraryHealthService = { initialize: vi.fn() };
|
||||
libraryLoadingService = {
|
||||
showBookLoadingProgress: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
};
|
||||
authService = { forceLogout: vi.fn() };
|
||||
libraryService = {
|
||||
largeLibraryLoading: signal(largeLibraryLoading),
|
||||
setLargeLibraryLoading: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [TranslocoTestingModule.forRoot({langs: {}})],
|
||||
imports: [TranslocoTestingModule.forRoot({ langs: {} })],
|
||||
providers: [
|
||||
{provide: AuthInitializationService, useValue: {initialized: signal(false)}},
|
||||
{provide: RxStompService, useValue: {watch: vi.fn(() => of())}},
|
||||
{provide: BookService, useValue: {}},
|
||||
{provide: NotificationEventService, useValue: {}},
|
||||
{provide: AppConfigService, useValue: {}},
|
||||
{provide: MetadataProgressService, useValue: {}},
|
||||
{provide: BookdropFileService, useValue: {}},
|
||||
{provide: TaskService, useValue: {}},
|
||||
{provide: LibraryService, useValue: {largeLibraryLoading: signal({isLoading: false, expectedCount: 0})}},
|
||||
{provide: LibraryHealthService, useValue: {initialize: vi.fn()}},
|
||||
{provide: LibraryLoadingService, useValue: {hide: vi.fn()}},
|
||||
{provide: AuthService, useValue: {token: signal(null)}},
|
||||
]
|
||||
{
|
||||
provide: AuthInitializationService,
|
||||
useValue: { initialized: signal(authReady) },
|
||||
},
|
||||
{ provide: RxStompService, useValue: rxStompService },
|
||||
{ provide: BookService, useValue: bookService },
|
||||
{
|
||||
provide: NotificationEventService,
|
||||
useValue: notificationEventService,
|
||||
},
|
||||
{ provide: AppConfigService, useValue: {} },
|
||||
{ provide: MetadataProgressService, useValue: metadataProgressService },
|
||||
{ provide: BookdropFileService, useValue: bookdropFileService },
|
||||
{ provide: TaskService, useValue: taskService },
|
||||
{ provide: LibraryService, useValue: libraryService },
|
||||
{ provide: LibraryHealthService, useValue: libraryHealthService },
|
||||
{ provide: LibraryLoadingService, useValue: libraryLoadingService },
|
||||
{ provide: AuthService, useValue: authService },
|
||||
ConfirmationService,
|
||||
MessageService,
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(AppComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should initialize with offline set to false', () => {
|
||||
expect(component.offline).toBe(false);
|
||||
afterEach(() => {
|
||||
fixture?.destroy();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should set offline to false when online event fires', () => {
|
||||
component.offline = true;
|
||||
window.dispatchEvent(new Event('online'));
|
||||
expect(component.offline).toBe(false);
|
||||
it("boots the websocket wiring when auth initialization is ready", () => {
|
||||
configureComponent(true);
|
||||
|
||||
expect(component.loading).toBe(false);
|
||||
expect(libraryHealthService.initialize).toHaveBeenCalledOnce();
|
||||
expect(rxStompService.watch).toHaveBeenCalledWith("/user/queue/book-add");
|
||||
expect(rxStompService.watch).toHaveBeenCalledWith(
|
||||
"/user/queue/session-revoked",
|
||||
);
|
||||
});
|
||||
|
||||
it('should not show offline when server is reachable despite browser offline event', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 200}));
|
||||
it("routes websocket book notifications through the large library loading branch", () => {
|
||||
configureComponent(true, { isLoading: true, expectedCount: 2 });
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
topics
|
||||
.get("/user/queue/book-add")
|
||||
?.next({ body: JSON.stringify({ metadata: { title: "First" } }) });
|
||||
topics
|
||||
.get("/user/queue/book-add")
|
||||
?.next({ body: JSON.stringify({ metadata: { title: "Second" } }) });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(false);
|
||||
expect(bookService.handleNewlyCreatedBook).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
libraryLoadingService.showBookLoadingProgress,
|
||||
).toHaveBeenNthCalledWith(1, "First", 1, 2);
|
||||
expect(
|
||||
libraryLoadingService.showBookLoadingProgress,
|
||||
).toHaveBeenNthCalledWith(2, "Second", 2, 2);
|
||||
expect(libraryService.setLargeLibraryLoading).toHaveBeenCalledWith(
|
||||
false,
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards websocket updates to the matching root services", () => {
|
||||
configureComponent(true);
|
||||
|
||||
topics
|
||||
.get("/user/queue/book-update")
|
||||
?.next({ body: JSON.stringify({ id: 1 }) });
|
||||
topics
|
||||
.get("/user/queue/books-cover-update")
|
||||
?.next({ body: JSON.stringify([{ id: 1 }]) });
|
||||
topics
|
||||
.get("/user/queue/books-remove")
|
||||
?.next({ body: JSON.stringify([1, 2]) });
|
||||
topics
|
||||
.get("/user/queue/book-metadata-update")
|
||||
?.next({ body: JSON.stringify({ id: 2 }) });
|
||||
topics
|
||||
.get("/user/queue/book-metadata-batch-update")
|
||||
?.next({ body: JSON.stringify([{ id: 3 }]) });
|
||||
topics
|
||||
.get("/user/queue/book-metadata-batch-progress")
|
||||
?.next({ body: JSON.stringify({ taskId: "task-1" }) });
|
||||
topics
|
||||
.get("/user/queue/log")
|
||||
?.next({ body: JSON.stringify({ message: "info", severity: "INFO" }) });
|
||||
topics
|
||||
.get("/user/queue/bookdrop-file")
|
||||
?.next({ body: JSON.stringify({ pendingCount: 1, totalCount: 2 }) });
|
||||
topics
|
||||
.get("/user/queue/task-progress")
|
||||
?.next({ body: JSON.stringify({ taskId: "task-2" }) });
|
||||
|
||||
expect(bookService.handleBookUpdate).toHaveBeenCalledWith({ id: 1 });
|
||||
expect(bookService.handleMultipleBookCoverPatches).toHaveBeenCalledWith([
|
||||
{ id: 1 },
|
||||
]);
|
||||
expect(bookService.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]);
|
||||
expect(bookService.handleMultipleBookUpdates).toHaveBeenCalledWith([
|
||||
{ id: 3 },
|
||||
]);
|
||||
expect(metadataProgressService.handleIncomingProgress).toHaveBeenCalledWith(
|
||||
{ taskId: "task-1" },
|
||||
);
|
||||
expect(notificationEventService.handleNewNotification).toHaveBeenCalledWith(
|
||||
{
|
||||
message: "info",
|
||||
severity: "INFO",
|
||||
},
|
||||
);
|
||||
expect(bookdropFileService.handleIncomingFile).toHaveBeenCalledWith({
|
||||
pendingCount: 1,
|
||||
totalCount: 2,
|
||||
});
|
||||
expect(taskService.handleTaskProgress).toHaveBeenCalledWith({
|
||||
taskId: "task-2",
|
||||
});
|
||||
});
|
||||
|
||||
it('should show offline when server is unreachable on browser offline event', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('Failed to fetch'));
|
||||
it("forces logout when the session is revoked", () => {
|
||||
configureComponent(true);
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
topics.get("/user/queue/session-revoked")?.next({ body: "" });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(true);
|
||||
});
|
||||
expect(authService.forceLogout).toHaveBeenCalledWith("session_revoked");
|
||||
});
|
||||
|
||||
it('should ping server with HEAD method and no-store cache', async () => {
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 200}));
|
||||
it("unsubscribes and hides the loading overlay when destroyed", () => {
|
||||
configureComponent(true);
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
component.ngOnDestroy();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(fetchSpy).toHaveBeenCalledWith('/api/public/settings', {method: 'HEAD', cache: 'no-store'});
|
||||
});
|
||||
});
|
||||
|
||||
it('should treat server errors as reachable', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 500}));
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should treat network timeout as unreachable', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('network timeout'));
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(true);
|
||||
});
|
||||
expect(libraryLoadingService.hide).toHaveBeenCalledOnce();
|
||||
topics
|
||||
.get("/user/queue/book-update")
|
||||
?.next({ body: JSON.stringify({ id: 99 }) });
|
||||
expect(bookService.handleBookUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {routes} from './app.routes';
|
||||
import {AuthGuard} from './core/security/auth.guard';
|
||||
import {BookdropGuard} from './core/security/guards/bookdrop.guard';
|
||||
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
|
||||
import {LibraryStatsGuard} from './core/security/guards/library-stats.guard';
|
||||
import {UserStatsGuard} from './core/security/guards/user-stats.guard';
|
||||
import {LoginGuard} from './shared/components/setup/login.guard';
|
||||
import {SetupGuard} from './shared/components/setup/setup.guard';
|
||||
import {SetupRedirectGuard} from './shared/components/setup/setup-redirect.guard';
|
||||
|
||||
describe('app routes', () => {
|
||||
it('defines the setup and auth entry routes', () => {
|
||||
const rootRedirect = routes.find(route => route.path === '' && route.pathMatch === 'full');
|
||||
const setupRoute = routes.find(route => route.path === 'setup');
|
||||
const loginRoute = routes.find(route => route.path === 'login');
|
||||
const wildcardRoute = routes.find(route => route.path === '**');
|
||||
|
||||
expect(rootRedirect?.canActivate).toEqual([SetupRedirectGuard]);
|
||||
expect(setupRoute?.canActivate).toEqual([SetupGuard]);
|
||||
expect(loginRoute?.canActivate).toEqual([LoginGuard]);
|
||||
expect(wildcardRoute?.redirectTo).toBe('login');
|
||||
});
|
||||
|
||||
it('defines the authenticated shell routes behind the auth guard', () => {
|
||||
const shellRoute = routes.find(route => route.path === '' && Array.isArray(route.children));
|
||||
const children = shellRoute?.children ?? [];
|
||||
|
||||
expect(children).toHaveLength(17);
|
||||
expect(children.find(route => route.path === 'dashboard')?.canActivate).toEqual([AuthGuard]);
|
||||
expect(children.find(route => route.path === 'all-books')?.canActivate).toEqual([AuthGuard]);
|
||||
expect(children.find(route => route.path === 'magic-shelf/:magicShelfId/books')?.canActivate).toEqual([AuthGuard]);
|
||||
expect(children.find(route => route.path === 'notebook')?.canActivate).toEqual([AuthGuard]);
|
||||
});
|
||||
|
||||
it('defines guarded lazy routes for metadata, stats, and bookdrop', () => {
|
||||
const shellRoute = routes.find(route => route.path === '' && Array.isArray(route.children));
|
||||
const children = shellRoute?.children ?? [];
|
||||
|
||||
expect(children.find(route => route.path === 'bookdrop')?.canActivate).toEqual([BookdropGuard]);
|
||||
expect(children.find(route => route.path === 'metadata-manager')?.canActivate).toEqual([EditMetadataGuard]);
|
||||
expect(children.find(route => route.path === 'library-stats')?.canActivate).toEqual([LibraryStatsGuard]);
|
||||
expect(children.find(route => route.path === 'reading-stats')?.canActivate).toEqual([UserStatsGuard]);
|
||||
|
||||
expect(typeof children.find(route => route.path === 'settings')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'series')?.loadComponent).toBe('function');
|
||||
expect(typeof children.find(route => route.path === 'book/:bookId')?.loadComponent).toBe('function');
|
||||
});
|
||||
|
||||
it('defines the dedicated reader routes outside the shell', () => {
|
||||
expect(routes.find(route => route.path === 'pdf-reader/book/:bookId')?.canActivate).toEqual([AuthGuard]);
|
||||
expect(routes.find(route => route.path === 'ebook-reader/book/:bookId')?.canActivate).toEqual([AuthGuard]);
|
||||
expect(routes.find(route => route.path === 'cbx-reader/book/:bookId')?.canActivate).toEqual([AuthGuard]);
|
||||
expect(routes.find(route => route.path === 'audiobook-player/book/:bookId')?.canActivate).toEqual([AuthGuard]);
|
||||
});
|
||||
|
||||
it('keeps the callback and password routes outside the authenticated shell', () => {
|
||||
expect(routes.find(route => route.path === 'oauth2-callback')?.component).toBeDefined();
|
||||
expect(routes.find(route => route.path === 'change-password')?.component).toBeDefined();
|
||||
expect(routes.find(route => route.path === 'change-password')?.canActivate).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {environment} from '../../../environments/environment';
|
||||
import {API_CONFIG} from './api-config';
|
||||
|
||||
describe('API_CONFIG', () => {
|
||||
it('re-exports the environment API config object', () => {
|
||||
expect(API_CONFIG).toBe(environment.API_CONFIG);
|
||||
});
|
||||
|
||||
it('exposes a defined config value', () => {
|
||||
expect(API_CONFIG).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {initializeLanguage, LANG_STORAGE_KEY, LEGACY_LANG_STORAGE_KEY} from './language-initializer';
|
||||
|
||||
describe('initializeLanguage', () => {
|
||||
const translocoService = {
|
||||
setActiveLang: vi.fn(),
|
||||
load: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
localStorage.clear();
|
||||
translocoService.setActiveLang.mockReset();
|
||||
translocoService.load.mockReset();
|
||||
translocoService.load.mockReturnValue(of({}));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('uses the current persisted language when it is available', async () => {
|
||||
localStorage.setItem(LANG_STORAGE_KEY, 'de');
|
||||
|
||||
const initializer = TestBed.runInInjectionContext(() => initializeLanguage());
|
||||
|
||||
await TestBed.runInInjectionContext(() => initializer());
|
||||
|
||||
expect(translocoService.setActiveLang).toHaveBeenCalledWith('de');
|
||||
expect(translocoService.load).toHaveBeenCalledWith('de');
|
||||
expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('de');
|
||||
});
|
||||
|
||||
it('migrates the legacy persisted language key', async () => {
|
||||
localStorage.setItem(LEGACY_LANG_STORAGE_KEY, 'fr');
|
||||
|
||||
const initializer = TestBed.runInInjectionContext(() => initializeLanguage());
|
||||
|
||||
await TestBed.runInInjectionContext(() => initializer());
|
||||
|
||||
expect(translocoService.setActiveLang).toHaveBeenCalledWith('fr');
|
||||
expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('fr');
|
||||
});
|
||||
|
||||
it('prefers the exact browser locale when it is available', async () => {
|
||||
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('pt');
|
||||
|
||||
const initializer = TestBed.runInInjectionContext(() => initializeLanguage());
|
||||
|
||||
await TestBed.runInInjectionContext(() => initializer());
|
||||
|
||||
expect(translocoService.setActiveLang).toHaveBeenCalledWith('pt');
|
||||
expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('pt');
|
||||
});
|
||||
|
||||
it('falls back to the browser base language when the full locale is unavailable', async () => {
|
||||
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('pt-BR');
|
||||
|
||||
const initializer = TestBed.runInInjectionContext(() => initializeLanguage());
|
||||
|
||||
await TestBed.runInInjectionContext(() => initializer());
|
||||
|
||||
expect(translocoService.setActiveLang).toHaveBeenCalledWith('pt');
|
||||
expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('pt');
|
||||
});
|
||||
|
||||
it('falls back to english when there is no supported saved or browser language', async () => {
|
||||
localStorage.setItem(LANG_STORAGE_KEY, 'zz');
|
||||
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zz-ZZ');
|
||||
|
||||
const initializer = TestBed.runInInjectionContext(() => initializeLanguage());
|
||||
|
||||
await TestBed.runInInjectionContext(() => initializer());
|
||||
|
||||
expect(translocoService.setActiveLang).toHaveBeenCalledWith('en');
|
||||
expect(translocoService.load).toHaveBeenCalledWith('en');
|
||||
expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('en');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import en from '../../../i18n/en';
|
||||
import de from '../../../i18n/de';
|
||||
import {AVAILABLE_LANGS, EN_TRANSLATIONS, LANG_LABELS, TranslocoInlineLoader} from './transloco-loader';
|
||||
|
||||
describe('TranslocoInlineLoader', () => {
|
||||
it('returns the english translations for the default language', async () => {
|
||||
const loader = new TranslocoInlineLoader();
|
||||
const translation = await firstValueFrom(loader.getTranslation('en'));
|
||||
|
||||
expect(translation).toBe(EN_TRANSLATIONS);
|
||||
expect(translation['auth']['login']['sessionRevoked']).toBe(en['auth']['login']['sessionRevoked']);
|
||||
});
|
||||
|
||||
it('falls back to english for unsupported languages', async () => {
|
||||
const loader = new TranslocoInlineLoader();
|
||||
const translation = await firstValueFrom(loader.getTranslation('xx'));
|
||||
|
||||
expect(translation).toBe(EN_TRANSLATIONS);
|
||||
});
|
||||
|
||||
it('loads and merges a lazy language bundle over english', async () => {
|
||||
const loader = new TranslocoInlineLoader();
|
||||
const translation = await firstValueFrom(loader.getTranslation('de'));
|
||||
|
||||
expect(translation['auth']['login']['oidcInitError']).toBe(de['auth']['login']['oidcInitError']);
|
||||
expect(translation['auth']['login']['sessionRevoked']).toBe(de['auth']['login']['sessionRevoked']);
|
||||
expect(translation['auth']['login']['oidcErrors']['providerUnreachable']).toBe(de['auth']['login']['oidcErrors']['providerUnreachable']);
|
||||
});
|
||||
|
||||
it('exposes the available language metadata', () => {
|
||||
expect(AVAILABLE_LANGS).toContain('en');
|
||||
expect(AVAILABLE_LANGS).toContain('de');
|
||||
expect(LANG_LABELS['en']).toBe('English');
|
||||
expect(LANG_LABELS['de']).toBe('Deutsch');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import {Injector, runInInjectionContext} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service';
|
||||
import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service';
|
||||
import {CustomReuseStrategy} from './custom-reuse-strategy';
|
||||
|
||||
function createRoute(path: string, params: Record<string, string> = {}): ActivatedRouteSnapshot {
|
||||
return {
|
||||
routeConfig: {path},
|
||||
params
|
||||
} as ActivatedRouteSnapshot;
|
||||
}
|
||||
|
||||
describe('CustomReuseStrategy', () => {
|
||||
const handle = {componentRef: {} as never} as DetachedRouteHandle;
|
||||
|
||||
let strategy: CustomReuseStrategy;
|
||||
let scrollService: BookBrowserScrollService;
|
||||
let selectionService: BookSelectionService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
|
||||
scrollService = new BookBrowserScrollService();
|
||||
selectionService = new BookSelectionService();
|
||||
const injector = Injector.create({
|
||||
providers: [
|
||||
{provide: BookBrowserScrollService, useValue: scrollService},
|
||||
{provide: BookSelectionService, useValue: selectionService},
|
||||
]
|
||||
});
|
||||
strategy = runInInjectionContext(injector, () => new CustomReuseStrategy());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('stores and reattaches book browser routes with their saved scroll position', async () => {
|
||||
vi.useFakeTimers();
|
||||
const route = createRoute('all-books', {libraryId: '42'});
|
||||
const scrollElement = document.createElement('div');
|
||||
scrollElement.className = 'virtual-scroller';
|
||||
const querySelectorSpy = vi.spyOn(document, 'querySelector').mockReturnValue(scrollElement);
|
||||
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
|
||||
|
||||
scrollService.savePosition('all-books:42', 321);
|
||||
strategy.store(route, handle);
|
||||
|
||||
expect(strategy.shouldDetach(route)).toBe(true);
|
||||
expect(strategy.shouldAttach(route)).toBe(true);
|
||||
expect(deselectSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
const restored = strategy.retrieve(route);
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
expect(restored).toBe(handle);
|
||||
expect(querySelectorSpy).toHaveBeenCalledWith('.virtual-scroller');
|
||||
expect(scrollElement.scrollTop).toBe(321);
|
||||
});
|
||||
|
||||
it('ignores non-book routes when storing or attaching', () => {
|
||||
const route = createRoute('login');
|
||||
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
|
||||
|
||||
strategy.store(route, handle);
|
||||
|
||||
expect(strategy.shouldDetach(route)).toBe(false);
|
||||
expect(strategy.shouldAttach(route)).toBe(false);
|
||||
expect(strategy.retrieve(route)).toBeNull();
|
||||
expect(deselectSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores null handles for book browser routes', () => {
|
||||
const route = createRoute('series', {seriesId: '77'});
|
||||
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
|
||||
|
||||
strategy.store(route, null);
|
||||
|
||||
expect(strategy.shouldDetach(route)).toBe(true);
|
||||
expect(strategy.shouldAttach(route)).toBe(false);
|
||||
expect(strategy.retrieve(route)).toBeNull();
|
||||
expect(deselectSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns a stored handle without touching the DOM when no scroll position was saved', () => {
|
||||
const route = createRoute('authors');
|
||||
const querySelectorSpy = vi.spyOn(document, 'querySelector');
|
||||
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
|
||||
|
||||
strategy.store(route, handle);
|
||||
|
||||
expect(deselectSpy).toHaveBeenCalledOnce();
|
||||
expect(strategy.shouldAttach(route)).toBe(true);
|
||||
expect(strategy.retrieve(route)).toBe(handle);
|
||||
expect(querySelectorSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reuses routes only when the route config and params both match', () => {
|
||||
const routeConfig = {path: 'series'};
|
||||
const current = {
|
||||
routeConfig,
|
||||
params: {seriesId: '12'}
|
||||
} as unknown as ActivatedRouteSnapshot;
|
||||
const same = {
|
||||
routeConfig,
|
||||
params: {seriesId: '12'}
|
||||
} as unknown as ActivatedRouteSnapshot;
|
||||
const differentParams = {
|
||||
routeConfig,
|
||||
params: {seriesId: '99'}
|
||||
} as unknown as ActivatedRouteSnapshot;
|
||||
const differentConfig = {
|
||||
routeConfig: {path: 'authors'},
|
||||
params: {seriesId: '12'}
|
||||
} as unknown as ActivatedRouteSnapshot;
|
||||
|
||||
expect(strategy.shouldReuseRoute(same, current)).toBe(true);
|
||||
expect(strategy.shouldReuseRoute(differentParams, current)).toBe(false);
|
||||
expect(strategy.shouldReuseRoute(differentConfig, current)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
|
||||
describe('AuthInitializationService', () => {
|
||||
it('starts in an uninitialized state and can be marked as initialized', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [AuthInitializationService],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthInitializationService);
|
||||
|
||||
expect(service.initialized()).toBe(false);
|
||||
|
||||
service.markAsInitialized();
|
||||
|
||||
expect(service.initialized()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,71 +1,149 @@
|
||||
import {Injector, runInInjectionContext} from '@angular/core';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {initializeAuthFactory} from './auth-initializer';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
|
||||
import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental';
|
||||
import {initializeAuthFactory} from './auth-initializer';
|
||||
|
||||
describe('initializeAuthFactory', () => {
|
||||
let authInitService: AuthInitializationService;
|
||||
let mockQueryClient: { fetchQuery: ReturnType<typeof vi.fn> };
|
||||
const authInitService = {
|
||||
markAsInitialized: vi.fn(),
|
||||
};
|
||||
|
||||
const defaultPublicSettings: PublicAppSettings = {
|
||||
oidcEnabled: false,
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
remoteLogin: vi.fn(),
|
||||
initializeWebSocketConnection: vi.fn(),
|
||||
};
|
||||
|
||||
const queryClient = {
|
||||
fetchQuery: vi.fn(),
|
||||
};
|
||||
|
||||
const appSettingsService = {
|
||||
getPublicSettingsQueryOptions: vi.fn(() => ({queryKey: ['public-settings']})),
|
||||
};
|
||||
|
||||
const settingsBase: PublicAppSettings = {
|
||||
oidcEnabled: true,
|
||||
remoteAuthEnabled: false,
|
||||
oidcProviderDetails: null!,
|
||||
oidcForceOnlyMode: false,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockQueryClient = {
|
||||
fetchQuery: vi.fn().mockResolvedValue(defaultPublicSettings),
|
||||
};
|
||||
vi.restoreAllMocks();
|
||||
authInitService.markAsInitialized.mockReset();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
authService.remoteLogin.mockReset();
|
||||
authService.initializeWebSocketConnection.mockReset();
|
||||
queryClient.fetchQuery.mockReset();
|
||||
appSettingsService.getPublicSettingsQueryOptions.mockClear();
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
it('marks auth initialized when public settings are unavailable', async () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
queryClient.fetchQuery.mockResolvedValue(null);
|
||||
|
||||
const injector = Injector.create({
|
||||
providers: [
|
||||
{provide: AuthService, useValue: {token: signal(null), getInternalAccessToken: vi.fn()}},
|
||||
{
|
||||
provide: AppSettingsService,
|
||||
useValue: {
|
||||
publicAppSettings: signal(null),
|
||||
getPublicSettingsQueryOptions: () => queryOptions({queryKey: ['public-settings'], queryFn: async () => defaultPublicSettings}),
|
||||
},
|
||||
},
|
||||
{provide: QueryClient, useValue: mockQueryClient},
|
||||
AuthInitializationService,
|
||||
{provide: AuthInitializationService, useValue: authInitService},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
]
|
||||
});
|
||||
|
||||
authInitService = TestBed.inject(AuthInitializationService);
|
||||
await runInInjectionContext(injector, () => initializeAuthFactory()());
|
||||
|
||||
expect(appSettingsService.getPublicSettingsQueryOptions).toHaveBeenCalledOnce();
|
||||
expect(authInitService.markAsInitialized).toHaveBeenCalledOnce();
|
||||
expect(warnSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should proceed with auth initialization when navigator.onLine is false', async () => {
|
||||
const markSpy = vi.spyOn(authInitService, 'markAsInitialized');
|
||||
it('initializes websocket auth when local auth is active and a token exists', async () => {
|
||||
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: false});
|
||||
authService.getInternalAccessToken.mockReturnValue('access-token');
|
||||
|
||||
Object.defineProperty(navigator, 'onLine', {value: false, configurable: true});
|
||||
const injector = Injector.create({
|
||||
providers: [
|
||||
{provide: AuthInitializationService, useValue: authInitService},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
]
|
||||
});
|
||||
|
||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||
await runInInjectionContext(injector, () => initializeAuthFactory()());
|
||||
|
||||
await initPromise;
|
||||
|
||||
expect(markSpy).toHaveBeenCalled();
|
||||
|
||||
Object.defineProperty(navigator, 'onLine', {value: true, configurable: true});
|
||||
expect(authService.initializeWebSocketConnection).toHaveBeenCalledOnce();
|
||||
expect(authInitService.markAsInitialized).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should initialize normally when navigator.onLine is true', async () => {
|
||||
const markSpy = vi.spyOn(authInitService, 'markAsInitialized');
|
||||
it('skips websocket initialization when local auth is active and no token exists', async () => {
|
||||
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: false});
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
|
||||
Object.defineProperty(navigator, 'onLine', {value: true, configurable: true});
|
||||
const injector = Injector.create({
|
||||
providers: [
|
||||
{provide: AuthInitializationService, useValue: authInitService},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
]
|
||||
});
|
||||
|
||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||
await runInInjectionContext(injector, () => initializeAuthFactory()());
|
||||
|
||||
await initPromise;
|
||||
expect(authService.initializeWebSocketConnection).not.toHaveBeenCalled();
|
||||
expect(authInitService.markAsInitialized).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
expect(markSpy).toHaveBeenCalled();
|
||||
it('performs remote login when remote auth is enabled', async () => {
|
||||
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: true});
|
||||
authService.remoteLogin.mockReturnValue(of({
|
||||
accessToken: 'access',
|
||||
refreshToken: 'refresh',
|
||||
isDefaultPassword: 'false',
|
||||
}));
|
||||
|
||||
const injector = Injector.create({
|
||||
providers: [
|
||||
{provide: AuthInitializationService, useValue: authInitService},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
]
|
||||
});
|
||||
|
||||
await runInInjectionContext(injector, () => initializeAuthFactory()());
|
||||
|
||||
expect(authService.remoteLogin).toHaveBeenCalledOnce();
|
||||
expect(authInitService.markAsInitialized).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('marks auth initialized even when remote login fails', async () => {
|
||||
const error = new Error('remote login failed');
|
||||
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: true});
|
||||
authService.remoteLogin.mockReturnValue(throwError(() => error));
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
const injector = Injector.create({
|
||||
providers: [
|
||||
{provide: AuthInitializationService, useValue: authInitService},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
]
|
||||
});
|
||||
|
||||
await runInInjectionContext(injector, () => initializeAuthFactory()());
|
||||
|
||||
expect(authService.remoteLogin).toHaveBeenCalledOnce();
|
||||
expect(authInitService.markAsInitialized).toHaveBeenCalledOnce();
|
||||
expect(errorSpy).toHaveBeenCalledWith('[Remote Login] failed:', error);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import {HttpErrorResponse, HttpHandlerFn, HttpRequest, HttpResponse} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {Observable, Subject, firstValueFrom, of, throwError} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {AuthInterceptorService} from './auth-interceptor.service';
|
||||
|
||||
describe('AuthInterceptorService', () => {
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
internalRefreshToken: vi.fn<() => Observable<{accessToken: string; refreshToken: string}>>(),
|
||||
saveInternalTokens: vi.fn<(accessToken: string, refreshToken: string) => void>(),
|
||||
logout: vi.fn<() => void>(),
|
||||
};
|
||||
|
||||
const apiUrl = `${API_CONFIG.BASE_URL}/api/v1`;
|
||||
let interceptor: (request: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<unknown>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
authService.internalRefreshToken.mockReset();
|
||||
authService.saveInternalTokens.mockReset();
|
||||
authService.logout.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: AuthService, useValue: authService},
|
||||
]
|
||||
});
|
||||
|
||||
interceptor = (request, next) => TestBed.runInInjectionContext(
|
||||
() => AuthInterceptorService(request, next)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('adds the bearer token to API requests', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({status: 200, body: request.headers.get('Authorization')})));
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
));
|
||||
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect((response as HttpResponse<string>).body).toBe('Bearer token-123');
|
||||
});
|
||||
|
||||
it('does not add auth headers to non-api requests', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')})));
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${API_CONFIG.BASE_URL}/assets/logo.svg`),
|
||||
next
|
||||
));
|
||||
|
||||
expect((response as HttpResponse<boolean>).body).toBe(false);
|
||||
});
|
||||
|
||||
it('forwards api requests unchanged when no token is available', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')})));
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
));
|
||||
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect((response as HttpResponse<boolean>).body).toBe(false);
|
||||
});
|
||||
|
||||
it('retries a 401 request after a successful refresh', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(of({accessToken: 'fresh-token', refreshToken: 'refresh-token'}));
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (authHeader === 'Bearer fresh-token') {
|
||||
return of(new HttpResponse({status: 200, body: authHeader}));
|
||||
}
|
||||
return throwError(() => new HttpErrorResponse({status: 401}));
|
||||
});
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
));
|
||||
|
||||
expect(authService.internalRefreshToken).toHaveBeenCalledOnce();
|
||||
expect(authService.saveInternalTokens).toHaveBeenCalledWith('fresh-token', 'refresh-token');
|
||||
expect((response as HttpResponse<string>).body).toBe('Bearer fresh-token');
|
||||
});
|
||||
|
||||
it('retries a 401 request without persisting tokens when the refresh response is incomplete', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(of({accessToken: 'fresh-token', refreshToken: ''}));
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
if (request.headers.get('Authorization') === 'Bearer fresh-token') {
|
||||
return of(new HttpResponse({status: 200, body: request.headers.get('Authorization')}));
|
||||
}
|
||||
return throwError(() => new HttpErrorResponse({status: 401}));
|
||||
});
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
));
|
||||
|
||||
expect(authService.saveInternalTokens).not.toHaveBeenCalled();
|
||||
expect((response as HttpResponse<string>).body).toBe('Bearer fresh-token');
|
||||
});
|
||||
|
||||
it('logs out when the refresh request fails', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(
|
||||
throwError(() => new HttpErrorResponse({status: 500}))
|
||||
);
|
||||
|
||||
const next = vi.fn(() => throwError(() => new HttpErrorResponse({status: 401})));
|
||||
|
||||
await expect(firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
))).rejects.toBeInstanceOf(HttpErrorResponse);
|
||||
|
||||
expect(authService.logout).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('rethrows non-401 errors without logging out', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
const next = vi.fn(() => throwError(() => new HttpErrorResponse({status: 500})));
|
||||
|
||||
await expect(firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
))).rejects.toBeInstanceOf(HttpErrorResponse);
|
||||
|
||||
expect(authService.internalRefreshToken).not.toHaveBeenCalled();
|
||||
expect(authService.logout).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('queues concurrent 401s behind a single refresh operation', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
const refreshSubject = new Subject<{accessToken: string; refreshToken: string}>();
|
||||
authService.internalRefreshToken.mockReturnValue(refreshSubject.asObservable());
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (authHeader === 'Bearer refreshed-token') {
|
||||
return of(new HttpResponse({status: 200, body: authHeader}));
|
||||
}
|
||||
return throwError(() => new HttpErrorResponse({status: 401}));
|
||||
});
|
||||
|
||||
const firstRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/books`), next));
|
||||
const secondRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/libraries`), next));
|
||||
|
||||
refreshSubject.next({accessToken: 'refreshed-token', refreshToken: 'refresh-token'});
|
||||
refreshSubject.complete();
|
||||
|
||||
const [firstResponse, secondResponse] = await Promise.all([firstRequest, secondRequest]);
|
||||
|
||||
expect(authService.internalRefreshToken).toHaveBeenCalledOnce();
|
||||
expect((firstResponse as HttpResponse<string>).body).toBe('Bearer refreshed-token');
|
||||
expect((secondResponse as HttpResponse<string>).body).toBe('Bearer refreshed-token');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {AuthGuard} from './auth.guard';
|
||||
|
||||
function buildToken(payload: Record<string, unknown>): string {
|
||||
return `header.${btoa(JSON.stringify(payload))}.signature`;
|
||||
}
|
||||
|
||||
describe('AuthGuard', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
const state = {} as RouterStateSnapshot;
|
||||
const router = {
|
||||
createUrlTree: vi.fn((commands: string[]) => ({commands}) as unknown as UrlTree),
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
localStorage.clear();
|
||||
router.createUrlTree.mockClear();
|
||||
router.navigate.mockClear();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: AuthService, useValue: authService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('allows navigation for a valid non-default-password token', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue(
|
||||
buildToken({exp: Math.floor(Date.now() / 1000) + 3600})
|
||||
);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to login when there is no token', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('returns a login UrlTree for expired tokens', () => {
|
||||
localStorage.setItem('accessToken_Internal', 'stale-token');
|
||||
authService.getInternalAccessToken.mockReturnValue(
|
||||
buildToken({exp: Math.floor(Date.now() / 1000) - 10})
|
||||
);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
|
||||
expect(router.createUrlTree).toHaveBeenCalledWith(['/login']);
|
||||
expect(result).toEqual({commands: ['/login']});
|
||||
expect(localStorage.getItem('accessToken_Internal')).toBeNull();
|
||||
});
|
||||
|
||||
it('redirects to the change-password flow for default-password tokens', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue(
|
||||
buildToken({exp: Math.floor(Date.now() / 1000) + 3600, isDefaultPassword: true})
|
||||
);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||
});
|
||||
|
||||
it('clears the token and redirects to login for malformed tokens', () => {
|
||||
localStorage.setItem('accessToken_Internal', 'bad-token');
|
||||
authService.getInternalAccessToken.mockReturnValue('bad-token');
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
||||
expect(localStorage.getItem('accessToken_Internal')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
|
||||
export const AuthGuard: CanActivateFn = () => {
|
||||
export const AuthGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
void route;
|
||||
void state;
|
||||
const router = inject(Router);
|
||||
const authService = inject(AuthService);
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
import {BookdropGuard} from './bookdrop.guard';
|
||||
|
||||
describe('BookdropGuard', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
const state = {} as RouterStateSnapshot;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const userService = {
|
||||
currentUser: vi.fn<() => {permissions: {admin: boolean; canAccessBookdrop: boolean}} | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
router.navigate.mockClear();
|
||||
userService.currentUser.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UserService, useValue: userService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('allows admins even without the explicit bookdrop permission', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: true,
|
||||
canAccessBookdrop: false,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => BookdropGuard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects anonymous users to the dashboard', () => {
|
||||
userService.currentUser.mockReturnValue(null);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => BookdropGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const BookdropGuard: CanActivateFn = () => {
|
||||
export const BookdropGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
void route;
|
||||
void state;
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
import {EditMetadataGuard} from './edit-metdata.guard';
|
||||
|
||||
describe('EditMetadataGuard', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
const state = {} as RouterStateSnapshot;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const userService = {
|
||||
currentUser: vi.fn<() => {permissions: {admin: boolean; canEditMetadata: boolean}} | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
router.navigate.mockClear();
|
||||
userService.currentUser.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UserService, useValue: userService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('allows users with metadata-edit permissions', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canEditMetadata: true,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => EditMetadataGuard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects users who lack metadata-edit permissions', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canEditMetadata: false,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => EditMetadataGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const EditMetadataGuard: CanActivateFn = () => {
|
||||
export const EditMetadataGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
void route;
|
||||
void state;
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
import {LibraryStatsGuard} from './library-stats.guard';
|
||||
|
||||
describe('LibraryStatsGuard', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
const state = {} as RouterStateSnapshot;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const userService = {
|
||||
currentUser: vi.fn<() => {permissions: {admin: boolean; canAccessLibraryStats: boolean}} | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
router.navigate.mockClear();
|
||||
userService.currentUser.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UserService, useValue: userService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('allows users with the library-stats permission', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canAccessLibraryStats: true,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => LibraryStatsGuard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects users without the library-stats permission', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canAccessLibraryStats: false,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => LibraryStatsGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const LibraryStatsGuard: CanActivateFn = () => {
|
||||
export const LibraryStatsGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
void route;
|
||||
void state;
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
import {ManageLibraryGuard} from './manage-library.guard';
|
||||
|
||||
describe('ManageLibraryGuard', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
const state = {} as RouterStateSnapshot;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const userService = {
|
||||
currentUser: vi.fn<() => {permissions: {admin: boolean; canManageLibrary: boolean}} | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
router.navigate.mockClear();
|
||||
userService.currentUser.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UserService, useValue: userService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('allows users with the manage-library permission', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canManageLibrary: true,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => ManageLibraryGuard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects users who lack access', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canManageLibrary: false,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => ManageLibraryGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const ManageLibraryGuard: CanActivateFn = () => {
|
||||
export const ManageLibraryGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
void route;
|
||||
void state;
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
import {UserStatsGuard} from './user-stats.guard';
|
||||
|
||||
describe('UserStatsGuard', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
const state = {} as RouterStateSnapshot;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const userService = {
|
||||
currentUser: vi.fn<() => {permissions: {admin: boolean; canAccessUserStats: boolean}} | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
router.navigate.mockClear();
|
||||
userService.currentUser.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UserService, useValue: userService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('allows admins through the guard', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: true,
|
||||
canAccessUserStats: false,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => UserStatsGuard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects users who cannot access user stats', () => {
|
||||
userService.currentUser.mockReturnValue({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canAccessUserStats: false,
|
||||
}
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => UserStatsGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const UserStatsGuard: CanActivateFn = () => {
|
||||
export const UserStatsGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
void route;
|
||||
void state;
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
import {HttpErrorResponse} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {signal} from '@angular/core';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of, throwError} from 'rxjs';
|
||||
|
||||
import {AppSettingKey, AppSettings, OidcProviderDetails} from '../../../shared/model/app-settings.model';
|
||||
import {OidcGroupMapping} from '../../../shared/model/oidc-group-mapping.model';
|
||||
import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
||||
import {OidcGroupMappingService} from '../../../shared/service/oidc-group-mapping.service';
|
||||
import {LibraryService} from '../../../features/book/service/library.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {AuthenticationSettingsComponent} from './authentication-settings.component';
|
||||
|
||||
function createSettings(overrides: Partial<AppSettings> = {}): AppSettings {
|
||||
return {
|
||||
oidcEnabled: false,
|
||||
oidcAutoProvisionDetails: undefined,
|
||||
oidcProviderDetails: undefined,
|
||||
oidcSessionDurationHours: null,
|
||||
oidcGroupSyncMode: null,
|
||||
oidcForceOnlyMode: false,
|
||||
...overrides,
|
||||
} as AppSettings;
|
||||
}
|
||||
|
||||
function completeProvider(overrides: Partial<OidcProviderDetails> = {}): OidcProviderDetails {
|
||||
return {
|
||||
providerName: 'Example IdP',
|
||||
clientId: 'client-id',
|
||||
clientSecret: 'secret',
|
||||
issuerUri: 'https://issuer.example',
|
||||
scopes: 'openid profile email',
|
||||
claimMapping: {
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'given_name',
|
||||
groups: 'groups',
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('AuthenticationSettingsComponent', () => {
|
||||
const appSettingsSignal = signal<AppSettings | null>(null);
|
||||
const librariesSignal = signal([{id: 1, name: 'Main Library'}, {id: 2, name: 'Overflow'}]);
|
||||
|
||||
const appSettingsService = {
|
||||
appSettings: appSettingsSignal,
|
||||
toggleOidcEnabled: vi.fn(),
|
||||
saveSettings: vi.fn(),
|
||||
testOidcConnection: vi.fn(),
|
||||
};
|
||||
|
||||
const groupMappingService = {
|
||||
getAll: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
};
|
||||
|
||||
const messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
|
||||
const translocoService = {
|
||||
translate: vi.fn((key: string) => key),
|
||||
};
|
||||
|
||||
const libraryService = {
|
||||
libraries: librariesSignal,
|
||||
};
|
||||
|
||||
let component: AuthenticationSettingsComponent;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
appSettingsSignal.set(null);
|
||||
librariesSignal.set([{id: 1, name: 'Main Library'}, {id: 2, name: 'Overflow'}]);
|
||||
appSettingsService.toggleOidcEnabled.mockReset();
|
||||
appSettingsService.saveSettings.mockReset();
|
||||
appSettingsService.testOidcConnection.mockReset();
|
||||
groupMappingService.getAll.mockReset();
|
||||
groupMappingService.create.mockReset();
|
||||
groupMappingService.update.mockReset();
|
||||
groupMappingService.delete.mockReset();
|
||||
messageService.add.mockReset();
|
||||
translocoService.translate.mockClear();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: LibraryService, useValue: libraryService},
|
||||
{provide: OidcGroupMappingService, useValue: groupMappingService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
]
|
||||
});
|
||||
|
||||
component = TestBed.runInInjectionContext(() => new AuthenticationSettingsComponent());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads defaults when OIDC is disabled and skips group mapping refresh', () => {
|
||||
component.loadSettings(createSettings({
|
||||
oidcEnabled: false,
|
||||
oidcAutoProvisionDetails: undefined,
|
||||
oidcProviderDetails: undefined,
|
||||
oidcSessionDurationHours: null,
|
||||
oidcGroupSyncMode: null,
|
||||
oidcForceOnlyMode: false,
|
||||
}));
|
||||
|
||||
expect(component.oidcEnabled).toBe(false);
|
||||
expect(component.autoUserProvisioningEnabled).toBe(false);
|
||||
expect(component.allowLocalAccountLinking).toBe(true);
|
||||
expect(component.selectedPermissions).toEqual([]);
|
||||
expect(component.editingLibraryIds).toEqual([]);
|
||||
expect(component.oidcProvider.claimMapping).toEqual({
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'given_name',
|
||||
groups: '',
|
||||
});
|
||||
expect(groupMappingService.getAll).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies loaded OIDC settings and refreshes group mappings when enabled', () => {
|
||||
const mappings: OidcGroupMapping[] = [
|
||||
{id: 1, oidcGroupClaim: 'admins', isAdmin: true, permissions: ['permissionUpload'], libraryIds: [1], description: 'Admins'},
|
||||
];
|
||||
groupMappingService.getAll.mockReturnValue(of(mappings));
|
||||
|
||||
component.loadSettings(createSettings({
|
||||
oidcEnabled: true,
|
||||
oidcAutoProvisionDetails: {
|
||||
enableAutoProvisioning: true,
|
||||
allowLocalAccountLinking: false,
|
||||
defaultPermissions: ['permissionUpload', 'permissionEmailBook'],
|
||||
defaultLibraryIds: [1, 2],
|
||||
},
|
||||
oidcProviderDetails: completeProvider({
|
||||
claimMapping: {
|
||||
username: 'sub',
|
||||
email: 'mail',
|
||||
name: 'displayName',
|
||||
groups: 'memberOf',
|
||||
},
|
||||
}),
|
||||
oidcSessionDurationHours: 12,
|
||||
oidcGroupSyncMode: 'ON_LOGIN',
|
||||
oidcForceOnlyMode: true,
|
||||
}));
|
||||
|
||||
expect(component.oidcEnabled).toBe(true);
|
||||
expect(component.autoUserProvisioningEnabled).toBe(true);
|
||||
expect(component.allowLocalAccountLinking).toBe(false);
|
||||
expect(component.selectedPermissions).toEqual(['permissionUpload', 'permissionEmailBook']);
|
||||
expect(component.availablePermissions.find(p => p.value === 'permissionUpload')?.selected).toBe(true);
|
||||
expect(component.availablePermissions.find(p => p.value === 'permissionDeleteBook')?.selected).toBe(false);
|
||||
expect(component.editingLibraryIds).toEqual([1, 2]);
|
||||
expect(component.sessionDurationHours).toBe(12);
|
||||
expect(component.groupSyncMode).toBe('ON_LOGIN');
|
||||
expect(component.oidcForceOnlyMode).toBe(true);
|
||||
expect(component.oidcProvider.providerName).toBe('Example IdP');
|
||||
expect(component.oidcProvider.claimMapping).toEqual({
|
||||
username: 'sub',
|
||||
email: 'mail',
|
||||
name: 'displayName',
|
||||
groups: 'memberOf',
|
||||
});
|
||||
expect(component.groupMappings).toEqual(mappings);
|
||||
expect(groupMappingService.getAll).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('keeps OIDC disabled when the provider form is incomplete', () => {
|
||||
component.oidcEnabled = true;
|
||||
|
||||
component.toggleOidcEnabled();
|
||||
|
||||
expect(appSettingsService.toggleOidcEnabled).not.toHaveBeenCalled();
|
||||
expect(messageService.add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens a new group mapping dialog with blank state', () => {
|
||||
component.editingGroupMapping = {
|
||||
oidcGroupClaim: 'existing',
|
||||
isAdmin: true,
|
||||
permissions: ['permissionUpload'],
|
||||
libraryIds: [1],
|
||||
description: 'Existing',
|
||||
};
|
||||
component.editingGroupMappingPerms = component.availablePermissions.map(permission => ({
|
||||
...permission,
|
||||
selected: true,
|
||||
}));
|
||||
component.editingGroupMappingLibraryIds = [1];
|
||||
|
||||
component.openNewGroupMapping();
|
||||
|
||||
expect(component.showGroupMappingDialog).toBe(true);
|
||||
expect(component.editingGroupMapping).toEqual({
|
||||
oidcGroupClaim: '',
|
||||
isAdmin: false,
|
||||
permissions: [],
|
||||
libraryIds: [],
|
||||
description: '',
|
||||
});
|
||||
expect(component.editingGroupMappingPerms.every(permission => !permission.selected)).toBe(true);
|
||||
expect(component.editingGroupMappingLibraryIds).toEqual([]);
|
||||
});
|
||||
|
||||
it('opens an existing group mapping dialog with cloned state and selected permissions', () => {
|
||||
const mapping: OidcGroupMapping = {
|
||||
id: 42,
|
||||
oidcGroupClaim: 'admins',
|
||||
isAdmin: true,
|
||||
permissions: ['permissionRead', 'permissionUpload'],
|
||||
libraryIds: [1, 2],
|
||||
description: 'Administrators',
|
||||
};
|
||||
|
||||
component.openEditGroupMapping(mapping);
|
||||
|
||||
expect(component.showGroupMappingDialog).toBe(true);
|
||||
expect(component.editingGroupMapping).toEqual(mapping);
|
||||
expect(component.editingGroupMapping).not.toBe(mapping);
|
||||
expect(component.editingGroupMappingPerms.find(permission => permission.value === 'permissionUpload')?.selected).toBe(true);
|
||||
expect(component.editingGroupMappingPerms.find(permission => permission.value === 'permissionDeleteBook')?.selected).toBe(false);
|
||||
expect(component.editingGroupMappingLibraryIds).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('toggles OIDC enablement and reports persistence failures', () => {
|
||||
component.oidcProvider = completeProvider();
|
||||
appSettingsService.toggleOidcEnabled.mockReturnValueOnce(of(void 0));
|
||||
component.oidcEnabled = true;
|
||||
|
||||
component.toggleOidcEnabled();
|
||||
|
||||
expect(appSettingsService.toggleOidcEnabled).toHaveBeenCalledWith(true);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
detail: 'settingsAuth.toast.oidcUpdated',
|
||||
}));
|
||||
|
||||
appSettingsService.toggleOidcEnabled.mockReturnValueOnce(
|
||||
throwError(() => new HttpErrorResponse({status: 500}))
|
||||
);
|
||||
component.oidcEnabled = false;
|
||||
|
||||
component.toggleOidcEnabled();
|
||||
|
||||
expect(messageService.add).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
detail: 'settingsAuth.toast.oidcError',
|
||||
}));
|
||||
});
|
||||
|
||||
it('copies the backchannel URI using the helper method', () => {
|
||||
const copySpy = vi.spyOn(component, 'copyToClipboard').mockImplementation(() => undefined);
|
||||
|
||||
component.copyBackchannelUri();
|
||||
|
||||
expect(copySpy).toHaveBeenCalledWith(component.backchannelLogoutUri);
|
||||
});
|
||||
|
||||
it('saves OIDC provider settings with the session duration only when OIDC is enabled', () => {
|
||||
appSettingsService.saveSettings.mockReturnValue(of(void 0));
|
||||
component.oidcProvider = completeProvider();
|
||||
component.oidcEnabled = false;
|
||||
component.sessionDurationHours = 24;
|
||||
|
||||
component.saveOidcProvider();
|
||||
|
||||
expect(appSettingsService.saveSettings).toHaveBeenCalledWith([
|
||||
{
|
||||
key: AppSettingKey.OIDC_PROVIDER_DETAILS,
|
||||
newValue: component.oidcProvider,
|
||||
}
|
||||
]);
|
||||
|
||||
component.oidcEnabled = true;
|
||||
component.saveOidcProvider();
|
||||
|
||||
expect(appSettingsService.saveSettings).toHaveBeenLastCalledWith([
|
||||
{
|
||||
key: AppSettingKey.OIDC_PROVIDER_DETAILS,
|
||||
newValue: component.oidcProvider,
|
||||
},
|
||||
{
|
||||
key: AppSettingKey.OIDC_SESSION_DURATION_HOURS,
|
||||
newValue: 24,
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
it('saves the group sync mode and reports failures', () => {
|
||||
appSettingsService.saveSettings.mockReturnValueOnce(of(void 0));
|
||||
component.groupSyncMode = 'ON_LOGIN_ADDITIVE';
|
||||
|
||||
component.saveGroupSyncMode();
|
||||
|
||||
expect(appSettingsService.saveSettings).toHaveBeenCalledWith([
|
||||
{
|
||||
key: AppSettingKey.OIDC_GROUP_SYNC_MODE,
|
||||
newValue: 'ON_LOGIN_ADDITIVE',
|
||||
}
|
||||
]);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
detail: 'settingsAuth.toast.syncModeSaved',
|
||||
}));
|
||||
|
||||
appSettingsService.saveSettings.mockReturnValueOnce(
|
||||
throwError(() => new HttpErrorResponse({status: 500}))
|
||||
);
|
||||
|
||||
component.saveGroupSyncMode();
|
||||
|
||||
expect(messageService.add).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
detail: 'settingsAuth.toast.syncModeError',
|
||||
}));
|
||||
});
|
||||
|
||||
it('saves the auto-provisioning payload with the selected permissions and library ids', () => {
|
||||
appSettingsService.saveSettings.mockReturnValue(of(void 0));
|
||||
component.autoUserProvisioningEnabled = true;
|
||||
component.allowLocalAccountLinking = false;
|
||||
component.availablePermissions.find(p => p.value === 'permissionUpload')!.selected = true;
|
||||
component.availablePermissions.find(p => p.value === 'permissionDeleteBook')!.selected = true;
|
||||
component.editingLibraryIds = [1, 2];
|
||||
|
||||
component.saveOidcAutoProvisionSettings();
|
||||
|
||||
expect(appSettingsService.saveSettings).toHaveBeenCalledWith([
|
||||
{
|
||||
key: AppSettingKey.OIDC_AUTO_PROVISION_DETAILS,
|
||||
newValue: {
|
||||
enableAutoProvisioning: true,
|
||||
allowLocalAccountLinking: false,
|
||||
defaultPermissions: ['permissionRead', 'permissionUpload', 'permissionDeleteBook'],
|
||||
defaultLibraryIds: [1, 2],
|
||||
},
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
it('creates and updates group mappings, and ignores delete requests without an id', () => {
|
||||
const createdMapping = {id: 9, oidcGroupClaim: 'readers', isAdmin: false, permissions: ['permissionRead'], libraryIds: [1], description: 'Readers'};
|
||||
appSettingsService.saveSettings.mockReturnValue(of(void 0));
|
||||
groupMappingService.create.mockReturnValue(of(createdMapping));
|
||||
groupMappingService.update.mockReturnValue(of(createdMapping));
|
||||
groupMappingService.delete.mockReturnValue(of(void 0));
|
||||
groupMappingService.getAll.mockReturnValue(of([createdMapping]));
|
||||
component.editingGroupMapping = {oidcGroupClaim: 'readers', isAdmin: false, permissions: [], libraryIds: [], description: ''};
|
||||
component.editingGroupMappingPerms = component.availablePermissions.map(permission => ({
|
||||
...permission,
|
||||
selected: permission.value === 'permissionUpload',
|
||||
}));
|
||||
component.editingGroupMappingLibraryIds = [1];
|
||||
|
||||
component.saveGroupMapping();
|
||||
|
||||
expect(groupMappingService.create).toHaveBeenCalledWith({
|
||||
oidcGroupClaim: 'readers',
|
||||
isAdmin: false,
|
||||
permissions: ['permissionRead', 'permissionUpload'],
|
||||
libraryIds: [1],
|
||||
description: '',
|
||||
});
|
||||
|
||||
component.editingGroupMapping = createdMapping;
|
||||
component.editingGroupMappingPerms = component.availablePermissions.map(permission => ({
|
||||
...permission,
|
||||
selected: false,
|
||||
}));
|
||||
component.editingGroupMappingLibraryIds = [2];
|
||||
component.saveGroupMapping();
|
||||
|
||||
expect(groupMappingService.update).toHaveBeenCalledWith(9, {
|
||||
...createdMapping,
|
||||
permissions: ['permissionRead'],
|
||||
libraryIds: [2],
|
||||
});
|
||||
|
||||
component.deleteGroupMapping({oidcGroupClaim: 'no-id', isAdmin: false, permissions: [], libraryIds: [], description: ''});
|
||||
expect(groupMappingService.delete).not.toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('surfaces failures when deleting a mapped group with an id', () => {
|
||||
const mapping = {id: 11, oidcGroupClaim: 'errors', isAdmin: false, permissions: [], libraryIds: [], description: ''};
|
||||
groupMappingService.delete.mockReturnValue(throwError(() => new HttpErrorResponse({status: 500})));
|
||||
|
||||
component.deleteGroupMapping(mapping);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
detail: 'settingsAuth.toast.groupMappingError',
|
||||
}));
|
||||
});
|
||||
|
||||
it('deletes mappings with an id and reloads after success', () => {
|
||||
const mapping = {id: 3, oidcGroupClaim: 'managers', isAdmin: false, permissions: [], libraryIds: [], description: ''};
|
||||
groupMappingService.delete.mockReturnValue(of(void 0));
|
||||
groupMappingService.getAll.mockReturnValue(of([]));
|
||||
|
||||
component.deleteGroupMapping(mapping);
|
||||
|
||||
expect(groupMappingService.delete).toHaveBeenCalledWith(3);
|
||||
expect(groupMappingService.getAll).toHaveBeenCalledOnce();
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('re-enables the force-only toggle when persistence succeeds', () => {
|
||||
appSettingsService.saveSettings.mockReturnValue(of(void 0));
|
||||
component.oidcForceOnlyMode = true;
|
||||
|
||||
component.toggleOidcForceOnlyMode();
|
||||
|
||||
expect(component.oidcForceOnlyMode).toBe(true);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
detail: 'settingsAuth.oidcOnly.saved',
|
||||
}));
|
||||
});
|
||||
|
||||
it('tests the OIDC connection and surfaces both success and failure states', () => {
|
||||
appSettingsService.testOidcConnection.mockReturnValueOnce(of({
|
||||
success: true,
|
||||
checks: [{name: 'issuer', status: 'PASS', message: 'ok'}],
|
||||
}));
|
||||
|
||||
component.testConnection();
|
||||
|
||||
expect(component.isTestingConnection).toBe(false);
|
||||
expect(component.testConnectionResult).toEqual({
|
||||
success: true,
|
||||
checks: [{name: 'issuer', status: 'PASS', message: 'ok'}],
|
||||
});
|
||||
expect(component.showTestDetails).toBe(true);
|
||||
|
||||
appSettingsService.testOidcConnection.mockReturnValueOnce(
|
||||
throwError(() => new HttpErrorResponse({status: 500}))
|
||||
);
|
||||
|
||||
component.testConnection();
|
||||
|
||||
expect(component.isTestingConnection).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
detail: 'settingsAuth.testConnection.error',
|
||||
}));
|
||||
});
|
||||
|
||||
it('reverts the force-only toggle when persistence fails', () => {
|
||||
component.oidcForceOnlyMode = true;
|
||||
appSettingsService.saveSettings.mockReturnValue(
|
||||
throwError(() => ({error: {message: 'backend rejected'}}))
|
||||
);
|
||||
|
||||
component.toggleOidcForceOnlyMode();
|
||||
|
||||
expect(component.oidcForceOnlyMode).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
detail: 'backend rejected',
|
||||
}));
|
||||
});
|
||||
|
||||
it('returns library names when present and falls back to the numeric id when missing', () => {
|
||||
expect(component.getLibraryName(1)).toBe('Main Library');
|
||||
expect(component.getLibraryName(999)).toBe('#999');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../testing/transloco-testing';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {OidcService} from '../oidc.service';
|
||||
import {OidcCallbackComponent} from './oidc-callback.component';
|
||||
|
||||
describe('OidcCallbackComponent', () => {
|
||||
let fixture: ComponentFixture<OidcCallbackComponent>;
|
||||
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const oidcService = {
|
||||
retrievePkceState: vi.fn(),
|
||||
exchangeCode: vi.fn(),
|
||||
};
|
||||
const authService = {
|
||||
saveInternalTokens: vi.fn(),
|
||||
initializeWebSocketConnection: vi.fn(),
|
||||
};
|
||||
|
||||
function configureComponent(search = ''): void {
|
||||
window.history.replaceState({}, '', `/oauth2-callback${search}`);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [
|
||||
OidcCallbackComponent,
|
||||
getTranslocoModule(),
|
||||
],
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: OidcService, useValue: oidcService},
|
||||
{provide: AuthService, useValue: authService},
|
||||
]
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(OidcCallbackComponent);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
sessionStorage.clear();
|
||||
router.navigate.mockClear();
|
||||
oidcService.retrievePkceState.mockReset();
|
||||
oidcService.exchangeCode.mockReset();
|
||||
authService.saveInternalTokens.mockReset();
|
||||
authService.initializeWebSocketConnection.mockReset();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.history.replaceState({}, '', '/');
|
||||
sessionStorage.clear();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('redirects to login when the provider returns an error', () => {
|
||||
configureComponent('?error=access_denied&error_description=denied');
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login'], {
|
||||
queryParams: {oidcError: 'denied'},
|
||||
});
|
||||
});
|
||||
|
||||
it('redirects to login when code or state is missing', () => {
|
||||
configureComponent('?state=missing-code');
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login'], {
|
||||
queryParams: {oidcError: 'missing_code'},
|
||||
});
|
||||
});
|
||||
|
||||
it('redirects to login when there is no stored PKCE state', () => {
|
||||
oidcService.retrievePkceState.mockReturnValue(null);
|
||||
|
||||
configureComponent('?code=code-123&state=state-123');
|
||||
|
||||
expect(oidcService.retrievePkceState).toHaveBeenCalledWith('state-123');
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login'], {
|
||||
queryParams: {oidcError: 'missing_pkce_state'},
|
||||
});
|
||||
});
|
||||
|
||||
it('redirects to login when the returned state does not match the stored PKCE state', () => {
|
||||
oidcService.retrievePkceState.mockReturnValue({
|
||||
codeVerifier: 'verifier',
|
||||
nonce: 'nonce',
|
||||
state: 'other-state',
|
||||
});
|
||||
|
||||
configureComponent('?code=code-123&state=state-123');
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login'], {
|
||||
queryParams: {oidcError: 'state_mismatch'},
|
||||
});
|
||||
});
|
||||
|
||||
it('saves tokens and redirects to change-password when the backend flags a default password', () => {
|
||||
sessionStorage.setItem('oidc_redirect_count', '2');
|
||||
oidcService.retrievePkceState.mockReturnValue({
|
||||
codeVerifier: 'verifier',
|
||||
nonce: 'nonce',
|
||||
state: 'state-123',
|
||||
});
|
||||
oidcService.exchangeCode.mockReturnValue(of({
|
||||
accessToken: 'access',
|
||||
refreshToken: 'refresh',
|
||||
isDefaultPassword: 'true',
|
||||
}));
|
||||
|
||||
configureComponent('?code=code-123&state=state-123');
|
||||
|
||||
expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh');
|
||||
expect(authService.initializeWebSocketConnection).toHaveBeenCalledOnce();
|
||||
expect(sessionStorage.getItem('oidc_redirect_count')).toBeNull();
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||
});
|
||||
|
||||
it('saves tokens and redirects to the dashboard after a successful exchange', () => {
|
||||
oidcService.retrievePkceState.mockReturnValue({
|
||||
codeVerifier: 'verifier',
|
||||
nonce: 'nonce',
|
||||
state: 'state-123',
|
||||
});
|
||||
oidcService.exchangeCode.mockReturnValue(of({
|
||||
accessToken: 'access',
|
||||
refreshToken: 'refresh',
|
||||
isDefaultPassword: 'false',
|
||||
}));
|
||||
|
||||
configureComponent('?code=code-123&state=state-123');
|
||||
|
||||
expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh');
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
|
||||
it('redirects to login with the backend error message when the exchange fails', () => {
|
||||
oidcService.retrievePkceState.mockReturnValue({
|
||||
codeVerifier: 'verifier',
|
||||
nonce: 'nonce',
|
||||
state: 'state-123',
|
||||
});
|
||||
oidcService.exchangeCode.mockReturnValue(
|
||||
throwError(() => ({error: {message: 'exchange_failed'}}))
|
||||
);
|
||||
|
||||
configureComponent('?code=code-123&state=state-123');
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login'], {
|
||||
queryParams: {oidcError: 'exchange_failed'},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of} from 'rxjs';
|
||||
|
||||
import {AppSettingsService} from '../../shared/service/app-settings.service';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
import {OidcService} from './oidc.service';
|
||||
|
||||
describe('OidcService', () => {
|
||||
interface OidcServiceInternals {
|
||||
http: {
|
||||
get: ReturnType<typeof vi.fn>;
|
||||
post: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
appSettingsService: AppSettingsService;
|
||||
}
|
||||
|
||||
const createService = () => {
|
||||
const service = Object.create(OidcService.prototype) as OidcService;
|
||||
const internals = service as unknown as OidcServiceInternals;
|
||||
internals.http = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
};
|
||||
internals.appSettingsService = {} as AppSettingsService;
|
||||
return {service, http: internals.http};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
it('generates PKCE verifier and challenge pairs', async () => {
|
||||
const {service} = createService();
|
||||
const digestSpy = vi.fn(async (_algorithm: string, value: Uint8Array) => value);
|
||||
const getRandomValuesSpy = vi.fn((array: Uint8Array) => {
|
||||
array.set(Uint8Array.from({length: array.length}, (_, index) => index + 1));
|
||||
return array;
|
||||
});
|
||||
vi.stubGlobal('crypto', {
|
||||
getRandomValues: getRandomValuesSpy,
|
||||
subtle: {digest: digestSpy},
|
||||
});
|
||||
|
||||
const result = await service.generatePkce();
|
||||
|
||||
expect(getRandomValuesSpy).toHaveBeenCalledOnce();
|
||||
expect(digestSpy).toHaveBeenCalledOnce();
|
||||
expect(result.codeVerifier).toBeTruthy();
|
||||
expect(result.codeChallenge).toBeTruthy();
|
||||
});
|
||||
|
||||
it('generates random URL-safe strings', () => {
|
||||
const {service} = createService();
|
||||
vi.stubGlobal('crypto', {
|
||||
getRandomValues: (array: Uint8Array) => {
|
||||
array.set(Uint8Array.from({length: array.length}, (_, index) => index + 10));
|
||||
return array;
|
||||
},
|
||||
subtle: {digest: vi.fn()},
|
||||
});
|
||||
|
||||
const value = service.generateRandomString();
|
||||
|
||||
expect(value).toMatch(/^[A-Za-z0-9_-]+$/);
|
||||
});
|
||||
|
||||
it('builds an auth url directly when the authorization endpoint is provided', async () => {
|
||||
const {service} = createService();
|
||||
const authUrl = await service.buildAuthUrl(
|
||||
'https://issuer.example',
|
||||
'client-id',
|
||||
'challenge',
|
||||
'state-token',
|
||||
'nonce-token',
|
||||
'https://issuer.example/authorize',
|
||||
'openid profile'
|
||||
);
|
||||
|
||||
expect(authUrl).toContain('https://issuer.example/authorize?');
|
||||
expect(authUrl).toContain('client_id=client-id');
|
||||
expect(authUrl).toContain('scope=openid+profile');
|
||||
expect(authUrl).toContain('state=state-token');
|
||||
});
|
||||
|
||||
it('builds an auth url from the OIDC discovery document when the endpoint is omitted', async () => {
|
||||
const {service} = createService();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
json: async () => ({authorization_endpoint: 'https://issuer.example/discovered-authorize'})
|
||||
}));
|
||||
|
||||
const authUrl = await service.buildAuthUrl(
|
||||
'https://issuer.example/',
|
||||
'client-id',
|
||||
'challenge',
|
||||
'state-token',
|
||||
'nonce-token'
|
||||
);
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('https://issuer.example/.well-known/openid-configuration');
|
||||
expect(authUrl).toContain('https://issuer.example/discovered-authorize?');
|
||||
});
|
||||
|
||||
it('throws when the discovery document does not expose an authorization endpoint', async () => {
|
||||
const {service} = createService();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
json: async () => ({issuer: 'https://issuer.example'})
|
||||
}));
|
||||
|
||||
await expect(service.buildAuthUrl(
|
||||
'https://issuer.example/',
|
||||
'client-id',
|
||||
'challenge',
|
||||
'state-token',
|
||||
'nonce-token'
|
||||
)).rejects.toThrow('authorization_endpoint not found in discovery document');
|
||||
});
|
||||
|
||||
it('fetches the backend-generated OIDC state token', async () => {
|
||||
const {service, http} = createService();
|
||||
http.get.mockReturnValue(of({state: 'server-state'}));
|
||||
|
||||
const statePromise = service.fetchState();
|
||||
|
||||
await expect(statePromise).resolves.toBe('server-state');
|
||||
expect(http.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/state`);
|
||||
});
|
||||
|
||||
it('posts the callback payload to exchange an OIDC code for tokens', () => {
|
||||
const {service, http} = createService();
|
||||
http.post.mockReturnValue(of({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'}));
|
||||
|
||||
service.exchangeCode('code-123', 'verifier', 'nonce', 'state').subscribe();
|
||||
|
||||
expect(http.post).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/callback`, {
|
||||
code: 'code-123',
|
||||
codeVerifier: 'verifier',
|
||||
redirectUri: `${window.location.origin}/oauth2-callback`,
|
||||
nonce: 'nonce',
|
||||
state: 'state',
|
||||
});
|
||||
});
|
||||
|
||||
it('stores, retrieves, and removes pkce state entries', () => {
|
||||
const {service} = createService();
|
||||
service.storePkceState({codeVerifier: 'verifier', state: 'state', nonce: 'nonce'});
|
||||
|
||||
expect(service.retrievePkceState('state')).toEqual({
|
||||
codeVerifier: 'verifier',
|
||||
state: 'state',
|
||||
nonce: 'nonce',
|
||||
});
|
||||
expect(service.retrievePkceState('state')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when stored PKCE state is missing or malformed', () => {
|
||||
const {service} = createService();
|
||||
expect(service.retrievePkceState('missing')).toBeNull();
|
||||
|
||||
sessionStorage.setItem('oidc_pkce_bad', '{not-json');
|
||||
|
||||
expect(service.retrievePkceState('bad')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {DomSanitizer} from '@angular/platform-browser';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {SecurePipe} from './secure-pipe';
|
||||
|
||||
describe('SecurePipe', () => {
|
||||
let pipe: SecurePipe;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let sanitizer: DomSanitizer;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
SecurePipe,
|
||||
]
|
||||
});
|
||||
|
||||
pipe = TestBed.inject(SecurePipe);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
sanitizer = TestBed.inject(DomSanitizer);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('fetches the blob and returns a sanitized object URL', async () => {
|
||||
const objectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:cover');
|
||||
const sanitizerSpy = vi.spyOn(sanitizer, 'bypassSecurityTrustUrl').mockReturnValue('safe:cover' as never);
|
||||
|
||||
const resultPromise = firstValueFrom(pipe.transform('/covers/1'));
|
||||
const request = httpTestingController.expectOne('/covers/1');
|
||||
request.flush(new Blob(['cover']));
|
||||
|
||||
await expect(resultPromise).resolves.toBe('safe:cover');
|
||||
expect(objectUrlSpy).toHaveBeenCalledOnce();
|
||||
expect(sanitizerSpy).toHaveBeenCalledWith('blob:cover');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import {Component} from '@angular/core';
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {By} from '@angular/platform-browser';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {SecureSrcDirective} from './secure-src.directive';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
imports: [SecureSrcDirective],
|
||||
template: `<img [appSecureSrc]="src" data-fallback-src="/fallback.png" alt="test cover" />`
|
||||
})
|
||||
class TestHostComponent {
|
||||
src = '';
|
||||
}
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
imports: [SecureSrcDirective],
|
||||
template: `<img [appSecureSrc]="src" alt="test cover" />`
|
||||
})
|
||||
class DefaultFallbackHostComponent {
|
||||
src = '';
|
||||
}
|
||||
|
||||
describe('SecureSrcDirective', () => {
|
||||
let fixture: ComponentFixture<TestHostComponent>;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
imports: [TestHostComponent],
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
]
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(TestHostComponent);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function image(): HTMLImageElement {
|
||||
return fixture.debugElement.query(By.css('img')).nativeElement as HTMLImageElement;
|
||||
}
|
||||
|
||||
it('loads a secure blob URL into the host image', () => {
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:secure-cover');
|
||||
|
||||
fixture.componentInstance.src = '/covers/1';
|
||||
fixture.detectChanges();
|
||||
|
||||
const request = httpTestingController.expectOne('/covers/1');
|
||||
request.flush(new Blob(['cover']));
|
||||
|
||||
expect(image().src).toContain('blob:secure-cover');
|
||||
});
|
||||
|
||||
it('skips loading when the source is empty', () => {
|
||||
fixture.detectChanges();
|
||||
|
||||
httpTestingController.expectNone(() => true);
|
||||
expect(image().getAttribute('src')).toBeNull();
|
||||
});
|
||||
|
||||
it('uses the fallback image and suppresses CORS-style console noise for status 0 and 403', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
fixture.componentInstance.src = '/covers/2';
|
||||
fixture.detectChanges();
|
||||
|
||||
const firstRequest = httpTestingController.expectOne('/covers/2');
|
||||
firstRequest.error(new ProgressEvent('error'), {status: 0, statusText: 'Unknown Error'});
|
||||
|
||||
expect(image().src).toContain('/fallback.png');
|
||||
expect(errorSpy).not.toHaveBeenCalled();
|
||||
|
||||
fixture.componentInstance.src = '/covers/3';
|
||||
fixture.detectChanges();
|
||||
|
||||
const secondRequest = httpTestingController.expectOne('/covers/3');
|
||||
secondRequest.flush(new Blob(['forbidden']), {status: 403, statusText: 'Forbidden'});
|
||||
|
||||
expect(image().src).toContain('/fallback.png');
|
||||
expect(errorSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs unexpected failures and revokes prior object URLs during cleanup', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const revokeSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValueOnce('blob:first').mockReturnValueOnce('blob:second');
|
||||
|
||||
fixture.componentInstance.src = '/covers/4';
|
||||
fixture.detectChanges();
|
||||
httpTestingController.expectOne('/covers/4').flush(new Blob(['first']));
|
||||
|
||||
fixture.componentInstance.src = '/covers/5';
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(revokeSpy).toHaveBeenCalledWith('blob:first');
|
||||
|
||||
httpTestingController.expectOne('/covers/5').flush(new Blob(['boom']), {status: 500, statusText: 'Server Error'});
|
||||
|
||||
expect(image().src).toContain('/fallback.png');
|
||||
expect(errorSpy).toHaveBeenCalledOnce();
|
||||
|
||||
fixture.destroy();
|
||||
});
|
||||
|
||||
it('revokes the active object URL when the directive is destroyed after a successful load', () => {
|
||||
const revokeSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:destroyed');
|
||||
|
||||
fixture.componentInstance.src = '/covers/7';
|
||||
fixture.detectChanges();
|
||||
|
||||
const request = httpTestingController.expectOne('/covers/7');
|
||||
request.flush(new Blob(['cover']));
|
||||
|
||||
fixture.destroy();
|
||||
|
||||
expect(revokeSpy).toHaveBeenCalledWith('blob:destroyed');
|
||||
});
|
||||
|
||||
it('uses the default fallback image when no fallback attribute is provided', () => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
imports: [DefaultFallbackHostComponent],
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
]
|
||||
});
|
||||
|
||||
const defaultFixture = TestBed.createComponent(DefaultFallbackHostComponent);
|
||||
const defaultHttpTestingController = TestBed.inject(HttpTestingController);
|
||||
defaultFixture.componentInstance.src = '/covers/6';
|
||||
defaultFixture.detectChanges();
|
||||
|
||||
const request = defaultHttpTestingController.expectOne('/covers/6');
|
||||
request.error(new ProgressEvent('error'), {status: 500, statusText: 'Server Error'});
|
||||
|
||||
expect(defaultFixture.debugElement.query(By.css('img')).nativeElement.src).toContain('assets/images/missing-cover.jpg');
|
||||
defaultHttpTestingController.verify();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../features/settings/user-management/user.service';
|
||||
import {BookdropGuard} from './guards/bookdrop.guard';
|
||||
import {EditMetadataGuard} from './guards/edit-metdata.guard';
|
||||
import {LibraryStatsGuard} from './guards/library-stats.guard';
|
||||
import {ManageLibraryGuard} from './guards/manage-library.guard';
|
||||
import {UserStatsGuard} from './guards/user-stats.guard';
|
||||
|
||||
type PermissionFlag =
|
||||
| 'canAccessBookdrop'
|
||||
| 'canEditMetadata'
|
||||
| 'canAccessLibraryStats'
|
||||
| 'canManageLibrary'
|
||||
| 'canAccessUserStats';
|
||||
|
||||
function createUser(permissionFlag: PermissionFlag, value: boolean, admin = false) {
|
||||
return {
|
||||
permissions: {
|
||||
admin,
|
||||
canAccessBookdrop: permissionFlag === 'canAccessBookdrop' ? value : false,
|
||||
canEditMetadata: permissionFlag === 'canEditMetadata' ? value : false,
|
||||
canAccessLibraryStats: permissionFlag === 'canAccessLibraryStats' ? value : false,
|
||||
canManageLibrary: permissionFlag === 'canManageLibrary' ? value : false,
|
||||
canAccessUserStats: permissionFlag === 'canAccessUserStats' ? value : false,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('security guards', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
const state = {} as RouterStateSnapshot;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const userService = {
|
||||
currentUser: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
router.navigate.mockClear();
|
||||
userService.currentUser.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UserService, useValue: userService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
function expectGuardAllows(
|
||||
permissionFlag: PermissionFlag,
|
||||
guard: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => unknown
|
||||
): void {
|
||||
userService.currentUser.mockReturnValue(createUser(permissionFlag, true));
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => guard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
function expectGuardAllowsAdmin(
|
||||
permissionFlag: PermissionFlag,
|
||||
guard: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => unknown
|
||||
): void {
|
||||
userService.currentUser.mockReturnValue(createUser(permissionFlag, false, true));
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => guard(route, state));
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
function expectGuardRedirects(
|
||||
permissionFlag: PermissionFlag,
|
||||
guard: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => unknown
|
||||
): void {
|
||||
userService.currentUser.mockReturnValue(createUser(permissionFlag, false));
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => guard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
}
|
||||
|
||||
it('allows bookdrop access for admins and users with the explicit permission', () => {
|
||||
expectGuardAllows('canAccessBookdrop', BookdropGuard);
|
||||
expectGuardAllowsAdmin('canAccessBookdrop', BookdropGuard);
|
||||
});
|
||||
|
||||
it('redirects bookdrop access when the user lacks permission', () => {
|
||||
expectGuardRedirects('canAccessBookdrop', BookdropGuard);
|
||||
});
|
||||
|
||||
it('allows metadata editing for admins and users with the explicit permission', () => {
|
||||
expectGuardAllows('canEditMetadata', EditMetadataGuard);
|
||||
expectGuardAllowsAdmin('canEditMetadata', EditMetadataGuard);
|
||||
});
|
||||
|
||||
it('redirects metadata editing when the user lacks permission', () => {
|
||||
expectGuardRedirects('canEditMetadata', EditMetadataGuard);
|
||||
});
|
||||
|
||||
it('allows library stats for admins and users with the explicit permission', () => {
|
||||
expectGuardAllows('canAccessLibraryStats', LibraryStatsGuard);
|
||||
expectGuardAllowsAdmin('canAccessLibraryStats', LibraryStatsGuard);
|
||||
});
|
||||
|
||||
it('redirects library stats when the user lacks permission', () => {
|
||||
expectGuardRedirects('canAccessLibraryStats', LibraryStatsGuard);
|
||||
});
|
||||
|
||||
it('allows library management for admins and users with the explicit permission', () => {
|
||||
expectGuardAllows('canManageLibrary', ManageLibraryGuard);
|
||||
expectGuardAllowsAdmin('canManageLibrary', ManageLibraryGuard);
|
||||
});
|
||||
|
||||
it('redirects library management when the user lacks permission', () => {
|
||||
expectGuardRedirects('canManageLibrary', ManageLibraryGuard);
|
||||
});
|
||||
|
||||
it('allows user stats for admins and users with the explicit permission', () => {
|
||||
expectGuardAllows('canAccessUserStats', UserStatsGuard);
|
||||
expectGuardAllowsAdmin('canAccessUserStats', UserStatsGuard);
|
||||
});
|
||||
|
||||
it('redirects user stats when the user lacks permission', () => {
|
||||
expectGuardRedirects('canAccessUserStats', UserStatsGuard);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import {afterEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {LoadingService} from './loading.service';
|
||||
|
||||
describe('LoadingService', () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
document.body.style.cursor = '';
|
||||
});
|
||||
|
||||
it('shows the default loading overlay and restores the cursor when hidden', () => {
|
||||
const service = new LoadingService();
|
||||
|
||||
const loader = service.show();
|
||||
|
||||
expect(document.body.contains(loader)).toBe(true);
|
||||
expect(loader.querySelector('.loader-content')?.textContent).toContain('Loading...');
|
||||
expect(document.body.style.cursor).toBe('wait');
|
||||
|
||||
service.hide(loader);
|
||||
|
||||
expect(document.body.contains(loader)).toBe(false);
|
||||
expect(document.body.style.cursor).toBe('default');
|
||||
});
|
||||
|
||||
it('renders a custom loading message', () => {
|
||||
const service = new LoadingService();
|
||||
|
||||
const loader = service.show('Syncing metadata');
|
||||
|
||||
expect(loader.querySelector('.loader-content')?.textContent).toContain('Syncing metadata');
|
||||
|
||||
service.hide(loader);
|
||||
});
|
||||
|
||||
it('removes all active overlays and ignores detached loaders', () => {
|
||||
const service = new LoadingService();
|
||||
|
||||
const first = service.show('First');
|
||||
const second = service.show('Second');
|
||||
const detached = document.createElement('div');
|
||||
|
||||
expect(() => service.hide(detached)).not.toThrow();
|
||||
|
||||
service.hideAll();
|
||||
|
||||
expect(document.body.contains(first)).toBe(false);
|
||||
expect(document.body.contains(second)).toBe(false);
|
||||
expect(document.body.style.cursor).toBe('default');
|
||||
});
|
||||
|
||||
it('keeps the wait cursor active until the final loader is hidden', () => {
|
||||
const service = new LoadingService();
|
||||
|
||||
const first = service.show('First');
|
||||
const second = service.show('Second');
|
||||
|
||||
service.hide(first);
|
||||
|
||||
expect(document.body.contains(first)).toBe(false);
|
||||
expect(document.body.contains(second)).toBe(true);
|
||||
expect(document.body.style.cursor).toBe('wait');
|
||||
|
||||
service.hide(second);
|
||||
|
||||
expect(document.body.contains(second)).toBe(false);
|
||||
expect(document.body.style.cursor).toBe('default');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {PostLoginInitializerService} from './post-login-initializer.service';
|
||||
|
||||
describe('PostLoginInitializerService', () => {
|
||||
it('completes successfully', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [PostLoginInitializerService],
|
||||
});
|
||||
|
||||
const service = TestBed.inject(PostLoginInitializerService);
|
||||
|
||||
await expect(firstValueFrom(service.initialize())).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import {Observable, firstValueFrom} from 'rxjs';
|
||||
import {skip, take} from 'rxjs/operators';
|
||||
|
||||
interface ChartTooltipContextInput {
|
||||
data: number[];
|
||||
labels: string[];
|
||||
dataIndex: number;
|
||||
}
|
||||
|
||||
export function nextChartEmission<T>(source$: Observable<T>): Promise<T> {
|
||||
return firstValueFrom(source$.pipe(skip(1), take(1)));
|
||||
}
|
||||
|
||||
export function fakeChartTooltipContext(input: ChartTooltipContextInput) {
|
||||
return {
|
||||
dataIndex: input.dataIndex,
|
||||
dataset: {
|
||||
data: input.data,
|
||||
},
|
||||
chart: {
|
||||
data: {
|
||||
labels: input.labels,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {MessageService, ConfirmationService} from 'primeng/api';
|
||||
import {vi} from 'vitest';
|
||||
import {MockProvider} from 'ng-mocks';
|
||||
|
||||
export function createDynamicDialogHarness<T>(data: T) {
|
||||
const dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
|
||||
return {
|
||||
dialogRef,
|
||||
providers: [
|
||||
MockProvider(DynamicDialogConfig, {data}),
|
||||
MockProvider(DynamicDialogRef, dialogRef),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function createMessageServiceSpy() {
|
||||
return {
|
||||
add: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
export function createConfirmServiceSpy() {
|
||||
return {
|
||||
confirm: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
export function createMessageServiceProvider(messageService: ReturnType<typeof createMessageServiceSpy>) {
|
||||
return MockProvider(MessageService, messageService);
|
||||
}
|
||||
|
||||
export function createConfirmServiceProvider(confirmationService: ReturnType<typeof createConfirmServiceSpy>) {
|
||||
return MockProvider(ConfirmationService, confirmationService);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import {signal, type EnvironmentProviders, type Provider, type WritableSignal} from '@angular/core';
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {provideTanStackQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
interface AuthServiceStub {
|
||||
token: WritableSignal<string | null>;
|
||||
getInternalAccessToken: () => string | null;
|
||||
}
|
||||
|
||||
export interface QueryClientHarness {
|
||||
providers: (Provider | EnvironmentProviders)[];
|
||||
queryClient: QueryClient;
|
||||
}
|
||||
|
||||
export function createAuthServiceStub(initialToken: string | null = 'token-123'): AuthServiceStub {
|
||||
const token = signal<string | null>(initialToken);
|
||||
return {
|
||||
token,
|
||||
getInternalAccessToken: () => token(),
|
||||
};
|
||||
}
|
||||
|
||||
export function createQueryClientHarness(): QueryClientHarness {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
return {
|
||||
queryClient,
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
provideTanStackQuery(queryClient),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function flushSignalAndQueryEffects(): void {
|
||||
TestBed.flushEffects();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {TranslocoTestingModule} from '@jsverse/transloco';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from './transloco-testing';
|
||||
|
||||
describe('getTranslocoModule', () => {
|
||||
it('returns a Transloco testing module wrapper', () => {
|
||||
const moduleWithProviders = getTranslocoModule();
|
||||
|
||||
expect(moduleWithProviders.ngModule).toBe(TranslocoTestingModule);
|
||||
expect(moduleWithProviders.providers?.length ?? 0).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('creates a fresh module wrapper when callers provide overrides', () => {
|
||||
const baseModule = getTranslocoModule();
|
||||
const customModule = getTranslocoModule({
|
||||
langs: {
|
||||
fr: {
|
||||
custom: {
|
||||
greeting: 'Bonjour',
|
||||
}
|
||||
},
|
||||
},
|
||||
translocoConfig: {
|
||||
availableLangs: ['en', 'fr'],
|
||||
defaultLang: 'fr',
|
||||
},
|
||||
});
|
||||
|
||||
expect(customModule.ngModule).toBe(TranslocoTestingModule);
|
||||
expect(customModule).not.toBe(baseModule);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around signal/effect synchronization,
|
||||
// virtual-scroller behavior, router/route query-param state, and cross-service selection logic so
|
||||
// author browsing can be tested without a full browser shell harness.
|
||||
describe.skip('AuthorBrowserComponent', () => {
|
||||
it('needs state-sync seams to verify author enrichment, filtering, sorting, and active-filter counting', () => {
|
||||
// TODO(seam): Cover enrichAuthors, applyFilters, and applySort once the reactive service graph is isolated for deterministic assertions.
|
||||
});
|
||||
|
||||
it('needs browser-shell seams to verify selection, scroll restoration, route state, and thumbnail cache-busting behavior', () => {
|
||||
// TODO(seam): Cover the virtual-scroller and router orchestration after extracting those concerns behind testable adapters.
|
||||
});
|
||||
});
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
import {ChangeDetectorRef, SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Subject, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AuthorDetails, AuthorSummary} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorCardComponent} from './author-card.component';
|
||||
|
||||
describe('AuthorCardComponent', () => {
|
||||
let getAuthorThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
let quickMatchAuthor: ReturnType<typeof vi.fn>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let markForCheck: ReturnType<typeof vi.fn>;
|
||||
|
||||
const baseAuthor: AuthorSummary = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00ADA',
|
||||
bookCount: 12,
|
||||
hasPhoto: true,
|
||||
};
|
||||
|
||||
const createComponent = (overrides?: {
|
||||
author?: Partial<AuthorSummary>;
|
||||
canQuickMatch?: boolean;
|
||||
canDelete?: boolean;
|
||||
isSelected?: boolean;
|
||||
index?: number;
|
||||
cacheBuster?: number;
|
||||
}) => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorCardComponent());
|
||||
component.author = {
|
||||
...baseAuthor,
|
||||
...overrides?.author,
|
||||
};
|
||||
component.canQuickMatch = overrides?.canQuickMatch ?? false;
|
||||
component.canDelete = overrides?.canDelete ?? false;
|
||||
component.isSelected = overrides?.isSelected ?? false;
|
||||
component.index = overrides?.index ?? 0;
|
||||
component.cacheBuster = overrides?.cacheBuster ?? 0;
|
||||
return component;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
getAuthorThumbnailUrl = vi.fn((authorId: number, cacheBuster?: number) => `/authors/${authorId}/thumbnail?t=${cacheBuster ?? 'none'}`);
|
||||
quickMatchAuthor = vi.fn();
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
translate = vi.fn((key: string) => key);
|
||||
markForCheck = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
getAuthorThumbnailUrl,
|
||||
quickMatchAuthor,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: ChangeDetectorRef,
|
||||
useValue: {
|
||||
markForCheck,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('resets photo state only for meaningful author changes and later cache busters', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.ngOnChanges({
|
||||
author: new SimpleChange(baseAuthor, {...baseAuthor, name: 'Augusta Ada'}, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(false);
|
||||
|
||||
component.ngOnChanges({
|
||||
author: new SimpleChange(baseAuthor, {...baseAuthor, asin: 'B00NEW', hasPhoto: false}, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(false);
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.ngOnChanges({
|
||||
cacheBuster: new SimpleChange(0, 1, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
});
|
||||
|
||||
it('short-circuits clicks that start inside the menu button container', () => {
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.cardClick, 'emit');
|
||||
|
||||
const menuContainer = document.createElement('div');
|
||||
menuContainer.className = 'menu-button-container';
|
||||
const button = document.createElement('button');
|
||||
menuContainer.appendChild(button);
|
||||
|
||||
const event = new Event('click');
|
||||
const stopPropagationSpy = vi.spyOn(event, 'stopPropagation');
|
||||
Object.defineProperty(event, 'target', {
|
||||
configurable: true,
|
||||
value: button,
|
||||
});
|
||||
|
||||
component.onCardClick(event);
|
||||
|
||||
expect(stopPropagationSpy).not.toHaveBeenCalled();
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats modifier clicks as selection toggles instead of opening the author', () => {
|
||||
const component = createComponent({isSelected: false, index: 3});
|
||||
const checkboxEmitSpy = vi.spyOn(component.checkboxClick, 'emit');
|
||||
const cardEmitSpy = vi.spyOn(component.cardClick, 'emit');
|
||||
|
||||
const target = document.createElement('div');
|
||||
const event = new MouseEvent('click', {ctrlKey: true});
|
||||
const preventDefaultSpy = vi.spyOn(event, 'preventDefault');
|
||||
const stopPropagationSpy = vi.spyOn(event, 'stopPropagation');
|
||||
Object.defineProperty(event, 'target', {
|
||||
configurable: true,
|
||||
value: target,
|
||||
});
|
||||
|
||||
component.onCardClick(event);
|
||||
|
||||
expect(preventDefaultSpy).toHaveBeenCalledOnce();
|
||||
expect(stopPropagationSpy).toHaveBeenCalledOnce();
|
||||
expect(cardEmitSpy).not.toHaveBeenCalled();
|
||||
expect(checkboxEmitSpy).toHaveBeenCalledWith({
|
||||
index: 3,
|
||||
author: component.author,
|
||||
selected: true,
|
||||
shiftKey: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('emits cardClick for normal clicks outside the menu controls', () => {
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.cardClick, 'emit');
|
||||
|
||||
const event = new Event('click');
|
||||
const stopPropagationSpy = vi.spyOn(event, 'stopPropagation');
|
||||
Object.defineProperty(event, 'target', {
|
||||
configurable: true,
|
||||
value: document.createElement('div'),
|
||||
});
|
||||
|
||||
component.onCardClick(event);
|
||||
|
||||
expect(stopPropagationSpy).toHaveBeenCalledOnce();
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
});
|
||||
|
||||
it('captures shift state from checkbox clicks and reuses it for selection events', () => {
|
||||
const component = createComponent({index: 5});
|
||||
const emitSpy = vi.spyOn(component.checkboxClick, 'emit');
|
||||
|
||||
const mouseEvent = new MouseEvent('click', {shiftKey: true});
|
||||
const stopPropagationSpy = vi.spyOn(mouseEvent, 'stopPropagation');
|
||||
|
||||
component.captureMouseEvent(mouseEvent);
|
||||
component.toggleSelection({checked: true} as never);
|
||||
|
||||
expect(stopPropagationSpy).toHaveBeenCalledOnce();
|
||||
expect(emitSpy).toHaveBeenCalledWith({
|
||||
index: 5,
|
||||
author: component.author,
|
||||
selected: true,
|
||||
shiftKey: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('lazily initializes the menu once, marks for check, and toggles the Prime menu each time', () => {
|
||||
const component = createComponent({canQuickMatch: true, canDelete: true});
|
||||
const menu = {
|
||||
toggle: vi.fn(),
|
||||
};
|
||||
const event = new Event('click');
|
||||
|
||||
component.onMenuToggle(event, menu as never);
|
||||
component.onMenuToggle(event, menu as never);
|
||||
|
||||
expect(markForCheck).toHaveBeenCalledOnce();
|
||||
expect(menu.toggle).toHaveBeenCalledTimes(2);
|
||||
expect(component.items.map(item => item.label)).toEqual([
|
||||
'authorBrowser.card.menu.viewAuthor',
|
||||
'authorBrowser.card.menu.editAuthor',
|
||||
'authorBrowser.card.menu.quickMatch',
|
||||
'authorBrowser.card.menu.deleteAuthor',
|
||||
]);
|
||||
});
|
||||
|
||||
it('quick-matches through the lazy menu command and reports success state', () => {
|
||||
const quickMatch$ = new Subject<AuthorDetails>();
|
||||
quickMatchAuthor.mockReturnValue(quickMatch$);
|
||||
|
||||
const component = createComponent({canQuickMatch: true});
|
||||
const emitSpy = vi.spyOn(component.quickMatched, 'emit');
|
||||
|
||||
component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never);
|
||||
const quickMatchItem = component.items.find(item => item.label === 'authorBrowser.card.menu.quickMatch');
|
||||
|
||||
quickMatchItem?.command?.({originalEvent: new Event('click'), item: quickMatchItem});
|
||||
|
||||
expect(quickMatchAuthor).toHaveBeenCalledWith(9);
|
||||
expect(component.quickMatching).toBe(true);
|
||||
|
||||
quickMatch$.next({
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00MATCH',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: false,
|
||||
});
|
||||
quickMatch$.complete();
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(component.author).toEqual({
|
||||
...baseAuthor,
|
||||
asin: 'B00MATCH',
|
||||
hasPhoto: true,
|
||||
});
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.toast.quickMatchSuccessSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchSuccessDetail',
|
||||
});
|
||||
|
||||
component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never);
|
||||
expect(markForCheck).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('clears quickMatching and reports an error toast when quick match fails', () => {
|
||||
quickMatchAuthor.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = createComponent({canQuickMatch: true});
|
||||
const emitSpy = vi.spyOn(component.quickMatched, 'emit');
|
||||
|
||||
component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never);
|
||||
const quickMatchItem = component.items.find(item => item.label === 'authorBrowser.card.menu.quickMatch');
|
||||
|
||||
quickMatchItem?.command?.({originalEvent: new Event('click'), item: quickMatchItem});
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.toast.quickMatchFailedSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchFailedDetail',
|
||||
});
|
||||
});
|
||||
});
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
import {ElementRef, signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {ActivatedRoute, convertToParamMap, Router} from '@angular/router';
|
||||
import {Subject, of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import type {AuthorDetails} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
import {AuthorDetailComponent} from './author-detail.component';
|
||||
|
||||
describe('AuthorDetailComponent', () => {
|
||||
let getAuthorDetails: ReturnType<typeof vi.fn>;
|
||||
let getAuthorPhotoUrl: ReturnType<typeof vi.fn>;
|
||||
let patchAuthorInCache: ReturnType<typeof vi.fn>;
|
||||
let quickMatchAuthor: ReturnType<typeof vi.fn>;
|
||||
let getCurrentUser: ReturnType<typeof vi.fn>;
|
||||
let setPageTitle: ReturnType<typeof vi.fn>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let route: {
|
||||
snapshot: {
|
||||
paramMap: ReturnType<typeof convertToParamMap>;
|
||||
queryParamMap: ReturnType<typeof convertToParamMap>;
|
||||
};
|
||||
};
|
||||
|
||||
const baseAuthor: AuthorDetails = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
description: 'Analytical engine pioneer',
|
||||
asin: 'B00ADA',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: false,
|
||||
photoLocked: false,
|
||||
};
|
||||
|
||||
const setRouteState = (authorId = 9, tab?: string) => {
|
||||
route.snapshot.paramMap = convertToParamMap({authorId: String(authorId)});
|
||||
route.snapshot.queryParamMap = convertToParamMap(tab ? {tab} : {});
|
||||
};
|
||||
|
||||
const createComponent = () => TestBed.runInInjectionContext(() => new AuthorDetailComponent());
|
||||
|
||||
beforeEach(() => {
|
||||
getAuthorDetails = vi.fn();
|
||||
getAuthorPhotoUrl = vi.fn((authorId: number) => `/api/authors/${authorId}/photo`);
|
||||
patchAuthorInCache = vi.fn();
|
||||
quickMatchAuthor = vi.fn();
|
||||
getCurrentUser = vi.fn(() => null);
|
||||
setPageTitle = vi.fn();
|
||||
translate = vi.fn((key: string) => key);
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
route = {
|
||||
snapshot: {
|
||||
paramMap: convertToParamMap({authorId: '9'}),
|
||||
queryParamMap: convertToParamMap({}),
|
||||
},
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: route,
|
||||
},
|
||||
{
|
||||
provide: Router,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
getAuthorDetails,
|
||||
getAuthorPhotoUrl,
|
||||
patchAuthorInCache,
|
||||
quickMatchAuthor,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookService,
|
||||
useValue: {
|
||||
books: signal([]),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: CoverScalePreferenceService,
|
||||
useValue: {
|
||||
currentCardSize: vi.fn(() => 'medium'),
|
||||
gridColumnMinWidth: vi.fn(() => '12rem'),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookCardOverlayPreferenceService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {
|
||||
getCurrentUser,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: PageTitleService,
|
||||
useValue: {
|
||||
setPageTitle,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('loads the author from the route, honors the tab query param, and updates page title on success', () => {
|
||||
setRouteState(42, 'series');
|
||||
getAuthorDetails.mockReturnValue(of({...baseAuthor, id: 42, name: 'Grace Hopper'}));
|
||||
|
||||
const component = createComponent();
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(getAuthorDetails).toHaveBeenCalledWith(42);
|
||||
expect(component.tab).toBe('series');
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.author()).toEqual({...baseAuthor, id: 42, name: 'Grace Hopper'});
|
||||
expect(setPageTitle).toHaveBeenCalledWith('Grace Hopper');
|
||||
});
|
||||
|
||||
it('keeps the default tab and clears loading when author load fails', () => {
|
||||
setRouteState(9);
|
||||
getAuthorDetails.mockReturnValue(throwError(() => new Error('load failed')));
|
||||
|
||||
const component = createComponent();
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.tab).toBe('books');
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.author()).toBeNull();
|
||||
expect(setPageTitle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('derives photoUrl from the loaded author state and gates canEditMetadata from user permissions', () => {
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(321);
|
||||
const component = createComponent();
|
||||
|
||||
expect(component.photoUrl).toBe('');
|
||||
expect(component.canEditMetadata).toBe(false);
|
||||
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
expect(component.photoUrl).toBe('/api/authors/9/photo&t=321');
|
||||
|
||||
getCurrentUser.mockReturnValue({permissions: {admin: false, canEditMetadata: true}});
|
||||
expect(component.canEditMetadata).toBe(true);
|
||||
|
||||
getCurrentUser.mockReturnValue({permissions: {admin: true, canEditMetadata: false}});
|
||||
expect(component.canEditMetadata).toBe(true);
|
||||
});
|
||||
|
||||
it('detects description overflow from the assigned element ref only while collapsed', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.descriptionContentRef = {
|
||||
nativeElement: {
|
||||
scrollHeight: 120,
|
||||
clientHeight: 60,
|
||||
},
|
||||
} as unknown as ElementRef<HTMLElement>;
|
||||
|
||||
component.ngAfterViewChecked();
|
||||
|
||||
expect(component.isOverflowing).toBe(true);
|
||||
|
||||
component.isExpanded = true;
|
||||
component.descriptionContentRef = {
|
||||
nativeElement: {
|
||||
scrollHeight: 20,
|
||||
clientHeight: 80,
|
||||
},
|
||||
} as unknown as ElementRef<HTMLElement>;
|
||||
|
||||
component.ngAfterViewChecked();
|
||||
|
||||
expect(component.isOverflowing).toBe(true);
|
||||
});
|
||||
|
||||
it('patches the cached author summary and refreshes photo state when the author is updated', () => {
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(777);
|
||||
const component = createComponent();
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.photoTimestamp = 10;
|
||||
|
||||
component.onAuthorUpdated({
|
||||
...baseAuthor,
|
||||
asin: 'B00UPDATED',
|
||||
});
|
||||
|
||||
expect(component.author()).toEqual({
|
||||
...baseAuthor,
|
||||
asin: 'B00UPDATED',
|
||||
});
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(777);
|
||||
expect(patchAuthorInCache).toHaveBeenCalledWith(9, {
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00UPDATED',
|
||||
hasPhoto: true,
|
||||
});
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('guards quickMatch when there is no author loaded or a match is already in flight', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.quickMatch();
|
||||
expect(quickMatchAuthor).not.toHaveBeenCalled();
|
||||
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
vi.clearAllMocks();
|
||||
component.quickMatching = true;
|
||||
|
||||
component.quickMatch();
|
||||
|
||||
expect(quickMatchAuthor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('quick-matches the loaded author, patches state, and reports a translated success toast', () => {
|
||||
const quickMatch$ = new Subject<AuthorDetails>();
|
||||
const matchedAuthor: AuthorDetails = {
|
||||
...baseAuthor,
|
||||
asin: 'B00MATCH',
|
||||
};
|
||||
quickMatchAuthor.mockReturnValue(quickMatch$);
|
||||
|
||||
const component = createComponent();
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
vi.clearAllMocks();
|
||||
|
||||
component.quickMatch();
|
||||
|
||||
expect(quickMatchAuthor).toHaveBeenCalledWith(9);
|
||||
expect(component.quickMatching).toBe(true);
|
||||
|
||||
quickMatch$.next(matchedAuthor);
|
||||
quickMatch$.complete();
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(component.author()).toEqual(matchedAuthor);
|
||||
expect(patchAuthorInCache).toHaveBeenCalledWith(9, {
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00MATCH',
|
||||
hasPhoto: true,
|
||||
});
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchSuccessSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchSuccessDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.toast.quickMatchSuccessSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the in-flight quick-match flag and reports a translated error toast on failure', () => {
|
||||
quickMatchAuthor.mockReturnValue(throwError(() => new Error('quick match failed')));
|
||||
|
||||
const component = createComponent();
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
vi.clearAllMocks();
|
||||
|
||||
component.quickMatch();
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchFailedSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.toast.quickMatchFailedSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchFailedDetail',
|
||||
});
|
||||
});
|
||||
});
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import {SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {Subject, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AuthorDetails} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorPhotoSearchComponent} from '../author-photo-search/author-photo-search.component';
|
||||
import {AuthorEditorComponent} from './author-editor.component';
|
||||
|
||||
describe('AuthorEditorComponent', () => {
|
||||
let updateAuthor: ReturnType<typeof vi.fn>;
|
||||
let dialogOpen: ReturnType<typeof vi.fn>;
|
||||
let dialogClose$: Subject<boolean>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
|
||||
const baseAuthor: AuthorDetails = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
description: 'Analytical engine pioneer',
|
||||
asin: 'B00ADA',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: false,
|
||||
photoLocked: false,
|
||||
};
|
||||
|
||||
const createComponent = (overrides?: {authorId?: number; author?: Partial<AuthorDetails>}) => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorEditorComponent());
|
||||
component.authorId = overrides?.authorId ?? 9;
|
||||
component.author = {
|
||||
...baseAuthor,
|
||||
...overrides?.author,
|
||||
};
|
||||
return component;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
updateAuthor = vi.fn();
|
||||
dialogClose$ = new Subject<boolean>();
|
||||
dialogOpen = vi.fn(() => ({onClose: dialogClose$}));
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
updateAuthor,
|
||||
getAuthorPhotoUrl: vi.fn((authorId: number) => `/api/authors/${authorId}/photo`),
|
||||
getUploadAuthorPhotoUrl: vi.fn((authorId: number) => `/api/authors/${authorId}/photo/upload`),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: DialogService,
|
||||
useValue: {
|
||||
open: dialogOpen,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('initializes the form and disables controls whose lock flags start enabled', () => {
|
||||
const component = createComponent({
|
||||
author: {
|
||||
nameLocked: true,
|
||||
asinLocked: true,
|
||||
},
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.form.get('name')?.value).toBe('Ada Lovelace');
|
||||
expect(component.form.get('description')?.value).toBe('Analytical engine pioneer');
|
||||
expect(component.form.get('asin')?.value).toBe('B00ADA');
|
||||
expect(component.form.get('name')?.disabled).toBe(true);
|
||||
expect(component.form.get('description')?.disabled).toBe(false);
|
||||
expect(component.form.get('asin')?.disabled).toBe(true);
|
||||
expect(component.form.get('photoLocked')?.value).toBe(false);
|
||||
});
|
||||
|
||||
it('restores photo state when a later author input change arrives', () => {
|
||||
const component = createComponent();
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(777);
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.photoTimestamp = 10;
|
||||
component.ngOnChanges({
|
||||
author: new SimpleChange(baseAuthor, {...baseAuthor, name: 'Updated Ada'}, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(777);
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shapes the save request from raw form values, emits the updated author, and reports success', () => {
|
||||
const updatedAuthor: AuthorDetails = {
|
||||
...baseAuthor,
|
||||
description: 'Updated description',
|
||||
asin: 'B00NEW',
|
||||
nameLocked: true,
|
||||
asinLocked: true,
|
||||
photoLocked: true,
|
||||
};
|
||||
const save$ = new Subject<AuthorDetails>();
|
||||
updateAuthor.mockReturnValue(save$);
|
||||
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
|
||||
component.ngOnInit();
|
||||
component.form.patchValue({
|
||||
name: ' ',
|
||||
description: ' Updated description ',
|
||||
asin: ' B00NEW ',
|
||||
nameLocked: true,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: true,
|
||||
});
|
||||
|
||||
component.onSave();
|
||||
|
||||
expect(component.isSaving).toBe(true);
|
||||
expect(updateAuthor).toHaveBeenCalledWith(9, {
|
||||
name: undefined,
|
||||
description: 'Updated description',
|
||||
asin: 'B00NEW',
|
||||
nameLocked: true,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: true,
|
||||
});
|
||||
|
||||
save$.next(updatedAuthor);
|
||||
save$.complete();
|
||||
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(emitSpy).toHaveBeenCalledWith(updatedAuthor);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.editor.toast.successSummary',
|
||||
detail: 'authorBrowser.editor.toast.successDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the saving flag and reports an error toast when saveMetadata fails', () => {
|
||||
updateAuthor.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
component.ngOnInit();
|
||||
|
||||
component.onSave();
|
||||
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.editor.toast.errorSummary',
|
||||
detail: 'authorBrowser.editor.toast.errorDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('opens the photo search dialog and refreshes photo state when it closes with success', () => {
|
||||
const component = createComponent({authorId: 42});
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(888);
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.photoTimestamp = 12;
|
||||
|
||||
component.openPhotoSearch();
|
||||
|
||||
expect(dialogOpen).toHaveBeenCalledWith(AuthorPhotoSearchComponent, {
|
||||
data: {authorId: 42, authorName: 'Ada Lovelace'},
|
||||
header: 'authorBrowser.editor.searchPhotoTitle',
|
||||
width: '70vw',
|
||||
height: '80vh',
|
||||
modal: true,
|
||||
closable: true,
|
||||
dismissableMask: true,
|
||||
contentStyle: {'overflow': 'hidden', 'padding': '0', 'display': 'flex', 'flex-direction': 'column'},
|
||||
});
|
||||
|
||||
dialogClose$.next(true);
|
||||
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(888);
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks upload success, refreshes the photo timestamp, and shows a success toast', () => {
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(999);
|
||||
|
||||
component.isUploading = true;
|
||||
component.hasPhoto = false;
|
||||
|
||||
component.onUpload();
|
||||
|
||||
expect(component.isUploading).toBe(false);
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(999);
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.editor.toast.photoUploadedSummary',
|
||||
detail: 'authorBrowser.editor.toast.photoUploadedDetail',
|
||||
});
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears upload progress and shows an error toast when upload fails', () => {
|
||||
const component = createComponent();
|
||||
component.isUploading = true;
|
||||
|
||||
component.onUploadError();
|
||||
|
||||
expect(component.isUploading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.editor.toast.errorSummary',
|
||||
detail: 'authorBrowser.editor.toast.photoUploadErrorDetail',
|
||||
});
|
||||
});
|
||||
});
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Subject, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AuthorDetails, AuthorSearchResult} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorMatchComponent} from './author-match.component';
|
||||
|
||||
describe('AuthorMatchComponent', () => {
|
||||
let searchAuthorMetadata: ReturnType<typeof vi.fn>;
|
||||
let matchAuthor: ReturnType<typeof vi.fn>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
|
||||
const createComponent = (overrides?: {authorId?: number; authorName?: string}) => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorMatchComponent());
|
||||
component.authorId = overrides?.authorId ?? 9;
|
||||
component.authorName = overrides?.authorName ?? 'Ada Lovelace';
|
||||
return component;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
searchAuthorMetadata = vi.fn();
|
||||
matchAuthor = vi.fn();
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
searchAuthorMetadata,
|
||||
matchAuthor,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('bootstraps searchQuery from authorName and gates canSearch on trimmed query inputs', () => {
|
||||
const component = createComponent({authorName: ' Ada Lovelace '});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.searchQuery).toBe(' Ada Lovelace ');
|
||||
expect(component.canSearch).toBe(true);
|
||||
|
||||
component.searchQuery = ' ';
|
||||
component.asinQuery = ' ';
|
||||
expect(component.canSearch).toBe(false);
|
||||
|
||||
component.asinQuery = ' B00TEST ';
|
||||
expect(component.canSearch).toBe(true);
|
||||
});
|
||||
|
||||
it('does not search when both query inputs are blank after trimming', () => {
|
||||
const component = createComponent();
|
||||
component.searchQuery = ' ';
|
||||
component.asinQuery = ' ';
|
||||
component.results = [{source: 'seed', asin: 'old', name: 'Existing'}];
|
||||
|
||||
component.search();
|
||||
|
||||
expect(searchAuthorMetadata).not.toHaveBeenCalled();
|
||||
expect(component.searching).toBe(false);
|
||||
expect(component.hasSearched).toBe(false);
|
||||
expect(component.results).toEqual([{source: 'seed', asin: 'old', name: 'Existing'}]);
|
||||
});
|
||||
|
||||
it('searches with trimmed values, clears stale results, and stores returned matches', () => {
|
||||
const results$ = new Subject<AuthorSearchResult[]>();
|
||||
searchAuthorMetadata.mockReturnValue(results$);
|
||||
|
||||
const component = createComponent();
|
||||
component.searchQuery = ' Ada ';
|
||||
component.asinQuery = ' B00MATCH ';
|
||||
component.selectedRegion = 'uk';
|
||||
component.results = [{source: 'seed', asin: 'old', name: 'Existing'}];
|
||||
|
||||
component.search();
|
||||
|
||||
expect(searchAuthorMetadata).toHaveBeenCalledWith(9, 'Ada', 'uk', 'B00MATCH');
|
||||
expect(component.searching).toBe(true);
|
||||
expect(component.hasSearched).toBe(true);
|
||||
expect(component.results).toEqual([]);
|
||||
|
||||
results$.next([
|
||||
{source: 'amazon', asin: 'B00MATCH', name: 'Ada Lovelace'},
|
||||
{source: 'amazon', asin: 'B00OTHER', name: 'A. Lovelace'},
|
||||
]);
|
||||
results$.complete();
|
||||
|
||||
expect(component.results).toEqual([
|
||||
{source: 'amazon', asin: 'B00MATCH', name: 'Ada Lovelace'},
|
||||
{source: 'amazon', asin: 'B00OTHER', name: 'A. Lovelace'},
|
||||
]);
|
||||
expect(component.searching).toBe(false);
|
||||
});
|
||||
|
||||
it('reports a translated search failure toast when metadata search errors', () => {
|
||||
searchAuthorMetadata.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = createComponent();
|
||||
component.searchQuery = 'Ada';
|
||||
|
||||
component.search();
|
||||
|
||||
expect(component.searching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.searchFailedSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.searchFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.match.toast.searchFailedSummary',
|
||||
detail: 'authorBrowser.match.toast.searchFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('shapes the match request, emits the updated author, and reports success on matchAuthor', () => {
|
||||
const updatedAuthor: AuthorDetails = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00MATCH',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: false,
|
||||
};
|
||||
const match$ = new Subject<AuthorDetails>();
|
||||
matchAuthor.mockReturnValue(match$);
|
||||
|
||||
const component = createComponent();
|
||||
component.selectedRegion = 'de';
|
||||
const emitSpy = vi.spyOn(component.authorMatched, 'emit');
|
||||
|
||||
component.matchAuthor({
|
||||
source: 'amazon',
|
||||
asin: 'B00MATCH',
|
||||
name: 'Ada Lovelace',
|
||||
description: 'Pioneer',
|
||||
});
|
||||
|
||||
expect(matchAuthor).toHaveBeenCalledWith(9, {
|
||||
source: 'amazon',
|
||||
asin: 'B00MATCH',
|
||||
region: 'de',
|
||||
});
|
||||
expect(component.matching).toBe(true);
|
||||
|
||||
match$.next(updatedAuthor);
|
||||
match$.complete();
|
||||
|
||||
expect(component.matching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchSuccessSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchSuccessDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.match.toast.matchSuccessSummary',
|
||||
detail: 'authorBrowser.match.toast.matchSuccessDetail',
|
||||
life: 3000,
|
||||
});
|
||||
expect(emitSpy).toHaveBeenCalledWith(updatedAuthor);
|
||||
});
|
||||
|
||||
it('reports a translated failure toast when matchAuthor errors', () => {
|
||||
matchAuthor.mockReturnValue(throwError(() => new Error('nope')));
|
||||
|
||||
const component = createComponent();
|
||||
|
||||
component.matchAuthor({
|
||||
source: 'amazon',
|
||||
asin: 'B00FAIL',
|
||||
name: 'Ada Lovelace',
|
||||
});
|
||||
|
||||
expect(component.matching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchFailedSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.match.toast.matchFailedSummary',
|
||||
detail: 'authorBrowser.match.toast.matchFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
});
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import type {AuthorPhotoResult} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorPhotoSearchComponent} from './author-photo-search.component';
|
||||
import {
|
||||
createDynamicDialogHarness,
|
||||
createMessageServiceProvider,
|
||||
createMessageServiceSpy,
|
||||
} from '../../../../core/testing/dialog-testing';
|
||||
|
||||
describe('AuthorPhotoSearchComponent', () => {
|
||||
let searchAuthorPhotos: ReturnType<typeof vi.fn>;
|
||||
let uploadAuthorPhotoFromUrl: ReturnType<typeof vi.fn>;
|
||||
let dialogHarness: ReturnType<typeof createDynamicDialogHarness<{authorId: number; authorName?: string}>>;
|
||||
let messageService: ReturnType<typeof createMessageServiceSpy>;
|
||||
|
||||
beforeEach(() => {
|
||||
searchAuthorPhotos = vi.fn(() => of([]));
|
||||
uploadAuthorPhotoFromUrl = vi.fn(() => of(undefined));
|
||||
dialogHarness = createDynamicDialogHarness({authorId: 9, authorName: 'Ada'});
|
||||
messageService = createMessageServiceSpy();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...dialogHarness.providers,
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
searchAuthorPhotos,
|
||||
uploadAuthorPhotoFromUrl,
|
||||
},
|
||||
},
|
||||
createMessageServiceProvider(messageService),
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate: (<T = string>(key: string) => key as T) as TranslocoService['translate'],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('hydrates the initial author query, performs the bootstrap search, and sorts the returned photos', () => {
|
||||
searchAuthorPhotos.mockReturnValue(of<AuthorPhotoResult[]>([
|
||||
{index: 3, url: 'three', width: 300, height: 400},
|
||||
{index: 1, url: 'one', width: 100, height: 200},
|
||||
{index: 2, url: 'two', width: 200, height: 300},
|
||||
]));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent());
|
||||
component.ngOnInit();
|
||||
|
||||
expect(searchAuthorPhotos).toHaveBeenCalledWith(9, 'Ada');
|
||||
expect(component.searchForm.value.query).toBe('Ada');
|
||||
expect(component.photos.map(photo => photo.index)).toEqual([1, 2, 3]);
|
||||
expect(component.hasSearched).toBe(true);
|
||||
expect(component.searching).toBe(false);
|
||||
});
|
||||
|
||||
it('clears results when searching fails and resets the form state on clear', () => {
|
||||
searchAuthorPhotos.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent());
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.photos).toEqual([]);
|
||||
expect(component.hasSearched).toBe(true);
|
||||
|
||||
component.onClear();
|
||||
|
||||
expect(component.searchForm.value.query).toBeNull();
|
||||
expect(component.photos).toEqual([]);
|
||||
expect(component.hasSearched).toBe(false);
|
||||
});
|
||||
|
||||
it('uploads a selected photo, reports success, and closes the dialog', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent());
|
||||
component.ngOnInit();
|
||||
|
||||
component.selectAndUploadPhoto({index: 1, url: 'https://example.com/photo.jpg', width: 640, height: 480});
|
||||
|
||||
expect(uploadAuthorPhotoFromUrl).toHaveBeenCalledWith(9, 'https://example.com/photo.jpg');
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.editor.toast.photoUploadedSummary',
|
||||
}));
|
||||
expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {
|
||||
AuthorDetails,
|
||||
AuthorFilters,
|
||||
AuthorMatchRequest,
|
||||
AuthorSummary,
|
||||
AuthorUpdateRequest,
|
||||
DEFAULT_AUTHOR_FILTERS,
|
||||
EnrichedAuthor
|
||||
} from './author.model';
|
||||
|
||||
describe('author.model', () => {
|
||||
it('provides all-author defaults for author filtering', () => {
|
||||
expect(DEFAULT_AUTHOR_FILTERS).toEqual({
|
||||
matchStatus: 'all',
|
||||
photoStatus: 'all',
|
||||
readStatus: 'all',
|
||||
bookCount: 'all',
|
||||
library: 'all',
|
||||
genre: 'all'
|
||||
} satisfies AuthorFilters);
|
||||
});
|
||||
|
||||
it('supports enriched authors extending the summary shape', () => {
|
||||
const enriched: EnrichedAuthor = {
|
||||
id: 7,
|
||||
name: 'Ursula K. Le Guin',
|
||||
bookCount: 12,
|
||||
hasPhoto: true,
|
||||
libraryIds: new Set([1, 2]),
|
||||
libraryNames: ['Main', 'Archive'],
|
||||
categories: ['Fantasy', 'Sci-Fi'],
|
||||
readStatus: 'some-read',
|
||||
hasSeries: true,
|
||||
seriesCount: 2,
|
||||
latestAddedOn: '2026-03-26',
|
||||
lastReadTime: '2026-03-25T20:15:00Z',
|
||||
readingProgress: 75,
|
||||
avgPersonalRating: 4.5
|
||||
};
|
||||
|
||||
expect(enriched.libraryIds.has(2)).toBe(true);
|
||||
expect(enriched.readStatus).toBe('some-read');
|
||||
expectTypeOf(enriched).toMatchTypeOf<AuthorSummary>();
|
||||
});
|
||||
|
||||
it('keeps author request and update payloads structurally typed', () => {
|
||||
const matchRequest: AuthorMatchRequest = {
|
||||
source: 'hardcover',
|
||||
asin: 'B001234',
|
||||
region: 'US'
|
||||
};
|
||||
const updateRequest: AuthorUpdateRequest = {
|
||||
name: 'New Name',
|
||||
descriptionLocked: true
|
||||
};
|
||||
const details: AuthorDetails = {
|
||||
id: 4,
|
||||
name: 'Author',
|
||||
nameLocked: false,
|
||||
descriptionLocked: true,
|
||||
asinLocked: false,
|
||||
photoLocked: false
|
||||
};
|
||||
|
||||
expect(matchRequest.region).toBe('US');
|
||||
expect(updateRequest.descriptionLocked).toBe(true);
|
||||
expect(details.nameLocked).toBe(false);
|
||||
expectTypeOf(updateRequest.name).toEqualTypeOf<string | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {AUTHORS_QUERY_KEY} from './author-query-keys';
|
||||
import {patchAuthorInCache} from './author-query-cache';
|
||||
|
||||
describe('patchAuthorInCache', () => {
|
||||
it('patches the matching author while keeping the rest intact', () => {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(AUTHORS_QUERY_KEY, [
|
||||
{id: 1, name: 'Ada', bookCount: 1, hasPhoto: false},
|
||||
{id: 2, name: 'Bert', bookCount: 2, hasPhoto: true},
|
||||
]);
|
||||
|
||||
patchAuthorInCache(queryClient, 2, {name: 'Bert Updated', hasPhoto: false});
|
||||
|
||||
expect(queryClient.getQueryData(AUTHORS_QUERY_KEY)).toEqual([
|
||||
{id: 1, name: 'Ada', bookCount: 1, hasPhoto: false},
|
||||
{id: 2, name: 'Bert Updated', bookCount: 2, hasPhoto: false},
|
||||
]);
|
||||
});
|
||||
|
||||
it('initializes an empty cache when there is no existing author list', () => {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
patchAuthorInCache(queryClient, 3, {name: 'Cy'});
|
||||
|
||||
expect(queryClient.getQueryData(AUTHORS_QUERY_KEY)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {AUTHORS_QUERY_KEY} from './author-query-keys';
|
||||
|
||||
describe('AUTHORS_QUERY_KEY', () => {
|
||||
it('uses a stable cache key for the author browser', () => {
|
||||
expect(AUTHORS_QUERY_KEY).toEqual(['authors']);
|
||||
});
|
||||
});
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
||||
import {AuthorScalePreferenceService} from './author-scale-preference.service';
|
||||
|
||||
describe('AuthorScalePreferenceService', () => {
|
||||
const localStorageService = {
|
||||
get: vi.fn(),
|
||||
set: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.restoreAllMocks();
|
||||
localStorageService.get.mockReset();
|
||||
localStorageService.set.mockReset();
|
||||
localStorageService.get.mockReturnValue(1.5);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
AuthorScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the persisted scale and does not persist unchanged values', () => {
|
||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
||||
|
||||
expect(service.scaleFactor()).toBe(1.5);
|
||||
|
||||
service.setScale(1.5);
|
||||
vi.runAllTimers();
|
||||
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('debounces and persists the most recent scale value', () => {
|
||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
||||
|
||||
service.setScale(1.2);
|
||||
service.setScale(1.4);
|
||||
|
||||
vi.advanceTimersByTime(999);
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
|
||||
expect(localStorageService.set).toHaveBeenCalledOnce();
|
||||
expect(localStorageService.set).toHaveBeenCalledWith('authorScalePreference', 1.4);
|
||||
});
|
||||
|
||||
it('falls back to the default scale when storage contains an invalid value', () => {
|
||||
localStorageService.get.mockReturnValue(Number.NaN);
|
||||
|
||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
||||
|
||||
expect(service.scaleFactor()).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {AuthorSelectionService} from './author-selection.service';
|
||||
|
||||
describe('AuthorSelectionService', () => {
|
||||
const authors = [
|
||||
{id: 1, name: 'Ada', bookCount: 1, hasPhoto: false},
|
||||
{id: 2, name: 'Bert', bookCount: 2, hasPhoto: true},
|
||||
{id: 3, name: 'Cy', bookCount: 3, hasPhoto: false},
|
||||
{id: 4, name: 'Dee', bookCount: 4, hasPhoto: true},
|
||||
];
|
||||
|
||||
it('selects and deselects authors and exposes the selected count', () => {
|
||||
const service = new AuthorSelectionService();
|
||||
service.setCurrentAuthors(authors);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 1,
|
||||
author: authors[1],
|
||||
selected: true,
|
||||
shiftKey: false,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([2]);
|
||||
expect(service.selectedCount()).toBe(1);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 1,
|
||||
author: authors[1],
|
||||
selected: false,
|
||||
shiftKey: false,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([]);
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('supports shift-click range selection and deselection', () => {
|
||||
const service = new AuthorSelectionService();
|
||||
service.setCurrentAuthors(authors);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 1,
|
||||
author: authors[1],
|
||||
selected: true,
|
||||
shiftKey: false,
|
||||
});
|
||||
service.handleCheckboxClick({
|
||||
index: 3,
|
||||
author: authors[3],
|
||||
selected: true,
|
||||
shiftKey: true,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([2, 3, 4]);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 2,
|
||||
author: authors[2],
|
||||
selected: false,
|
||||
shiftKey: true,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([4]);
|
||||
});
|
||||
|
||||
it('selects and clears the full current author list', () => {
|
||||
const service = new AuthorSelectionService();
|
||||
service.setCurrentAuthors(authors);
|
||||
|
||||
service.selectAll();
|
||||
expect(service.getSelectedIds()).toEqual([1, 2, 3, 4]);
|
||||
|
||||
service.deselectAll();
|
||||
expect(service.getSelectedIds()).toEqual([]);
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {SseClient} from 'ngx-sse-client';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {AuthorService} from './author.service';
|
||||
|
||||
describe('AuthorService', () => {
|
||||
const httpClient = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
};
|
||||
|
||||
const authService = {
|
||||
token: vi.fn(),
|
||||
getInternalAccessToken: vi.fn(),
|
||||
};
|
||||
|
||||
const sseClient = {
|
||||
stream: vi.fn(),
|
||||
};
|
||||
|
||||
const queryClient = {
|
||||
removeQueries: vi.fn(),
|
||||
invalidateQueries: vi.fn(),
|
||||
};
|
||||
|
||||
let service: AuthorService;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClient.get.mockReset();
|
||||
httpClient.post.mockReset();
|
||||
httpClient.put.mockReset();
|
||||
httpClient.delete.mockReset();
|
||||
authService.token.mockReset();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
sseClient.stream.mockReset();
|
||||
queryClient.removeQueries.mockReset();
|
||||
queryClient.invalidateQueries.mockReset();
|
||||
|
||||
authService.token.mockReturnValue('token-123');
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
httpClient.get.mockReturnValue(of([]));
|
||||
httpClient.post.mockReturnValue(of({}));
|
||||
httpClient.put.mockReturnValue(of({}));
|
||||
httpClient.delete.mockReturnValue(of(undefined));
|
||||
sseClient.stream.mockReturnValue(of({type: 'message', data: '{"id":7,"name":"Ada"}'}));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
AuthorService,
|
||||
{provide: HttpClient, useValue: httpClient},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: SseClient, useValue: sseClient},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(AuthorService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('builds metadata search params with q or asin depending on the request', () => {
|
||||
service.searchAuthorMetadata(9, 'Ada', 'us');
|
||||
|
||||
expect(httpClient.get).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/9/search-metadata`,
|
||||
{params: {region: 'us', q: 'Ada'}},
|
||||
);
|
||||
|
||||
service.searchAuthorMetadata(9, 'Ada', 'us', 'B000123');
|
||||
|
||||
expect(httpClient.get).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/9/search-metadata`,
|
||||
{params: {region: 'us', asin: 'B000123'}},
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the default region for quick matches and preserves custom regions', () => {
|
||||
service.quickMatchAuthor(11);
|
||||
service.quickMatchAuthor(11, 'gb');
|
||||
|
||||
expect(httpClient.post).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/11/quick-match`,
|
||||
null,
|
||||
{params: {region: 'us'}},
|
||||
);
|
||||
expect(httpClient.post).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/11/quick-match`,
|
||||
null,
|
||||
{params: {region: 'gb'}},
|
||||
);
|
||||
});
|
||||
|
||||
it('maps SSE auto-match responses and throws on error events', () => {
|
||||
sseClient.stream.mockReturnValueOnce(of({type: 'message', data: '{"id":3,"name":"Grace"}'}));
|
||||
|
||||
const results: unknown[] = [];
|
||||
service.autoMatchAuthors([1, 2]).subscribe(value => results.push(value));
|
||||
|
||||
expect(sseClient.stream).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/auto-match`,
|
||||
expect.objectContaining({keepAlive: false, reconnectionDelay: 1000, responseType: 'event'}),
|
||||
expect.objectContaining({
|
||||
body: [1, 2],
|
||||
withCredentials: true,
|
||||
}),
|
||||
'POST',
|
||||
);
|
||||
expect(results).toEqual([{id: 3, name: 'Grace'}]);
|
||||
|
||||
sseClient.stream.mockReturnValueOnce(of({type: 'error', message: 'boom'}));
|
||||
|
||||
const errors: Error[] = [];
|
||||
service.autoMatchAuthors([7]).subscribe({
|
||||
next: () => undefined,
|
||||
error: error => errors.push(error),
|
||||
});
|
||||
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]).toEqual(new Error('boom'));
|
||||
});
|
||||
|
||||
it('builds tokenized author media urls with and without cache busters', () => {
|
||||
expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo?token=token-123`);
|
||||
expect(service.getAuthorThumbnailUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123`);
|
||||
expect(service.getAuthorThumbnailUrl(5, 99)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123&t=99`);
|
||||
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo`);
|
||||
expect(service.getAuthorThumbnailUrl(5, 99)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?t=99`);
|
||||
});
|
||||
});
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import type {AutoCompleteCompleteEvent} from 'primeng/autocomplete';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, Subject, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {Book, BookMetadata} from '../../model/book.model';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {BookMetadataService} from '../../service/book-metadata.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {AddPhysicalBookDialogComponent} from './add-physical-book-dialog.component';
|
||||
|
||||
describe('AddPhysicalBookDialogComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createLibrary(overrides: Partial<Library> = {}): Library {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'Main Library',
|
||||
watch: true,
|
||||
paths: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 99,
|
||||
libraryId: 2,
|
||||
libraryName: 'Branch Library',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createMetadata(overrides: Partial<BookMetadata> = {}): BookMetadata {
|
||||
return {
|
||||
bookId: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(options: {
|
||||
dialogData?: {libraryId?: number};
|
||||
librariesData?: Library[];
|
||||
metadataValues?: {
|
||||
authors: string[];
|
||||
categories: string[];
|
||||
moods: string[];
|
||||
tags: string[];
|
||||
publishers: string[];
|
||||
series: string[];
|
||||
};
|
||||
lookupResult$?: Observable<BookMetadata>;
|
||||
createResult$?: Observable<Book>;
|
||||
} = {}) {
|
||||
const libraries = signal<Library[]>(options.librariesData ?? [
|
||||
createLibrary({id: 1, name: 'Main Library'}),
|
||||
createLibrary({id: 2, name: 'Branch Library'}),
|
||||
]);
|
||||
const uniqueMetadata = signal(options.metadataValues ?? {
|
||||
authors: ['Ursula Le Guin', 'Octavia Butler', 'Robin Hobb'],
|
||||
categories: ['Science Fiction', 'Epic Fantasy', 'Mystery'],
|
||||
moods: [],
|
||||
tags: [],
|
||||
publishers: [],
|
||||
series: [],
|
||||
});
|
||||
const lookupResult$ = options.lookupResult$ ?? new Subject<BookMetadata>();
|
||||
const createResult$ = options.createResult$ ?? new Subject<Book>();
|
||||
const lookupByIsbn = vi.fn(() => lookupResult$);
|
||||
const createPhysicalBook = vi.fn(() => createResult$);
|
||||
const dialogRef = {close: vi.fn()};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: DynamicDialogConfig, useValue: {data: options.dialogData ?? {}}},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: BookService, useValue: {uniqueMetadata, createPhysicalBook}},
|
||||
{provide: BookMetadataService, useValue: {lookupByIsbn}},
|
||||
{provide: LibraryService, useValue: {libraries}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new AddPhysicalBookDialogComponent());
|
||||
TestBed.flushEffects();
|
||||
|
||||
return {
|
||||
component,
|
||||
libraries,
|
||||
uniqueMetadata,
|
||||
lookupResult$,
|
||||
createResult$,
|
||||
lookupByIsbn,
|
||||
createPhysicalBook,
|
||||
dialogRef,
|
||||
};
|
||||
}
|
||||
|
||||
function triggerEnter(component: AddPhysicalBookDialogComponent, fieldName: 'authors' | 'categories', value: string): HTMLInputElement {
|
||||
const input = document.createElement('input');
|
||||
input.value = value;
|
||||
|
||||
component.onAutoCompleteKeyUp(fieldName, {
|
||||
key: 'Enter',
|
||||
target: input,
|
||||
} as unknown as KeyboardEvent);
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
function triggerSelect(component: AddPhysicalBookDialogComponent, fieldName: 'authors' | 'categories', value: string): HTMLInputElement {
|
||||
const input = document.createElement('input');
|
||||
input.value = value;
|
||||
|
||||
component.onAutoCompleteSelect(fieldName, {
|
||||
value,
|
||||
originalEvent: {target: input} as unknown as Event,
|
||||
});
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
it('prefers the dialog library selection when one is provided', () => {
|
||||
const {component} = createHarness({
|
||||
dialogData: {libraryId: 2},
|
||||
});
|
||||
|
||||
expect(component.selectedLibraryId).toBe(2);
|
||||
});
|
||||
|
||||
it('defaults to the first available library when the dialog does not provide one', () => {
|
||||
const {component} = createHarness({
|
||||
dialogData: {},
|
||||
});
|
||||
|
||||
expect(component.selectedLibraryId).toBe(1);
|
||||
});
|
||||
|
||||
it('filters authors and categories with case-insensitive substring matches', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
component.filterAuthors({query: 'taV', originalEvent: new Event('input')} as AutoCompleteCompleteEvent);
|
||||
component.filterCategories({query: 'fic', originalEvent: new Event('input')} as AutoCompleteCompleteEvent);
|
||||
|
||||
expect(component.filteredAuthors).toEqual(['Octavia Butler']);
|
||||
expect(component.filteredCategories).toEqual(['Science Fiction']);
|
||||
});
|
||||
|
||||
it('adds entered autocomplete values once and clears the input after Enter', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
const firstInput = triggerEnter(component, 'authors', ' N. K. Jemisin ');
|
||||
const duplicateInput = triggerEnter(component, 'authors', 'N. K. Jemisin');
|
||||
|
||||
expect(component.authors).toEqual(['N. K. Jemisin']);
|
||||
expect(firstInput.value).toBe('');
|
||||
expect(duplicateInput.value).toBe('');
|
||||
});
|
||||
|
||||
it('adds selected autocomplete values once and clears the input after selection', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
const firstInput = triggerSelect(component, 'categories', 'Mythic Fantasy');
|
||||
const duplicateInput = triggerSelect(component, 'categories', 'Mythic Fantasy');
|
||||
|
||||
expect(component.categories).toEqual(['Mythic Fantasy']);
|
||||
expect(firstInput.value).toBe('');
|
||||
expect(duplicateInput.value).toBe('');
|
||||
});
|
||||
|
||||
it('trims the isbn, hydrates metadata fields, and clears the fetching flag on success', () => {
|
||||
const lookupResult$ = new Subject<BookMetadata>();
|
||||
const {component, lookupByIsbn} = createHarness({lookupResult$});
|
||||
|
||||
component.isbn = ' 9780441172719 ';
|
||||
component.fetchMetadataByIsbn();
|
||||
|
||||
expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719');
|
||||
expect(component.isFetchingMetadata).toBe(true);
|
||||
|
||||
lookupResult$.next(createMetadata({
|
||||
title: 'Dune',
|
||||
authors: ['Frank Herbert'],
|
||||
description: 'Arrakis.',
|
||||
publisher: 'Ace',
|
||||
publishedDate: '1965',
|
||||
language: 'en',
|
||||
pageCount: 412,
|
||||
categories: ['Science Fiction'],
|
||||
thumbnailUrl: 'https://covers.example/dune.jpg',
|
||||
}));
|
||||
lookupResult$.complete();
|
||||
|
||||
expect(component.title).toBe('Dune');
|
||||
expect(component.authors).toEqual(['Frank Herbert']);
|
||||
expect(component.description).toBe('Arrakis.');
|
||||
expect(component.publisher).toBe('Ace');
|
||||
expect(component.publishedDate).toBe('1965');
|
||||
expect(component.language).toBe('en');
|
||||
expect(component.pageCount).toBe(412);
|
||||
expect(component.categories).toEqual(['Science Fiction']);
|
||||
expect(component.coverUrl).toBe('https://covers.example/dune.jpg');
|
||||
expect(component.isFetchingMetadata).toBe(false);
|
||||
});
|
||||
|
||||
it('does not start isbn lookup for blank or in-flight requests and clears the flag on error', () => {
|
||||
const {component, lookupByIsbn} = createHarness();
|
||||
|
||||
component.isbn = ' ';
|
||||
component.fetchMetadataByIsbn();
|
||||
expect(lookupByIsbn).not.toHaveBeenCalled();
|
||||
|
||||
component.isbn = '9780441172719';
|
||||
component.isFetchingMetadata = true;
|
||||
component.fetchMetadataByIsbn();
|
||||
expect(lookupByIsbn).not.toHaveBeenCalled();
|
||||
|
||||
component.isFetchingMetadata = false;
|
||||
lookupByIsbn.mockReturnValueOnce(throwError(() => new Error('lookup failed')));
|
||||
|
||||
component.fetchMetadataByIsbn();
|
||||
|
||||
expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719');
|
||||
expect(component.isFetchingMetadata).toBe(false);
|
||||
});
|
||||
|
||||
it('gates creation on required fields and does not submit when already loading', () => {
|
||||
const {component, createPhysicalBook} = createHarness();
|
||||
|
||||
expect(component.canCreate()).toBe(false);
|
||||
component.createBook();
|
||||
expect(createPhysicalBook).not.toHaveBeenCalled();
|
||||
|
||||
component.selectedLibraryId = 2;
|
||||
component.title = 'Physical Copy';
|
||||
expect(component.canCreate()).toBe(true);
|
||||
|
||||
component.isLoading = true;
|
||||
component.createBook();
|
||||
|
||||
expect(createPhysicalBook).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shapes the create payload, resets loading, and closes with the created book on success', () => {
|
||||
const createResult$ = new Subject<Book>();
|
||||
const createdBook = createBook({
|
||||
id: 321,
|
||||
libraryId: 2,
|
||||
libraryName: 'Branch Library',
|
||||
metadata: {bookId: 321, title: 'The Left Hand of Darkness'},
|
||||
});
|
||||
const {component, createPhysicalBook, dialogRef} = createHarness({createResult$});
|
||||
|
||||
component.selectedLibraryId = 2;
|
||||
component.title = ' The Left Hand of Darkness ';
|
||||
component.isbn = ' ';
|
||||
component.authors = ['Ursula Le Guin'];
|
||||
component.description = ' ';
|
||||
component.publisher = ' Ace Books ';
|
||||
component.publishedDate = ' 1969 ';
|
||||
component.language = ' en ';
|
||||
component.pageCount = 304;
|
||||
component.categories = ['Science Fiction'];
|
||||
component.coverUrl = 'https://covers.example/left-hand.jpg';
|
||||
|
||||
component.createBook();
|
||||
|
||||
expect(component.isLoading).toBe(true);
|
||||
expect(createPhysicalBook).toHaveBeenCalledWith({
|
||||
libraryId: 2,
|
||||
title: 'The Left Hand of Darkness',
|
||||
isbn: undefined,
|
||||
authors: ['Ursula Le Guin'],
|
||||
description: undefined,
|
||||
publisher: 'Ace Books',
|
||||
publishedDate: '1969',
|
||||
language: 'en',
|
||||
pageCount: 304,
|
||||
categories: ['Science Fiction'],
|
||||
thumbnailUrl: 'https://covers.example/left-hand.jpg',
|
||||
});
|
||||
|
||||
createResult$.next(createdBook);
|
||||
createResult$.complete();
|
||||
|
||||
expect(component.isLoading).toBe(false);
|
||||
expect(dialogRef.close).toHaveBeenCalledWith(createdBook);
|
||||
});
|
||||
|
||||
it('resets loading and keeps the dialog open when create fails', () => {
|
||||
const {component, createPhysicalBook, dialogRef} = createHarness();
|
||||
createPhysicalBook.mockReturnValueOnce(throwError(() => new Error('create failed')));
|
||||
|
||||
component.selectedLibraryId = 2;
|
||||
component.isbn = '9780441172719';
|
||||
|
||||
component.createBook();
|
||||
|
||||
expect(createPhysicalBook).toHaveBeenCalledWith({
|
||||
libraryId: 2,
|
||||
title: undefined,
|
||||
isbn: '9780441172719',
|
||||
authors: undefined,
|
||||
description: undefined,
|
||||
publisher: undefined,
|
||||
publishedDate: undefined,
|
||||
language: undefined,
|
||||
pageCount: undefined,
|
||||
categories: undefined,
|
||||
thumbnailUrl: undefined,
|
||||
});
|
||||
expect(component.isLoading).toBe(false);
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around PrimeNG file-upload callbacks,
|
||||
// dialog bootstrapping, and upload stream orchestration so single-file validation and upload state
|
||||
// transitions can be asserted without browser File objects and the live upload widget runtime.
|
||||
describe.skip('AdditionalFileUploaderComponent', () => {
|
||||
it('needs upload-widget seams to verify file-type resets, size validation, and file list management', () => {
|
||||
// TODO(seam): Cover onFileTypeChange, onFilesSelect, onClear, and badge/status helpers after FileUpload callbacks and browser File objects are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs upload-service seams to verify upload success, upload failure, and dialog close behavior', () => {
|
||||
// TODO(seam): Cover uploadFiles and closeDialog after BookFileService streams and dialog refs are exposed through a stable test harness.
|
||||
});
|
||||
});
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {convertToParamMap} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookBrowserEntityService} from './book-browser-entity.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {EntityType} from './book-browser.component';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {MagicShelfService, MagicShelf} from '../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {bookId: id, title: `Book ${id}`},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookBrowserEntityService', () => {
|
||||
let service: BookBrowserEntityService;
|
||||
let libraryService: {libraries: ReturnType<typeof vi.fn>};
|
||||
let shelfService: {shelves: ReturnType<typeof vi.fn>};
|
||||
let magicShelfService: {findShelfById: ReturnType<typeof vi.fn>};
|
||||
let bookRuleEvaluatorService: {evaluateGroup: ReturnType<typeof vi.fn>};
|
||||
|
||||
const library = {
|
||||
id: 1,
|
||||
name: 'Library',
|
||||
watch: true,
|
||||
paths: [{path: '/books'}]
|
||||
} as Library;
|
||||
const shelf = {id: 2, name: 'Shelf'} as Shelf;
|
||||
const magicShelf = {
|
||||
id: 3,
|
||||
name: 'Magic Shelf',
|
||||
filterJson: JSON.stringify({group: 'all'})
|
||||
} as MagicShelf;
|
||||
|
||||
beforeEach(() => {
|
||||
libraryService = {
|
||||
libraries: vi.fn(() => [library])
|
||||
};
|
||||
shelfService = {
|
||||
shelves: vi.fn(() => [shelf])
|
||||
};
|
||||
magicShelfService = {
|
||||
findShelfById: vi.fn((id: number) => id === 3 ? magicShelf : null)
|
||||
};
|
||||
bookRuleEvaluatorService = {
|
||||
evaluateGroup: vi.fn((book: Book) => book.id === 2)
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookBrowserEntityService,
|
||||
{provide: LibraryService, useValue: libraryService},
|
||||
{provide: ShelfService, useValue: shelfService},
|
||||
{provide: MagicShelfService, useValue: magicShelfService},
|
||||
{provide: BookRuleEvaluatorService, useValue: bookRuleEvaluatorService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookBrowserEntityService);
|
||||
});
|
||||
|
||||
it('resolves entity ids from route params in priority order', () => {
|
||||
const allParams = convertToParamMap({
|
||||
libraryId: '1',
|
||||
shelfId: '2',
|
||||
magicShelfId: '3'
|
||||
});
|
||||
const shelfFirstParams = convertToParamMap({
|
||||
shelfId: '2',
|
||||
magicShelfId: '3'
|
||||
});
|
||||
const emptyParams = convertToParamMap({});
|
||||
|
||||
expect(service.getEntityInfo(allParams)).toEqual({
|
||||
entityId: 1,
|
||||
entityType: EntityType.LIBRARY
|
||||
});
|
||||
expect(service.getEntityInfo(shelfFirstParams)).toEqual({
|
||||
entityId: 2,
|
||||
entityType: EntityType.SHELF
|
||||
});
|
||||
expect(service.getEntityInfo(emptyParams)).toEqual({
|
||||
entityId: NaN,
|
||||
entityType: EntityType.ALL_BOOKS
|
||||
});
|
||||
});
|
||||
|
||||
it('returns entity records and recognizes library and magic shelf types', () => {
|
||||
expect(service.getEntity(1, EntityType.LIBRARY)).toBe(library);
|
||||
expect(service.getEntity(2, EntityType.SHELF)).toBe(shelf);
|
||||
expect(service.getEntity(3, EntityType.MAGIC_SHELF)).toBe(magicShelf);
|
||||
expect(service.getEntity(999, EntityType.ALL_BOOKS)).toBeNull();
|
||||
|
||||
expect(service.isLibrary(library)).toBe(true);
|
||||
expect(service.isLibrary(shelf as Library | Shelf | MagicShelf)).toBe(false);
|
||||
expect(service.isMagicShelf(magicShelf)).toBe(true);
|
||||
expect(service.isMagicShelf(null)).toBe(false);
|
||||
});
|
||||
|
||||
it('filters books by entity type and handles magic shelf parsing failures', () => {
|
||||
const books = [
|
||||
makeBook(1, {libraryId: 1, shelves: [{id: 2} as never]}),
|
||||
makeBook(2, {libraryId: 1, shelves: []}),
|
||||
makeBook(3, {libraryId: 2, shelves: [{id: 2} as never]})
|
||||
];
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
|
||||
expect(service.getBooksByEntity(books, 1, EntityType.LIBRARY)).toEqual([
|
||||
books[0],
|
||||
books[1]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 2, EntityType.SHELF)).toEqual([
|
||||
books[0],
|
||||
books[2]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 0, EntityType.UNSHELVED)).toEqual([
|
||||
books[1]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 0, EntityType.ALL_BOOKS)).toBe(books);
|
||||
|
||||
expect(service.getBooksByEntity(books, 3, EntityType.MAGIC_SHELF)).toEqual([
|
||||
books[1]
|
||||
]);
|
||||
expect(bookRuleEvaluatorService.evaluateGroup).toHaveBeenCalledWith(
|
||||
books[0],
|
||||
{group: 'all'},
|
||||
books
|
||||
);
|
||||
|
||||
magicShelfService.findShelfById.mockReturnValueOnce({
|
||||
id: 4,
|
||||
name: 'Broken Magic Shelf',
|
||||
filterJson: '{broken json'
|
||||
} as MagicShelf);
|
||||
|
||||
expect(service.getBooksByEntity(books, 4, EntityType.MAGIC_SHELF)).toEqual([]);
|
||||
expect(warnSpy).toHaveBeenCalledWith('Invalid filterJson for MagicShelf');
|
||||
});
|
||||
});
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {EntityType} from './book-browser.component';
|
||||
import {
|
||||
BookBrowserQueryParamsService,
|
||||
QUERY_PARAMS,
|
||||
VIEW_MODES
|
||||
} from './book-browser-query-params.service';
|
||||
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||
import {EntityViewPreferences} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('BookBrowserQueryParamsService', () => {
|
||||
let service: BookBrowserQueryParamsService;
|
||||
let routerNavigate: ReturnType<typeof vi.fn>;
|
||||
let routeSnapshot: {
|
||||
queryParams: Record<string, string | null>;
|
||||
queryParamMap: ParamMap;
|
||||
};
|
||||
let activatedRoute: {snapshot: typeof routeSnapshot};
|
||||
|
||||
const sortOptions: SortOption[] = [
|
||||
{label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING},
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
{label: 'Authors', field: 'author', direction: SortDirection.ASCENDING}
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
routerNavigate = vi.fn();
|
||||
routeSnapshot = {
|
||||
queryParams: {},
|
||||
queryParamMap: convertToParamMap({})
|
||||
};
|
||||
activatedRoute = {snapshot: routeSnapshot};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookBrowserQueryParamsService,
|
||||
{provide: Router, useValue: {navigate: routerNavigate}},
|
||||
{provide: ActivatedRoute, useValue: activatedRoute}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookBrowserQueryParamsService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('parses explicit query params, filters, and toggle state', () => {
|
||||
const result = service.parseQueryParams(
|
||||
convertToParamMap({
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE,
|
||||
[QUERY_PARAMS.SORT]: 'title:desc,author:asc',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi,series:A%3AB',
|
||||
[QUERY_PARAMS.FMODE]: 'or',
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
}),
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
viewMode: VIEW_MODES.TABLE,
|
||||
sortOption: {label: 'Title', field: 'title', direction: SortDirection.DESCENDING},
|
||||
sortCriteria: [
|
||||
{label: 'Title', field: 'title', direction: SortDirection.DESCENDING},
|
||||
{label: 'Authors', field: 'author', direction: SortDirection.ASCENDING}
|
||||
],
|
||||
filters: {
|
||||
tag: ['fiction', 'sci fi'],
|
||||
series: ['A:B']
|
||||
},
|
||||
filterMode: 'or',
|
||||
viewModeFromToggle: true
|
||||
});
|
||||
});
|
||||
|
||||
it('uses entity overrides, legacy preferences, and default sort fallback', () => {
|
||||
const userPrefs: EntityViewPreferences = {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
sortCriteria: [
|
||||
{field: 'title', direction: 'DESC'}
|
||||
],
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 7,
|
||||
preferences: {
|
||||
sortKey: 'authors',
|
||||
sortDir: 'DESC',
|
||||
sortCriteria: [
|
||||
{field: 'authors', direction: 'DESC'}
|
||||
],
|
||||
view: 'GRID',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: false
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const overrideResult = service.parseQueryParams(
|
||||
convertToParamMap({
|
||||
[QUERY_PARAMS.FMODE]: 'single'
|
||||
}),
|
||||
userPrefs,
|
||||
EntityType.LIBRARY,
|
||||
7,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(overrideResult.viewMode).toBe(VIEW_MODES.GRID);
|
||||
expect(overrideResult.filterMode).toBe('single');
|
||||
expect(overrideResult.sortCriteria).toEqual([
|
||||
{label: 'authors', field: 'authors', direction: SortDirection.DESCENDING}
|
||||
]);
|
||||
|
||||
const legacyResult = service.parseQueryParams(
|
||||
convertToParamMap({}),
|
||||
{
|
||||
global: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'DESC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(legacyResult.sortOption).toEqual({
|
||||
label: 'Title',
|
||||
field: 'title',
|
||||
direction: SortDirection.DESCENDING
|
||||
});
|
||||
expect(legacyResult.viewMode).toBe('table');
|
||||
|
||||
const fallbackResult = service.parseQueryParams(
|
||||
convertToParamMap({}),
|
||||
{
|
||||
global: {
|
||||
sortKey: 'missing',
|
||||
sortDir: 'DESC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(fallbackResult.sortOption).toEqual({
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
});
|
||||
});
|
||||
|
||||
it('serializes and deserializes sorts and filters while ignoring malformed input', () => {
|
||||
expect(service.serializeSort([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
{label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING}
|
||||
])).toBe('title:asc,addedOn:desc');
|
||||
|
||||
expect(service.deserializeSort('title:desc,missing:asc', sortOptions)).toEqual([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.DESCENDING}
|
||||
]);
|
||||
|
||||
expect(service.serializeFilters({
|
||||
tag: ['sci fi', 'new:release'],
|
||||
series: ['A/B']
|
||||
})).toBe('tag:sci%20fi|new%3Arelease,series:A%2FB');
|
||||
|
||||
expect(service.deserializeFilters('tag:sci%20fi|new%3Arelease,broken,series:A%2FB')).toEqual({
|
||||
tag: ['sci fi', 'new:release'],
|
||||
series: ['A/B']
|
||||
});
|
||||
});
|
||||
|
||||
it('updates query params for view mode, sort, filters, and sync changes', () => {
|
||||
routeSnapshot.queryParams = {
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'title:asc',
|
||||
[QUERY_PARAMS.DIRECTION]: 'desc',
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.GRID,
|
||||
[QUERY_PARAMS.FMODE]: 'and',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
};
|
||||
routeSnapshot.queryParamMap = convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
});
|
||||
|
||||
service.updateViewMode(VIEW_MODES.TABLE);
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE,
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
}));
|
||||
|
||||
service.updateSort({label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: expect.objectContaining({
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'addedOn:desc',
|
||||
[QUERY_PARAMS.DIRECTION]: null
|
||||
}),
|
||||
replaceUrl: true
|
||||
}));
|
||||
|
||||
routerNavigate.mockClear();
|
||||
routeSnapshot.queryParamMap = convertToParamMap({});
|
||||
service.updateFilters(null);
|
||||
expect(routerNavigate).not.toHaveBeenCalled();
|
||||
|
||||
routeSnapshot.queryParamMap = convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
});
|
||||
service.updateFilters({tag: ['fiction', 'sci fi']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {[QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi'},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
service.updateFilterMode('single', {tag: ['fiction', 'sci fi']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.FMODE]: 'single',
|
||||
[QUERY_PARAMS.FILTER]: null
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
service.updateFilterMode('or', {tag: ['fiction']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.FMODE]: 'or'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
routerNavigate.mockClear();
|
||||
service.syncQueryParams('grid', 'and', {tag: ['fiction']});
|
||||
expect(routerNavigate).not.toHaveBeenCalled();
|
||||
|
||||
service.syncQueryParams('table', 'single', {tag: ['fiction']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: {
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'title:asc',
|
||||
[QUERY_PARAMS.DIRECTION]: 'desc',
|
||||
[QUERY_PARAMS.VIEW]: 'table',
|
||||
[QUERY_PARAMS.FMODE]: 'single',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
},
|
||||
replaceUrl: true
|
||||
}));
|
||||
});
|
||||
|
||||
it('detects when a series filter should force expansion', () => {
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({}))).toBe(false);
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction,series:space-opera'
|
||||
}))).toBe(true);
|
||||
});
|
||||
});
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookBrowserScrollService} from './book-browser-scroll.service';
|
||||
|
||||
describe('BookBrowserScrollService', () => {
|
||||
const service = new BookBrowserScrollService();
|
||||
|
||||
it('stores, retrieves, clears, and creates stable keys', () => {
|
||||
expect(service.getPosition('books')).toBeUndefined();
|
||||
|
||||
service.savePosition('books', 144);
|
||||
service.savePosition('books:library', 288);
|
||||
|
||||
expect(service.getPosition('books')).toBe(144);
|
||||
expect(service.getPosition('books:library')).toBe(288);
|
||||
expect(service.createKey('/books', {libraryId: '1', shelfId: '2'})).toBe('/books:1-2');
|
||||
expect(service.createKey('/books', {})).toBe('/books');
|
||||
|
||||
service.clearPosition('books');
|
||||
expect(service.getPosition('books')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This needs a routed integration harness for the query-backed book browser,
|
||||
// PrimeNG overlays, and the persisted filter/sidebar preference services before the
|
||||
// control-flow branches can be exercised without brittle template scaffolding.
|
||||
describe.skip('BookBrowserComponent', () => {
|
||||
it('needs a browser-level harness for routed query state, filters, and overlay actions', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service';
|
||||
|
||||
describe('BookCardOverlayPreferenceService', () => {
|
||||
let service: BookCardOverlayPreferenceService;
|
||||
let userService: {
|
||||
currentUser: unknown;
|
||||
getCurrentUser: ReturnType<typeof vi.fn>;
|
||||
updateUserSetting: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let user: {
|
||||
id: number;
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
overlayBookType?: boolean;
|
||||
showBookTypePill?: boolean;
|
||||
};
|
||||
overrides: unknown[];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
user = {
|
||||
id: 7,
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
overlayBookType: false,
|
||||
},
|
||||
overrides: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
userService = {
|
||||
currentUser: signal(user),
|
||||
getCurrentUser: vi.fn(() => user),
|
||||
updateUserSetting: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookCardOverlayPreferenceService,
|
||||
{provide: UserService, useValue: userService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookCardOverlayPreferenceService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('updates the exposed signal immediately when the overlay preference changes', () => {
|
||||
service.setShowBookTypePill(false);
|
||||
|
||||
expect(service.showBookTypePill()).toBe(false);
|
||||
});
|
||||
|
||||
it('persists the updated global overlay preference after the debounce delay', () => {
|
||||
service.setShowBookTypePill(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(
|
||||
7,
|
||||
'entityViewPreferences',
|
||||
expect.objectContaining({
|
||||
global: expect.objectContaining({overlayBookType: true}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
import {NO_ERRORS_SCHEMA, SimpleChange, SimpleChanges} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {User, UserService} from '../../../../settings/user-management/user.service';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model';
|
||||
import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||
import {BookCardComponent} from './book-card.component';
|
||||
import {BookFileService} from '../../../service/book-file.service';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
|
||||
function makeBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 41,
|
||||
libraryId: 2,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: 41,
|
||||
title: 'Book Title',
|
||||
seriesName: 'Series Name',
|
||||
coverUpdatedOn: '2024-01-01',
|
||||
audiobookCoverUpdatedOn: '2024-01-02',
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeUser(metadataCenterViewMode: 'route' | 'dialog'): User {
|
||||
return {
|
||||
id: 1,
|
||||
username: 'tester',
|
||||
name: 'Tester',
|
||||
email: 'tester@example.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false,
|
||||
},
|
||||
userSettings: {
|
||||
metadataCenterViewMode,
|
||||
perBookSetting: {} as never,
|
||||
pdfReaderSetting: {} as never,
|
||||
epubReaderSetting: {} as never,
|
||||
ebookReaderSetting: {} as never,
|
||||
cbxReaderSetting: {} as never,
|
||||
newPdfReaderSetting: {} as never,
|
||||
sidebarLibrarySorting: {} as never,
|
||||
sidebarShelfSorting: {} as never,
|
||||
sidebarMagicShelfSorting: {} as never,
|
||||
filterMode: 'and',
|
||||
enableSeriesView: false,
|
||||
entityViewPreferences: {global: {} as never, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookCardComponent', () => {
|
||||
let component: BookCardComponent;
|
||||
let bookService: {
|
||||
readBook: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookFileService: {
|
||||
downloadFile: ReturnType<typeof vi.fn>;
|
||||
downloadAdditionalFile: ReturnType<typeof vi.fn>;
|
||||
deleteAdditionalFile: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookMetadataManageService: {
|
||||
regenerateCover: ReturnType<typeof vi.fn>;
|
||||
generateCustomCover: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let taskHelperService: {
|
||||
refreshMetadataTask: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {
|
||||
currentUser: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let emailService: {
|
||||
emailBookQuick: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let messageService: {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let router: {
|
||||
navigate: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let urlHelper: {
|
||||
getThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let confirmationService: {
|
||||
confirm: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookDialogHelperService: {
|
||||
openShelfAssignerDialog: ReturnType<typeof vi.fn>;
|
||||
openBookDetailsDialog: ReturnType<typeof vi.fn>;
|
||||
openCustomSendDialog: ReturnType<typeof vi.fn>;
|
||||
openMetadataRefreshDialog: ReturnType<typeof vi.fn>;
|
||||
openFileMoverDialog: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookNavigationService: {
|
||||
availableBookIds: ReturnType<typeof vi.fn>;
|
||||
setNavigationContext: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let appSettingsService: {
|
||||
appSettings: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translocoService: {
|
||||
translate: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let queryClient: {
|
||||
fetchQuery: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let cdr: {
|
||||
markForCheck: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
bookService = {
|
||||
readBook: vi.fn(),
|
||||
};
|
||||
bookFileService = {
|
||||
downloadFile: vi.fn(),
|
||||
downloadAdditionalFile: vi.fn(),
|
||||
deleteAdditionalFile: vi.fn(),
|
||||
};
|
||||
bookMetadataManageService = {
|
||||
regenerateCover: vi.fn(),
|
||||
generateCustomCover: vi.fn(),
|
||||
};
|
||||
taskHelperService = {
|
||||
refreshMetadataTask: vi.fn(),
|
||||
};
|
||||
userService = {
|
||||
currentUser: vi.fn(() => null),
|
||||
};
|
||||
emailService = {
|
||||
emailBookQuick: vi.fn(),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
router = {
|
||||
navigate: vi.fn(),
|
||||
};
|
||||
urlHelper = {
|
||||
getThumbnailUrl: vi.fn((bookId: number, coverUpdatedOn?: string) => `thumb:${bookId}:${coverUpdatedOn ?? 'none'}`),
|
||||
getAudiobookThumbnailUrl: vi.fn((bookId: number, audiobookCoverUpdatedOn?: string) => `audio-thumb:${bookId}:${audiobookCoverUpdatedOn ?? 'none'}`),
|
||||
};
|
||||
confirmationService = {
|
||||
confirm: vi.fn(),
|
||||
};
|
||||
bookDialogHelperService = {
|
||||
openShelfAssignerDialog: vi.fn(),
|
||||
openBookDetailsDialog: vi.fn(),
|
||||
openCustomSendDialog: vi.fn(),
|
||||
openMetadataRefreshDialog: vi.fn(),
|
||||
openFileMoverDialog: vi.fn(),
|
||||
};
|
||||
bookNavigationService = {
|
||||
availableBookIds: vi.fn(() => []),
|
||||
setNavigationContext: vi.fn(),
|
||||
};
|
||||
appSettingsService = {
|
||||
appSettings: vi.fn(() => ({diskType: 'LOCAL'})),
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string, params?: Record<string, unknown>) => (params ? `${key}:${JSON.stringify(params)}` : key)),
|
||||
};
|
||||
queryClient = {
|
||||
fetchQuery: vi.fn(),
|
||||
};
|
||||
cdr = {
|
||||
markForCheck: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BookCardComponent],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
providers: [
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: BookFileService, useValue: bookFileService},
|
||||
{provide: BookMetadataManageService, useValue: bookMetadataManageService},
|
||||
{provide: TaskHelperService, useValue: taskHelperService},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: EmailService, useValue: emailService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UrlHelperService, useValue: urlHelper},
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: BookDialogHelperService, useValue: bookDialogHelperService},
|
||||
{provide: BookNavigationService, useValue: bookNavigationService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
{provide: BookCardComponent, useValue: BookCardComponent},
|
||||
{provide: 'ChangeDetectorRef', useValue: cdr},
|
||||
],
|
||||
});
|
||||
|
||||
component = TestBed.createComponent(BookCardComponent).componentInstance;
|
||||
(component as unknown as {cdr: typeof cdr}).cdr = cdr;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('derives progress, audiobook, and series display state from inputs and changes', () => {
|
||||
component.book = makeBook({
|
||||
id: 8,
|
||||
metadata: {
|
||||
bookId: 8,
|
||||
title: 'Volume One',
|
||||
seriesName: 'Series Saga',
|
||||
coverUpdatedOn: '2024-04-01',
|
||||
audiobookCoverUpdatedOn: '2024-04-02',
|
||||
},
|
||||
seriesCount: 2,
|
||||
primaryFile: {
|
||||
id: 81,
|
||||
bookId: 8,
|
||||
bookType: 'AUDIOBOOK',
|
||||
extension: 'm4b',
|
||||
filePath: 'books/volume-one.m4b',
|
||||
},
|
||||
pdfProgress: {page: 11, percentage: 42},
|
||||
koreaderProgress: {percentage: 11},
|
||||
koboProgress: {percentage: 7},
|
||||
readStatus: ReadStatus.READING,
|
||||
});
|
||||
component.seriesViewEnabled = true;
|
||||
component.isSeriesCollapsed = true;
|
||||
component.forceEbookMode = false;
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.hasProgress).toBe(true);
|
||||
expect(component.displayTitle).toBe('Series Saga');
|
||||
expect(component.titleTooltip).toContain('Series Saga');
|
||||
expect(component.coverImageUrl).toBe('audio-thumb:8:2024-04-02');
|
||||
expect(component.progressTooltip).toBe('42% (Grimmory) | 11% (KOReader) | 7% (Kobo)');
|
||||
expect(component.readButtonIcon).toBe('pi pi-forward');
|
||||
|
||||
component.isSeriesCollapsed = false;
|
||||
component.ngOnChanges({
|
||||
isSeriesCollapsed: new SimpleChange(true, false, false),
|
||||
} as SimpleChanges);
|
||||
|
||||
expect(component.displayTitle).toBe('Volume One');
|
||||
expect(component.titleTooltip).toContain('Volume One');
|
||||
});
|
||||
|
||||
it('uses forced ebook mode for audiobook reads and falls back to the normal read flow otherwise', () => {
|
||||
const audiobookWithAlternativeFormat = makeBook({
|
||||
id: 12,
|
||||
primaryFile: {
|
||||
id: 121,
|
||||
bookId: 12,
|
||||
bookType: 'AUDIOBOOK',
|
||||
extension: 'm4b',
|
||||
filePath: 'books/audiobook.m4b',
|
||||
},
|
||||
alternativeFormats: [
|
||||
{
|
||||
id: 122,
|
||||
bookId: 12,
|
||||
bookType: 'PDF',
|
||||
fileName: 'A PDF',
|
||||
filePath: 'books/audiobook.pdf',
|
||||
fileSizeKb: 2048,
|
||||
} as AdditionalFile,
|
||||
],
|
||||
});
|
||||
|
||||
component.forceEbookMode = true;
|
||||
component.readBook(audiobookWithAlternativeFormat);
|
||||
|
||||
expect(bookService.readBook).toHaveBeenCalledWith(12, undefined, 'PDF');
|
||||
|
||||
component.forceEbookMode = false;
|
||||
component.readBook(makeBook({id: 13}));
|
||||
|
||||
expect(bookService.readBook).toHaveBeenCalledWith(13);
|
||||
});
|
||||
|
||||
it('derives display format from missing primary files, extensions, paths, and forced audiobook ebook types', () => {
|
||||
component.book = makeBook({id: 20, primaryFile: undefined});
|
||||
component.forceEbookMode = false;
|
||||
expect(component.getDisplayFormat()).toBe('PHY');
|
||||
|
||||
component.book = makeBook({
|
||||
id: 21,
|
||||
primaryFile: {
|
||||
id: 211,
|
||||
bookId: 21,
|
||||
bookType: 'PDF',
|
||||
extension: 'pdf',
|
||||
filePath: 'books/volume-one.pdf',
|
||||
},
|
||||
});
|
||||
expect(component.getDisplayFormat()).toBe('PDF');
|
||||
|
||||
component.book = makeBook({
|
||||
id: 22,
|
||||
primaryFile: {
|
||||
id: 221,
|
||||
bookId: 22,
|
||||
bookType: 'EPUB',
|
||||
filePath: 'books/volume-one.mobi',
|
||||
},
|
||||
});
|
||||
expect(component.getDisplayFormat()).toBe('MOBI');
|
||||
|
||||
component.book = makeBook({
|
||||
id: 23,
|
||||
primaryFile: {
|
||||
id: 231,
|
||||
bookId: 23,
|
||||
bookType: 'AUDIOBOOK',
|
||||
filePath: 'books/volume-one.m4b',
|
||||
},
|
||||
epubProgress: {cfi: 'epub', percentage: 73},
|
||||
});
|
||||
component.forceEbookMode = true;
|
||||
expect(component.getDisplayFormat()).toBe('EPUB');
|
||||
});
|
||||
|
||||
it('guards card selection and preserves shift metadata for ctrl-initiated changes only', () => {
|
||||
component.book = makeBook({id: 30});
|
||||
component.index = 4;
|
||||
component.isCheckboxEnabled = false;
|
||||
component.isSelected = false;
|
||||
component.onBookSelect = vi.fn();
|
||||
|
||||
const emitSpy = vi.spyOn(component.checkboxClick, 'emit');
|
||||
|
||||
component.toggleCardSelection(true);
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
expect(component.onBookSelect).not.toHaveBeenCalled();
|
||||
|
||||
component.isCheckboxEnabled = true;
|
||||
component.captureMouseEvent(new MouseEvent('mousedown', {shiftKey: true}));
|
||||
|
||||
component.onCardClick(new MouseEvent('click', {ctrlKey: false}));
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
|
||||
component.onCardClick(new MouseEvent('click', {ctrlKey: true}));
|
||||
|
||||
expect(component.isSelected).toBe(true);
|
||||
expect(emitSpy).toHaveBeenCalledWith({
|
||||
index: 4,
|
||||
book: component.book,
|
||||
selected: true,
|
||||
shiftKey: true,
|
||||
});
|
||||
expect(component.onBookSelect).toHaveBeenCalledWith(component.book, true);
|
||||
});
|
||||
|
||||
it('routes series info and book details through the correct destination', () => {
|
||||
const book = makeBook({
|
||||
id: 44,
|
||||
metadata: {
|
||||
bookId: 44,
|
||||
title: 'Volume Four',
|
||||
seriesName: 'The Series',
|
||||
coverUpdatedOn: '2024-05-01',
|
||||
audiobookCoverUpdatedOn: '2024-05-02',
|
||||
},
|
||||
});
|
||||
|
||||
userService.currentUser.mockReturnValue(makeUser('route'));
|
||||
component.book = book;
|
||||
component.isSeriesCollapsed = true;
|
||||
component.ngOnInit();
|
||||
|
||||
component.openSeriesInfo();
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/series', 'The Series']);
|
||||
|
||||
bookNavigationService.availableBookIds.mockReturnValue([2, 44, 77]);
|
||||
component.isSeriesCollapsed = false;
|
||||
component.openSeriesInfo();
|
||||
|
||||
expect(bookNavigationService.setNavigationContext).toHaveBeenCalledWith([2, 44, 77], 44);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/book', 44], {
|
||||
queryParams: {tab: 'view'},
|
||||
});
|
||||
|
||||
userService.currentUser.mockReturnValue(makeUser('dialog'));
|
||||
const dialogComponent = component as unknown as {metadataCenterViewMode: 'route' | 'dialog'};
|
||||
dialogComponent.metadataCenterViewMode = 'dialog';
|
||||
router.navigate.mockClear();
|
||||
bookNavigationService.setNavigationContext.mockClear();
|
||||
|
||||
component.openBookInfo(book);
|
||||
|
||||
expect(bookDialogHelperService.openBookDetailsDialog).toHaveBeenCalledWith(44);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
expect(bookNavigationService.setNavigationContext).toHaveBeenCalledWith([2, 44, 77], 44);
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
|
||||
describe('BookDialogHelperService', () => {
|
||||
let service: BookDialogHelperService;
|
||||
let dialogLauncherService: {openDialog: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
dialogLauncherService = {
|
||||
openDialog: vi.fn(() => ({id: 'dialog-ref'})),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookDialogHelperService,
|
||||
{provide: DialogLauncherService, useValue: dialogLauncherService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookDialogHelperService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('opens the book details dialog with the expected payload', () => {
|
||||
const dialogRef = service.openBookDetailsDialog(42);
|
||||
|
||||
expect(dialogLauncherService.openDialog).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
expect.objectContaining({
|
||||
showHeader: false,
|
||||
data: {bookId: 42},
|
||||
})
|
||||
);
|
||||
expect(dialogRef).toEqual({id: 'dialog-ref'});
|
||||
});
|
||||
|
||||
it('returns null instead of opening the shelf assigner when no inputs are provided', () => {
|
||||
const dialogRef = service.openShelfAssignerDialog(null, null);
|
||||
|
||||
expect(dialogRef).toBeNull();
|
||||
expect(dialogLauncherService.openDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens the bulk file attacher with the provided source books', () => {
|
||||
const sourceBooks = [{id: 1}, {id: 2}] as never[];
|
||||
|
||||
service.openBulkBookFileAttacherDialog(sourceBooks);
|
||||
|
||||
expect(dialogLauncherService.openDialog).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
expect.objectContaining({
|
||||
showHeader: false,
|
||||
data: {sourceBooks},
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {convertToParamMap} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookFilterOrchestrationService} from './book-filter-orchestration.service';
|
||||
import {SortService} from '../../service/sort.service';
|
||||
|
||||
describe('BookFilterOrchestrationService', () => {
|
||||
let service: BookFilterOrchestrationService;
|
||||
let sortService: {applyMultiSort: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
sortService = {
|
||||
applyMultiSort: vi.fn((books: unknown[]) => books),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookFilterOrchestrationService,
|
||||
{provide: SortService, useValue: sortService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookFilterOrchestrationService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('passes searched and collapsed books through the sorter', () => {
|
||||
const books = [
|
||||
{id: 1, metadata: {title: 'Alpha Flight'}},
|
||||
{id: 2, metadata: {title: 'Beta Test'}},
|
||||
] as never[];
|
||||
const seriesCollapseFilter = {
|
||||
collapseBooks: vi.fn((items: unknown[]) => items),
|
||||
};
|
||||
const sortCriteria = [{property: 'title', direction: 'ASC'}] as never[];
|
||||
|
||||
const result = service.applyFilters(
|
||||
books,
|
||||
'alpha',
|
||||
null,
|
||||
'and',
|
||||
seriesCollapseFilter as never,
|
||||
false,
|
||||
false,
|
||||
sortCriteria
|
||||
);
|
||||
|
||||
expect(seriesCollapseFilter.collapseBooks).toHaveBeenCalledWith(
|
||||
[books[0]],
|
||||
false,
|
||||
false
|
||||
);
|
||||
expect(sortService.applyMultiSort).toHaveBeenCalledWith([books[0]], sortCriteria);
|
||||
expect(result).toEqual([books[0]]);
|
||||
});
|
||||
|
||||
it('forces series expansion only when a series filter is present in the query string', () => {
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({filter: 'author:42,series:Saga'}))).toBe(true);
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({filter: 'author:42'}))).toBe(false);
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({}))).toBe(false);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around reset streams, user-setting effects,
|
||||
// and virtual-scroll accordion rendering so filter-mode changes and panel expansion can be
|
||||
// asserted without the full book-browser sidebar runtime.
|
||||
describe.skip('BookFilterComponent', () => {
|
||||
it('needs signal seams to verify visible filter hydration, mode changes, and emitted active-filter payloads', () => {
|
||||
// TODO(seam): Cover selectedFilterMode, setFilters, and emitFilters after the user-settings signal and filter service signals are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs UI-shell seams to verify reset handling, panel expansion, and multi-select filter clicks', () => {
|
||||
// TODO(seam): Cover handleFilterClick, clearActiveFilter, and accordion expansion after the virtual-scroll and select-button runtime is removed from the test surface.
|
||||
});
|
||||
});
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {
|
||||
CONTENT_RATING_LABELS,
|
||||
FILTER_CONFIGS,
|
||||
FILTER_EXTRACTORS,
|
||||
FILTER_LABEL_KEYS,
|
||||
MATCH_SCORE_RANGES,
|
||||
NUMERIC_ID_FILTER_TYPES,
|
||||
RATING_OPTIONS_10,
|
||||
READ_STATUS_LABELS
|
||||
} from './book-filter.config';
|
||||
|
||||
const makeBook = (overrides: Partial<Book> = {}): Book => ({
|
||||
id: 1,
|
||||
libraryId: 9,
|
||||
libraryName: 'Main',
|
||||
...overrides
|
||||
});
|
||||
|
||||
describe('book-filter.config', () => {
|
||||
it('covers every read status with a label', () => {
|
||||
expect(READ_STATUS_LABELS[ReadStatus.UNREAD]).toBe('Unread');
|
||||
expect(READ_STATUS_LABELS[ReadStatus.UNSET]).toBe('Unset');
|
||||
expect(Object.keys(READ_STATUS_LABELS)).toHaveLength(Object.keys(ReadStatus).length);
|
||||
});
|
||||
|
||||
it('defines 10 one-step rating buckets', () => {
|
||||
expect(RATING_OPTIONS_10).toHaveLength(10);
|
||||
expect(RATING_OPTIONS_10[0]).toMatchObject({id: 1, label: '1', min: 1, max: 2, sortIndex: 0});
|
||||
expect(RATING_OPTIONS_10.at(-1)).toMatchObject({id: 10, label: '10', min: 10, max: 11, sortIndex: 9});
|
||||
});
|
||||
|
||||
it('keeps filter labels and configs aligned', () => {
|
||||
const configKeys = Object.keys(FILTER_CONFIGS).sort();
|
||||
const labelKeysWithoutLibrary = Object.keys(FILTER_LABEL_KEYS).filter((key) => key !== 'library').sort();
|
||||
|
||||
expect(labelKeysWithoutLibrary).toEqual(configKeys);
|
||||
expect(FILTER_LABEL_KEYS.library).toBe('book.filter.labels.library');
|
||||
expect(NUMERIC_ID_FILTER_TYPES.has('pageCount')).toBe(true);
|
||||
expect(NUMERIC_ID_FILTER_TYPES.has('author')).toBe(false);
|
||||
});
|
||||
|
||||
it('normalizes read status, metadata match score, and content ratings', () => {
|
||||
expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: ReadStatus.READING}))).toEqual([
|
||||
{id: ReadStatus.READING, name: 'Reading'}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: 'INVALID' as ReadStatus}))).toEqual([
|
||||
{id: ReadStatus.UNSET, name: 'Unset'}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.matchScore(makeBook({metadataMatchScore: 92}))).toEqual([
|
||||
{id: MATCH_SCORE_RANGES[1].id, name: MATCH_SCORE_RANGES[1].label, sortIndex: MATCH_SCORE_RANGES[1].sortIndex}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.contentRating(makeBook({
|
||||
metadata: {bookId: 1, contentRating: 'EVERYONE'}
|
||||
}))).toEqual([{id: 'EVERYONE', name: CONTENT_RATING_LABELS['EVERYONE']}]);
|
||||
});
|
||||
|
||||
it('builds comic creator filters with role-aware labels', () => {
|
||||
const filters = FILTER_EXTRACTORS.comicCreator(makeBook({
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
comicMetadata: {
|
||||
pencillers: ['Jane Artist'],
|
||||
editors: ['Max Editor']
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
expect(filters).toEqual([
|
||||
{id: 'Jane Artist:penciller', name: 'Jane Artist (Penciller)'},
|
||||
{id: 'Max Editor:editor', name: 'Max Editor (Editor)'}
|
||||
]);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around the live book, library, and
|
||||
// magic-shelf signal graph so dynamic filter aggregation can be asserted without recreating the
|
||||
// full sidebar filter runtime and evaluator dependencies.
|
||||
describe.skip('BookFilterService', () => {
|
||||
it('needs signal seams to verify library, shelf, and magic-shelf entity filtering across active sidebar filters', () => {
|
||||
// TODO(seam): Cover createFilterSignals and filterBooksByEntity once the dependent signals and evaluator service are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs aggregation seams to verify filter count sorting, numeric-id coercion, and invalid magic-shelf fallback handling', () => {
|
||||
// TODO(seam): Cover buildAndSortFilters, processFilterValue, and filterByMagicShelf after extractor inputs and service state are exposed through a stable harness.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookSelectionService} from './book-selection.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {bookId: id, title: `Book ${id}`},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookSelectionService', () => {
|
||||
let service: BookSelectionService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [BookSelectionService]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookSelectionService);
|
||||
});
|
||||
|
||||
it('selects and deselects single books and series groups', () => {
|
||||
const singleBook = makeBook(1);
|
||||
const seriesBook = makeBook(2, {
|
||||
seriesBooks: [makeBook(2), makeBook(3)]
|
||||
});
|
||||
|
||||
service.selectBook(singleBook);
|
||||
service.selectBook(seriesBook);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set([1, 2, 3]));
|
||||
expect(service.selectedCount()).toBe(3);
|
||||
|
||||
service.deselectBook(makeBook(1));
|
||||
service.deselectBook(seriesBook);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('tracks checkbox clicks with and without shift selection', () => {
|
||||
const books = [makeBook(1), makeBook(2), makeBook(3), makeBook(4)];
|
||||
service.setCurrentBooks(books);
|
||||
|
||||
service.handleCheckboxClick({index: 1, book: books[1], selected: true, shiftKey: false});
|
||||
expect(service.selectedBooks()).toEqual(new Set([2]));
|
||||
|
||||
service.handleCheckboxClick({index: 3, book: books[3], selected: true, shiftKey: true});
|
||||
expect(service.selectedBooks()).toEqual(new Set([2, 3, 4]));
|
||||
|
||||
service.handleCheckboxClick({index: 3, book: books[3], selected: false, shiftKey: true});
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
});
|
||||
|
||||
it('selects all current books, resets selection, and clones selected ids', () => {
|
||||
expect(() => service.selectAll()).not.toThrow();
|
||||
|
||||
const books = [makeBook(1), makeBook(2)];
|
||||
service.setCurrentBooks(books);
|
||||
service.selectAll();
|
||||
expect(service.selectedBooks()).toEqual(new Set([1, 2]));
|
||||
|
||||
const selectedIds = new Set([4, 5]);
|
||||
service.setSelectedBooks(selectedIds);
|
||||
selectedIds.add(6);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set([4, 5]));
|
||||
|
||||
service.deselectAll();
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around DOM sizing, table selection events,
|
||||
// router-link rendering, and metadata-lock helpers so table interactions can be asserted without
|
||||
// mounting the full PrimeNG virtual-table runtime.
|
||||
describe.skip('BookTableComponent', () => {
|
||||
it('needs browser seams to verify responsive scroll-height updates and virtual scroller resizing', () => {
|
||||
// TODO(seam): Cover setScrollHeight and ngOnChanges after window/document globals are isolated behind deterministic adapters.
|
||||
});
|
||||
|
||||
it('needs table-event seams to verify row selection, bulk selection, and clickable metadata cell generation', () => {
|
||||
// TODO(seam): Cover selection methods and getCellClickableValue after the PrimeNG table event surface is extracted into a stable test harness.
|
||||
});
|
||||
});
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||
|
||||
describe('CoverScalePreferenceService', () => {
|
||||
let service: CoverScalePreferenceService;
|
||||
let localStorageService: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
|
||||
let messageService: { add: ReturnType<typeof vi.fn> };
|
||||
let translocoService: { translate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
localStorageService = {
|
||||
get: vi.fn(),
|
||||
set: vi.fn()
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string, params?: Record<string, unknown>) =>
|
||||
params ? `${key}:${JSON.stringify(params)}` : `t:${key}`
|
||||
)
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the saved scale and derives the card metrics', () => {
|
||||
localStorageService.get.mockReturnValue(1.5);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CoverScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(CoverScalePreferenceService);
|
||||
|
||||
expect(service.scaleFactor()).toBe(1.5);
|
||||
expect(service.currentCardSize()).toEqual({width: 203, height: 330});
|
||||
expect(service.gridColumnMinWidth()).toBe('203px');
|
||||
expect(service.getCardHeight({} as never)).toBe(330);
|
||||
});
|
||||
|
||||
it('falls back to the default scale and skips persistence when unchanged', () => {
|
||||
localStorageService.get.mockReturnValue(null);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CoverScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(CoverScalePreferenceService);
|
||||
|
||||
service.setScale(1.0);
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
expect(messageService.add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('persists updated scale after debounce and reports failures', () => {
|
||||
localStorageService.get.mockReturnValue(1.0);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CoverScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(CoverScalePreferenceService);
|
||||
|
||||
service.setScale(1.2);
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
expect(localStorageService.set).toHaveBeenCalledWith('coverScalePreference', 1.2);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 't:book.coverPref.toast.savedSummary',
|
||||
detail: 'book.coverPref.toast.savedDetail:{"scale":"1.20"}',
|
||||
life: 1500
|
||||
}));
|
||||
|
||||
vi.clearAllMocks();
|
||||
localStorageService.set.mockImplementation(() => {
|
||||
throw new Error('storage unavailable');
|
||||
});
|
||||
|
||||
service.setScale(1.3);
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 't:book.coverPref.toast.saveFailedSummary',
|
||||
detail: 't:book.coverPref.toast.saveFailedDetail',
|
||||
life: 3000
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {FilterLabelHelper} from './filter-label.helper';
|
||||
|
||||
describe('FilterLabelHelper', () => {
|
||||
it('returns friendly names for known filter types and capitalizes unknown names', () => {
|
||||
expect(FilterLabelHelper.getFilterTypeName('personalRating')).toBe('Personal Rating');
|
||||
expect(FilterLabelHelper.getFilterTypeName('customFilter')).toBe('CustomFilter');
|
||||
});
|
||||
|
||||
it('maps numeric ids to configured range labels', () => {
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 1)).toBe('1–10 MB');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 3)).toBe('200–400 pages');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 0)).toBe('Outstanding (95–100%)');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('personalRating', 7)).toBe('7');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 5)).toBe('4.5+');
|
||||
});
|
||||
|
||||
it('falls back to the raw value when a numeric id is not recognized', () => {
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 999)).toBe('999');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('tag', 'favorite')).toBe('favorite');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {filterBooksBySearchTerm, normalizeSearchTerm} from './HeaderFilter';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
fileName: `Book ${id}.epub`,
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Title ${id}`,
|
||||
seriesName: `Series ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
categories: [`Category ${id}`],
|
||||
isbn10: `ISBN10-${id}`,
|
||||
isbn13: `ISBN13-${id}`
|
||||
},
|
||||
primaryFile: {id, bookId: id, fileName: `Book ${id}.epub`, bookType: 'EPUB'},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('HeaderFilter', () => {
|
||||
it('normalizes unicode, punctuation, whitespace, and empty input', () => {
|
||||
expect(normalizeSearchTerm('')).toBe('');
|
||||
expect(normalizeSearchTerm(' Ætna øresund! ')).toBe('aetna oresund');
|
||||
expect(normalizeSearchTerm('Łódź / Straße')).toBe('lodz strasse');
|
||||
});
|
||||
|
||||
it('keeps the full book list for short terms and filters by searchable fields', () => {
|
||||
const books = [
|
||||
makeBook(1),
|
||||
makeBook(2, {
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'The Other Title',
|
||||
seriesName: 'Other Series',
|
||||
authors: ['Different Author'],
|
||||
categories: ['Biography'],
|
||||
isbn10: '999',
|
||||
isbn13: '888'
|
||||
},
|
||||
primaryFile: {id: 2, bookId: 2, fileName: 'Notes.txt', bookType: 'EPUB'}
|
||||
}),
|
||||
makeBook(3, {
|
||||
metadata: {
|
||||
bookId: 3,
|
||||
title: 'Completely Different',
|
||||
seriesName: 'Third Series',
|
||||
authors: ['Series Match'],
|
||||
categories: ['History'],
|
||||
isbn10: '111',
|
||||
isbn13: '222'
|
||||
},
|
||||
primaryFile: {id: 3, bookId: 3, fileName: 'Search Target.epub', bookType: 'EPUB'}
|
||||
})
|
||||
];
|
||||
|
||||
expect(filterBooksBySearchTerm(books, '')).toBe(books);
|
||||
expect(filterBooksBySearchTerm(books, 'a')).toBe(books);
|
||||
|
||||
expect(filterBooksBySearchTerm(books, 'other title').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, 'other series').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, 'series match').map(book => book.id)).toEqual([3]);
|
||||
expect(filterBooksBySearchTerm(books, 'biography').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, '222').map(book => book.id)).toEqual([3]);
|
||||
expect(filterBooksBySearchTerm(books, 'search target').map(book => book.id)).toEqual([3]);
|
||||
});
|
||||
});
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
import {SeriesCollapseFilter} from './SeriesCollapseFilter';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {Book} from '../../../model/book.model';
|
||||
|
||||
function makeBook(id: number, seriesName?: string, seriesNumber?: number): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
seriesName,
|
||||
seriesNumber
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('SeriesCollapseFilter', () => {
|
||||
let userService: {currentUser: ReturnType<typeof vi.fn>; getCurrentUser: ReturnType<typeof vi.fn>; updateUserSetting: ReturnType<typeof vi.fn>};
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let service: SeriesCollapseFilter;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({id: 1})),
|
||||
getCurrentUser: vi.fn(() => null),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
messageService = {add: vi.fn()};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SeriesCollapseFilter,
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: MessageService, useValue: messageService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(SeriesCollapseFilter);
|
||||
});
|
||||
|
||||
it('returns books unchanged when collapse is disabled or series expansion is forced', () => {
|
||||
const books = [makeBook(1), makeBook(2, 'Series', 2)];
|
||||
|
||||
expect(service.collapseBooks(books, false, false)).toBe(books);
|
||||
expect(service.collapseBooks([], false, true)).toEqual([]);
|
||||
expect(service.collapseBooks(books, true, true)).toBe(books);
|
||||
});
|
||||
|
||||
it('collapses series into grouped books with the lowest numbered entry first', () => {
|
||||
const books = [
|
||||
makeBook(1, 'Series', 2),
|
||||
makeBook(2, 'Series', 1),
|
||||
makeBook(3),
|
||||
makeBook(4, 'Other Series', 5)
|
||||
];
|
||||
|
||||
const collapsed = service.collapseBooks(books, false, true);
|
||||
|
||||
expect(collapsed).toEqual([
|
||||
makeBook(3),
|
||||
{
|
||||
...makeBook(2, 'Series', 1),
|
||||
seriesBooks: [books[0], books[1]],
|
||||
seriesCount: 2
|
||||
},
|
||||
{
|
||||
...makeBook(4, 'Other Series', 5),
|
||||
seriesBooks: [books[3]],
|
||||
seriesCount: 1
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
it('persists context-aware and global preferences with legacy fallbacks', () => {
|
||||
const user = {
|
||||
id: 1,
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1,
|
||||
seriesCollapse: true
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 99,
|
||||
preferences: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'ASC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
userService.getCurrentUser.mockReturnValue(user);
|
||||
|
||||
service.setContext('LIBRARY', 99);
|
||||
expect(service.seriesCollapsed()).toBe(false);
|
||||
|
||||
service.setCollapsed(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({
|
||||
overrides: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 99,
|
||||
preferences: expect.objectContaining({
|
||||
seriesCollapsed: true
|
||||
})
|
||||
})
|
||||
])
|
||||
}));
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved'
|
||||
}));
|
||||
|
||||
userService.updateUserSetting.mockClear();
|
||||
messageService.add.mockClear();
|
||||
|
||||
service.setContext(null, null);
|
||||
service.setCollapsed(false);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({
|
||||
global: expect.objectContaining({
|
||||
seriesCollapsed: false
|
||||
})
|
||||
}));
|
||||
});
|
||||
});
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
||||
import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service';
|
||||
|
||||
describe('SidebarFilterTogglePrefService', () => {
|
||||
let originalInnerWidth: number;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let localStorageService: {
|
||||
get: ReturnType<typeof vi.fn>;
|
||||
set: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
const setViewport = (width: number) => {
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
configurable: true,
|
||||
value: width,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
originalInnerWidth = window.innerWidth;
|
||||
messageService = {add: vi.fn()};
|
||||
localStorageService = {
|
||||
get: vi.fn(() => null),
|
||||
set: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setViewport(originalInnerWidth);
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
const createService = () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SidebarFilterTogglePrefService,
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: TranslocoService, useValue: {translate: (key: string) => key}},
|
||||
],
|
||||
});
|
||||
|
||||
return TestBed.inject(SidebarFilterTogglePrefService);
|
||||
};
|
||||
|
||||
it('loads the stored preference on wide screens', () => {
|
||||
setViewport(1280);
|
||||
localStorageService.get.mockReturnValue(false);
|
||||
|
||||
const service = createService();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.get).toHaveBeenCalledWith('showSidebarFilter');
|
||||
});
|
||||
|
||||
it('forces the filter closed on narrow screens', () => {
|
||||
setViewport(640);
|
||||
|
||||
const service = createService();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('toggles the visibility and persists the updated value', () => {
|
||||
setViewport(1280);
|
||||
const service = createService();
|
||||
|
||||
service.toggle();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.set).toHaveBeenCalledWith('showSidebarFilter', false);
|
||||
});
|
||||
|
||||
it('shows an error toast when persistence fails', () => {
|
||||
setViewport(1280);
|
||||
localStorageService.set.mockImplementation(() => {
|
||||
throw new Error('storage failed');
|
||||
});
|
||||
const service = createService();
|
||||
|
||||
service.setShowFilter(false);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 'book.filterPref.toast.saveFailedSummary',
|
||||
detail: 'book.filterPref.toast.saveFailedDetail',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {
|
||||
doesBookMatchFilter,
|
||||
doesBookMatchReadStatus,
|
||||
filterBooksByFilters,
|
||||
isFileSizeInRange,
|
||||
isMatchScoreInRange,
|
||||
isPageCountInRange,
|
||||
isRatingInRange,
|
||||
isRatingInRange10
|
||||
} from './sidebar-filter';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
readStatus: ReadStatus.UNREAD,
|
||||
fileSizeKb: 1500,
|
||||
metadataMatchScore: 87,
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Title ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
categories: [`Category ${id}`],
|
||||
seriesName: `Series ${id}`,
|
||||
publisher: 'Publisher',
|
||||
publishedDate: '2024-02-01',
|
||||
pageCount: 230,
|
||||
language: 'en',
|
||||
tags: ['tag-a'],
|
||||
moods: ['mood-a'],
|
||||
amazonRating: 4.3,
|
||||
goodreadsRating: 4.1,
|
||||
hardcoverRating: 4.2,
|
||||
narrator: 'Narrator',
|
||||
ageRating: 16,
|
||||
contentRating: 'PG-13',
|
||||
comicMetadata: {
|
||||
characters: ['hero'],
|
||||
teams: ['team-a'],
|
||||
locations: ['earth'],
|
||||
pencillers: ['Penciller'],
|
||||
inkers: ['Inker'],
|
||||
colorists: ['Colorist'],
|
||||
letterers: ['Letterer'],
|
||||
coverArtists: ['Cover'],
|
||||
editors: ['Editor']
|
||||
}
|
||||
},
|
||||
shelves: [{id: 7, name: 'Favorites'}],
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('sidebar-filter', () => {
|
||||
it('covers the numeric helper ranges and read status matching', () => {
|
||||
expect(isRatingInRange(null, 1)).toBe(false);
|
||||
expect(isRatingInRange(4.3, '4')).toBe(true);
|
||||
expect(isRatingInRange10(4.4, 4)).toBe(true);
|
||||
expect(isFileSizeInRange(undefined, 1)).toBe(false);
|
||||
expect(isFileSizeInRange(1500, 1)).toBe(true);
|
||||
expect(isPageCountInRange(230, '3')).toBe(true);
|
||||
expect(isMatchScoreInRange(87, 2)).toBe(true);
|
||||
expect(isMatchScoreInRange(87, 9)).toBe(false);
|
||||
expect(doesBookMatchReadStatus(makeBook(1), [ReadStatus.UNREAD])).toBe(true);
|
||||
expect(doesBookMatchReadStatus(makeBook(1, {readStatus: undefined}), [ReadStatus.UNSET])).toBe(true);
|
||||
});
|
||||
|
||||
it('matches all filter branches across or, and, and not modes', () => {
|
||||
const book = makeBook(1);
|
||||
const books = [book, makeBook(2, {
|
||||
readStatus: ReadStatus.READING,
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Other',
|
||||
authors: ['Other Author'],
|
||||
categories: ['Other Category'],
|
||||
seriesName: 'Other Series',
|
||||
publisher: 'Other Publisher',
|
||||
publishedDate: '2021-01-01',
|
||||
pageCount: 50,
|
||||
language: 'fr',
|
||||
tags: ['other-tag'],
|
||||
moods: ['other-mood'],
|
||||
amazonRating: 3.1,
|
||||
goodreadsRating: 3.2,
|
||||
hardcoverRating: 3.3,
|
||||
narrator: 'Someone Else',
|
||||
ageRating: 12,
|
||||
contentRating: 'R',
|
||||
comicMetadata: {
|
||||
characters: ['villain'],
|
||||
teams: ['team-b'],
|
||||
locations: ['mars'],
|
||||
pencillers: ['Alt Penciller'],
|
||||
inkers: ['Alt Inker'],
|
||||
colorists: ['Alt Colorist'],
|
||||
letterers: ['Alt Letterer'],
|
||||
coverArtists: ['Alt Cover'],
|
||||
editors: ['Alt Editor']
|
||||
}
|
||||
},
|
||||
shelves: []
|
||||
})];
|
||||
|
||||
expect(doesBookMatchFilter(book, 'author', ['Author 1'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'category', ['Category 1'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'series', ['Series 1'], 'not')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'bookType', ['PHYSICAL'], 'or')).toBe(false);
|
||||
expect(doesBookMatchFilter(book, 'readStatus', [ReadStatus.UNREAD], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'publisher', ['Publisher'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'matchScore', [2], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'library', [1], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'shelf', [7], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'shelfStatus', ['shelved'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(makeBook(3, {shelves: []}), 'shelfStatus', ['unshelved'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'tag', ['tag-a'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'publishedDate', ['2024'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'fileSize', [1], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'amazonRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'goodreadsRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'hardcoverRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'language', ['en'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'pageCount', [3], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'mood', ['mood-a'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'ageRating', ['16'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'contentRating', ['PG-13'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'narrator', ['Narrator'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicCharacter', ['hero'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicTeam', ['team-a'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicLocation', ['earth'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicCreator', ['Penciller:penciller'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'unknown', ['x'], 'or')).toBe(false);
|
||||
|
||||
expect(doesBookMatchFilter(makeBook(4, {isPhysical: true}), 'bookType', ['PHYSICAL'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'author', [], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'author', [], 'and')).toBe(false);
|
||||
|
||||
expect(filterBooksByFilters(books, null, 'or')).toBe(books);
|
||||
expect(filterBooksByFilters(books, {author: ['Author 1']}, 'or')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Other Author']}, 'not')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Author 1'], category: ['Category 1']}, 'and')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Other Author'], category: ['Category 1']}, 'or', 'author')).toEqual([book]);
|
||||
});
|
||||
});
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LoadingService} from '../../../../../core/services/loading.service';
|
||||
import {
|
||||
createDynamicDialogHarness,
|
||||
createMessageServiceProvider,
|
||||
createMessageServiceSpy,
|
||||
} from '../../../../../core/testing/dialog-testing';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog.component';
|
||||
|
||||
describe('LockUnlockMetadataDialogComponent', () => {
|
||||
let toggleFieldLocks: ReturnType<typeof vi.fn>;
|
||||
let dialogHarness: ReturnType<typeof createDynamicDialogHarness<{bookIds: Set<number>}>>;
|
||||
let messageService: ReturnType<typeof createMessageServiceSpy>;
|
||||
let loadingService: {
|
||||
show: ReturnType<typeof vi.fn>;
|
||||
hide: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translate: TranslocoService['translate'];
|
||||
|
||||
beforeEach(() => {
|
||||
toggleFieldLocks = vi.fn(() => of(void 0));
|
||||
dialogHarness = createDynamicDialogHarness({bookIds: new Set([7, 9])});
|
||||
messageService = createMessageServiceSpy();
|
||||
loadingService = {
|
||||
show: vi.fn(() => 'loader-token'),
|
||||
hide: vi.fn(),
|
||||
};
|
||||
translate = (<T = string>(key: string) => `translated:${key}` as T) as TranslocoService['translate'];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createComponent() {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...dialogHarness.providers,
|
||||
{
|
||||
provide: BookMetadataManageService,
|
||||
useValue: {
|
||||
toggleFieldLocks,
|
||||
},
|
||||
},
|
||||
createMessageServiceProvider(messageService),
|
||||
{
|
||||
provide: LoadingService,
|
||||
useValue: loadingService,
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new LockUnlockMetadataDialogComponent());
|
||||
component.ngOnInit();
|
||||
return component;
|
||||
}
|
||||
|
||||
it('toggles every lockable field between locked and unlocked states', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.toggleLockAll('LOCK');
|
||||
expect(component.lockableFields.every(field => component.fieldLocks[field] === true)).toBe(true);
|
||||
|
||||
component.toggleLockAll('UNLOCK');
|
||||
expect(component.lockableFields.every(field => component.fieldLocks[field] === false)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns translated labels and icons for unselected, locked, and unlocked states', () => {
|
||||
const component = createComponent();
|
||||
|
||||
expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.unselected');
|
||||
expect(component.getLockIcon('titleLocked')).toBe('');
|
||||
|
||||
component.fieldLocks['titleLocked'] = true;
|
||||
expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.locked');
|
||||
expect(component.getLockIcon('titleLocked')).toBe('pi pi-lock');
|
||||
|
||||
component.fieldLocks['titleLocked'] = false;
|
||||
expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.unlocked');
|
||||
expect(component.getLockIcon('titleLocked')).toBe('pi pi-lock-open');
|
||||
});
|
||||
|
||||
it('resets every field lock back to an unselected state', () => {
|
||||
const component = createComponent();
|
||||
component.toggleLockAll('LOCK');
|
||||
|
||||
component.resetFieldLocks();
|
||||
|
||||
expect(component.lockableFields.every(field => component.fieldLocks[field] === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it('cycles a field through locked, unlocked, and cleared states', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.cycleLockState('titleLocked');
|
||||
expect(component.fieldLocks['titleLocked']).toBe(true);
|
||||
|
||||
component.cycleLockState('titleLocked');
|
||||
expect(component.fieldLocks['titleLocked']).toBe(false);
|
||||
|
||||
component.cycleLockState('titleLocked');
|
||||
expect(component.fieldLocks['titleLocked']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('applies selected field locks, shows a success toast, and closes the dialog', () => {
|
||||
const component = createComponent();
|
||||
component.fieldLocks['titleLocked'] = true;
|
||||
component.fieldLocks['authorsLocked'] = false;
|
||||
component.fieldLocks['subtitleLocked'] = undefined;
|
||||
|
||||
component.applyFieldLocks();
|
||||
|
||||
expect(toggleFieldLocks).toHaveBeenCalledWith(new Set([7, 9]), {
|
||||
titleLocked: 'LOCK',
|
||||
authorsLocked: 'UNLOCK',
|
||||
});
|
||||
expect(loadingService.show).toHaveBeenCalledWith(
|
||||
'translated:book.lockUnlockDialog.toast.updatingFieldLocks'
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-token');
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:book.lockUnlockDialog.toast.updatedSummary',
|
||||
detail: 'translated:book.lockUnlockDialog.toast.updatedDetail',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith('fields-updated');
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when saving fails', () => {
|
||||
toggleFieldLocks.mockReturnValueOnce(throwError(() => new Error('save failed')));
|
||||
const component = createComponent();
|
||||
component.fieldLocks['titleLocked'] = false;
|
||||
|
||||
component.applyFieldLocks();
|
||||
|
||||
expect(toggleFieldLocks).toHaveBeenCalledWith(new Set([7, 9]), {
|
||||
titleLocked: 'UNLOCK',
|
||||
});
|
||||
expect(loadingService.show).toHaveBeenCalledWith(
|
||||
'translated:book.lockUnlockDialog.toast.updatingFieldLocks'
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-token');
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:book.lockUnlockDialog.toast.failedSummary',
|
||||
detail: 'translated:book.lockUnlockDialog.toast.failedDetail',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {CdkDragDrop} from '@angular/cdk/drag-drop';
|
||||
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
import {BookSorter} from './BookSorter';
|
||||
|
||||
describe('BookSorter', () => {
|
||||
it('uses default labels when no transloco service is provided', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
|
||||
expect(sorter.sortOptions[0]).toMatchObject({
|
||||
field: 'title',
|
||||
label: 'Title',
|
||||
direction: SortDirection.ASCENDING
|
||||
});
|
||||
});
|
||||
|
||||
it('uses translated labels when transloco is available', () => {
|
||||
const transloco = {
|
||||
translate: vi.fn((key: string) => `translated:${key}`)
|
||||
} as unknown as TranslocoService;
|
||||
|
||||
const sorter = new BookSorter(() => undefined, transloco);
|
||||
|
||||
expect(sorter.sortOptions[0].label).toBe('translated:book.sorting.options.title');
|
||||
});
|
||||
|
||||
it('supports legacy selectedSort getter and setter', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
const sort: SortOption = {label: 'Title', field: 'title', direction: SortDirection.ASCENDING};
|
||||
|
||||
sorter.selectedSort = sort;
|
||||
expect(sorter.selectedSort).toEqual(sort);
|
||||
|
||||
sorter.selectedSort = undefined;
|
||||
expect(sorter.selectedSortCriteria).toEqual([]);
|
||||
});
|
||||
|
||||
it('sorts by a field and toggles the primary direction on repeat', () => {
|
||||
const onSortChange = vi.fn();
|
||||
const sorter = new BookSorter(onSortChange);
|
||||
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.selectedSortCriteria).toEqual([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING}
|
||||
]);
|
||||
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.selectedSortCriteria[0].direction).toBe(SortDirection.DESCENDING);
|
||||
expect(onSortChange).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('adds, removes, toggles, and reorders criteria', () => {
|
||||
const onSortChange = vi.fn();
|
||||
const sorter = new BookSorter(onSortChange);
|
||||
|
||||
sorter.addSortCriterion('title');
|
||||
sorter.addSortCriterion('author');
|
||||
sorter.addSortCriterion('title');
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title', 'author']);
|
||||
|
||||
sorter.toggleCriterionDirection(1);
|
||||
expect(sorter.selectedSortCriteria[1].direction).toBe(SortDirection.DESCENDING);
|
||||
|
||||
sorter.reorderCriteria({
|
||||
previousIndex: 1,
|
||||
currentIndex: 0
|
||||
} as unknown as CdkDragDrop<SortOption[]>);
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['author', 'title']);
|
||||
|
||||
sorter.removeSortCriterion(0);
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title']);
|
||||
});
|
||||
|
||||
it('omits already-used fields from available options and marks the primary icon', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
|
||||
sorter.setSortCriteria([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING}
|
||||
]);
|
||||
|
||||
const titleOption = sorter.sortOptions.find((option) => option.field === 'title') as SortOption & {icon?: string};
|
||||
|
||||
expect(sorter.getAvailableSortOptions().some((option) => option.field === 'title')).toBe(false);
|
||||
expect(titleOption.icon).toBe('pi pi-arrow-up');
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This popover needs a PrimeNG overlay and drag-drop harness so the
|
||||
// multi-sort reorder and apply flows can be tested against real emitted events.
|
||||
describe.skip('MultiSortPopoverComponent', () => {
|
||||
it('needs an overlay harness for drag-drop reorder and sort application flows', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('TableColumnPreferenceService', () => {
|
||||
let service: TableColumnPreferenceService;
|
||||
let userService: { getCurrentUser: ReturnType<typeof vi.fn>; updateUserSetting: ReturnType<typeof vi.fn> };
|
||||
let messageService: { add: ReturnType<typeof vi.fn> };
|
||||
let translocoService: { translate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
userService = {
|
||||
getCurrentUser: vi.fn(),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string) => `t:${key}`)
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TableColumnPreferenceService,
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(TableColumnPreferenceService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('merges saved preferences with all available columns', () => {
|
||||
const savedPrefs: TableColumnPreference[] = [
|
||||
{field: 'title', visible: false, order: 4},
|
||||
{field: 'authors', visible: true, order: 1},
|
||||
{field: 'fileName', visible: true, order: 0}
|
||||
];
|
||||
|
||||
service.initPreferences(savedPrefs);
|
||||
|
||||
expect(service.preferences().find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: false,
|
||||
order: 4
|
||||
});
|
||||
expect(service.preferences().find(pref => pref.field === 'authors')).toEqual({
|
||||
field: 'authors',
|
||||
visible: true,
|
||||
order: 1
|
||||
});
|
||||
expect(service.allColumns[0]).toEqual({
|
||||
field: 'readStatus',
|
||||
header: 't:book.columnPref.columns.readStatus'
|
||||
});
|
||||
expect(service.visibleColumns.map(column => column.field).slice(0, 2)).toEqual(['readStatus', 'fileName']);
|
||||
});
|
||||
|
||||
it('falls back to defaults when no saved preferences exist', () => {
|
||||
service.initPreferences(undefined);
|
||||
|
||||
expect(service.preferences().length).toBe(service.allColumns.length);
|
||||
expect(service.visibleColumns[0]).toEqual({
|
||||
field: 'readStatus',
|
||||
header: 't:book.columnPref.columns.readStatus'
|
||||
});
|
||||
});
|
||||
|
||||
it('skips persistence when there is no current user', () => {
|
||||
userService.getCurrentUser.mockReturnValue(null);
|
||||
|
||||
service.saveVisibleColumns([{field: 'title'}]);
|
||||
|
||||
expect(userService.updateUserSetting).not.toHaveBeenCalled();
|
||||
expect(messageService.add).not.toHaveBeenCalled();
|
||||
expect(service.preferences().find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: true,
|
||||
order: 0
|
||||
});
|
||||
});
|
||||
|
||||
it('saves preferences and shows a success toast for the current user', () => {
|
||||
userService.getCurrentUser.mockReturnValue({id: 42});
|
||||
|
||||
service.saveVisibleColumns([{field: 'title'}, {field: 'authors'}]);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', expect.any(Array));
|
||||
const savedPrefs = userService.updateUserSetting.mock.calls[0][2] as TableColumnPreference[];
|
||||
expect(savedPrefs.find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: true,
|
||||
order: 0
|
||||
});
|
||||
expect(savedPrefs.find(pref => pref.field === 'authors')).toEqual({
|
||||
field: 'authors',
|
||||
visible: true,
|
||||
order: 1
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 't:book.columnPref.toast.savedSummary',
|
||||
detail: 't:book.columnPref.toast.savedDetail',
|
||||
life: 1500
|
||||
}));
|
||||
});
|
||||
});
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {BookCardLiteComponent} from './book-card-lite-component';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('BookCardLiteComponent', () => {
|
||||
let fixture: ComponentFixture<BookCardLiteComponent>;
|
||||
let component: BookCardLiteComponent;
|
||||
let router: {navigate: ReturnType<typeof vi.fn>};
|
||||
let urlHelper: {
|
||||
getThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {currentUser: ReturnType<typeof vi.fn>};
|
||||
let hostService: {requestBookSwitch: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
router = {navigate: vi.fn()};
|
||||
urlHelper = {
|
||||
getThumbnailUrl: vi.fn(() => '/covers/1'),
|
||||
getAudiobookThumbnailUrl: vi.fn(() => '/covers/audio/1'),
|
||||
};
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({userSettings: {metadataCenterViewMode: 'route'}})),
|
||||
};
|
||||
hostService = {
|
||||
requestBookSwitch: vi.fn(),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [BookCardLiteComponent],
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UrlHelperService, useValue: urlHelper},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: BookMetadataHostService, useValue: hostService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(BookCardLiteComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('treats a book as audiobook-only when no non-audiobook alternative format exists', () => {
|
||||
component.book = buildBook({
|
||||
primaryFile: {id: 10, bookId: 1, bookType: 'AUDIOBOOK'},
|
||||
alternativeFormats: [{id: 11, bookId: 1, bookType: 'AUDIOBOOK'}],
|
||||
});
|
||||
|
||||
expect(component.isAudiobookOnly()).toBe(true);
|
||||
expect(component.getThumbnailUrl()).toBe('/covers/audio/1');
|
||||
expect(urlHelper.getAudiobookThumbnailUrl).toHaveBeenCalledWith(1, '2026-01-02');
|
||||
});
|
||||
|
||||
it('uses the standard thumbnail when the book has an ebook format available', () => {
|
||||
component.book = buildBook({
|
||||
primaryFile: {id: 10, bookId: 1, bookType: 'AUDIOBOOK'},
|
||||
alternativeFormats: [{id: 11, bookId: 1, bookType: 'EPUB'}],
|
||||
});
|
||||
|
||||
expect(component.isAudiobookOnly()).toBe(false);
|
||||
expect(component.getThumbnailUrl()).toBe('/covers/1');
|
||||
expect(urlHelper.getThumbnailUrl).toHaveBeenCalledWith(1, '2026-01-01');
|
||||
});
|
||||
|
||||
it('navigates to the route-based metadata center when that mode is active', () => {
|
||||
const book = buildBook();
|
||||
|
||||
component.openBookInfo(book);
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/book', 1], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
expect(hostService.requestBookSwitch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('delegates to the metadata host when the user prefers dialog mode', () => {
|
||||
userService.currentUser.mockReturnValue({userSettings: {metadataCenterViewMode: 'dialog'}});
|
||||
const book = buildBook();
|
||||
|
||||
component.openBookInfo(book);
|
||||
|
||||
expect(hostService.requestBookSwitch).toHaveBeenCalledWith(1);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
function buildBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 1,
|
||||
fileName: 'Example Book',
|
||||
metadata: {
|
||||
title: 'Example Book',
|
||||
coverUpdatedOn: '2026-01-01',
|
||||
audiobookCoverUpdatedOn: '2026-01-02',
|
||||
...overrides.metadata,
|
||||
},
|
||||
primaryFile: {
|
||||
id: 10,
|
||||
bookType: 'EPUB',
|
||||
...overrides.primaryFile,
|
||||
},
|
||||
alternativeFormats: overrides.alternativeFormats ?? [],
|
||||
...overrides,
|
||||
} as Book;
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {BookFileService} from '../../service/book-file.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookFileAttacherComponent} from './book-file-attacher.component';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
|
||||
interface DialogData {
|
||||
sourceBook?: Book;
|
||||
sourceBooks?: Book[];
|
||||
}
|
||||
|
||||
type AppSettingsLike = {
|
||||
metadataPersistenceSettings?: {
|
||||
moveFilesToLibraryPattern?: boolean;
|
||||
};
|
||||
} | null;
|
||||
|
||||
function buildBook(overrides: Partial<Book> = {}): Book {
|
||||
const id = overrides.id ?? 1;
|
||||
return {
|
||||
id,
|
||||
libraryId: overrides.libraryId ?? 10,
|
||||
libraryName: overrides.libraryName ?? 'Main Library',
|
||||
metadata: overrides.metadata ?? {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
},
|
||||
primaryFile: overrides.primaryFile,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function setup(options: {
|
||||
dialogData?: DialogData;
|
||||
books?: Book[];
|
||||
appSettings?: AppSettingsLike;
|
||||
attachResult?: Observable<{updatedBook: Book; deletedSourceBookIds: number[]}>;
|
||||
} = {}) {
|
||||
const dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
const config = {
|
||||
data: options.dialogData ?? {},
|
||||
};
|
||||
const booksSignal = signal<Book[]>(options.books ?? []);
|
||||
const bookFileService = {
|
||||
attachBookFiles: vi.fn().mockReturnValue(
|
||||
options.attachResult ?? of({updatedBook: buildBook({id: 999}), deletedSourceBookIds: []})
|
||||
),
|
||||
};
|
||||
const appSettingsService = {
|
||||
appSettings: vi.fn(() => options.appSettings ?? null),
|
||||
};
|
||||
const translocoService = {
|
||||
translate: vi.fn((key: string) => key),
|
||||
};
|
||||
const messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: DynamicDialogConfig, useValue: config},
|
||||
{provide: BookService, useValue: {books: booksSignal}},
|
||||
{provide: BookFileService, useValue: bookFileService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new BookFileAttacherComponent());
|
||||
|
||||
return {
|
||||
component,
|
||||
dialogRef,
|
||||
bookFileService,
|
||||
appSettingsService,
|
||||
translocoService,
|
||||
booksSignal,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookFileAttacherComponent', () => {
|
||||
it('bootstraps a single source book, filters candidates by library/source ids, and applies the moveFiles setting', () => {
|
||||
const sourceBook = buildBook({id: 1, libraryId: 7, metadata: {bookId: 1, title: 'Source', authors: ['Origin']}});
|
||||
const siblingCandidate = buildBook({id: 2, libraryId: 7, metadata: {bookId: 2, title: 'Sibling', authors: ['Match']}});
|
||||
const foreignLibraryBook = buildBook({id: 3, libraryId: 99, metadata: {bookId: 3, title: 'Foreign', authors: ['Other']}});
|
||||
const {component} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, siblingCandidate, foreignLibraryBook],
|
||||
appSettings: {
|
||||
metadataPersistenceSettings: {
|
||||
moveFilesToLibraryPattern: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.sourceBooks).toEqual([sourceBook]);
|
||||
expect(component.isBulkMode).toBe(false);
|
||||
expect(component.moveFiles).toBe(true);
|
||||
expect(component.filteredBooks).toEqual([siblingCandidate]);
|
||||
});
|
||||
|
||||
it('bootstraps bulk mode from sourceBooks and defaults moveFiles to false when settings are unavailable', () => {
|
||||
const sourceA = buildBook({id: 10, libraryId: 4});
|
||||
const sourceB = buildBook({id: 11, libraryId: 4});
|
||||
const target = buildBook({id: 12, libraryId: 4});
|
||||
const {component} = setup({
|
||||
dialogData: {sourceBooks: [sourceA, sourceB]},
|
||||
books: [sourceA, sourceB, target],
|
||||
appSettings: null,
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.sourceBooks).toEqual([sourceA, sourceB]);
|
||||
expect(component.isBulkMode).toBe(true);
|
||||
expect(component.moveFiles).toBe(false);
|
||||
expect(component.filteredBooks).toEqual([target]);
|
||||
});
|
||||
|
||||
it('closes immediately when no source payload is provided', () => {
|
||||
const {component, dialogRef, appSettingsService} = setup({
|
||||
dialogData: {},
|
||||
books: [buildBook({id: 20})],
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
expect(dialogRef.close).toHaveBeenCalledWith();
|
||||
expect(appSettingsService.appSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters candidate books by title and author and resets blank queries to the first twenty matches', () => {
|
||||
const sourceBook = buildBook({id: 1, libraryId: 5, metadata: {bookId: 1, title: 'Source', authors: ['Keeper']}});
|
||||
const matchingByTitle = buildBook({id: 2, libraryId: 5, metadata: {bookId: 2, title: 'Dune Messiah', authors: ['Frank Herbert']}});
|
||||
const matchingByAuthor = buildBook({id: 3, libraryId: 5, metadata: {bookId: 3, title: 'Fahrenheit 451', authors: ['Ray Bradbury']}});
|
||||
const fillerBooks = Array.from({length: 25}, (_, index) =>
|
||||
buildBook({
|
||||
id: index + 10,
|
||||
libraryId: 5,
|
||||
metadata: {bookId: index + 10, title: `Candidate ${index}`, authors: [`Writer ${index}`]},
|
||||
})
|
||||
);
|
||||
const {component} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, matchingByTitle, matchingByAuthor, ...fillerBooks],
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.filteredBooks).toHaveLength(20);
|
||||
|
||||
component.filterBooks({query: ' dune '});
|
||||
expect(component.filteredBooks).toEqual([matchingByTitle]);
|
||||
|
||||
component.filterBooks({query: 'bradbury'});
|
||||
expect(component.filteredBooks).toEqual([matchingByAuthor]);
|
||||
|
||||
component.filterBooks({query: ' '});
|
||||
expect(component.filteredBooks).toHaveLength(20);
|
||||
expect(component.filteredBooks[0]).toEqual(matchingByTitle);
|
||||
});
|
||||
|
||||
it('handles lightweight selection events and formats display helpers with fallbacks', () => {
|
||||
const selectedBook = buildBook({
|
||||
id: 30,
|
||||
metadata: {bookId: 30, title: 'The Left Hand of Darkness', authors: ['Ursula K. Le Guin', 'Guest Author']},
|
||||
primaryFile: {id: 301, bookId: 30, extension: 'epub', fileName: 'left-hand.epub'},
|
||||
});
|
||||
const untitledBook = buildBook({id: 31, metadata: undefined, primaryFile: undefined});
|
||||
const {component, translocoService} = setup();
|
||||
|
||||
component.onBookSelect({value: selectedBook} as never);
|
||||
expect(component.targetBook).toEqual(selectedBook);
|
||||
|
||||
component.onBookClear();
|
||||
expect(component.targetBook).toBeNull();
|
||||
|
||||
expect(component.getBookDisplayName(selectedBook)).toBe('The Left Hand of Darkness - Ursula K. Le Guin, Guest Author');
|
||||
expect(component.getBookDisplayName(untitledBook)).toBe('Book #31');
|
||||
expect(component.getSourceFileInfo(selectedBook)).toBe('EPUB - left-hand.epub');
|
||||
expect(component.getSourceFileInfo(untitledBook)).toBe('book.fileAttacher.unknownFile');
|
||||
expect(translocoService.translate).toHaveBeenCalledWith('book.fileAttacher.unknownFile');
|
||||
});
|
||||
|
||||
it('uses the target selection and defaulted moveFiles value when attach succeeds', () => {
|
||||
const sourceBook = buildBook({id: 40, libraryId: 8});
|
||||
const targetBook = buildBook({id: 41, libraryId: 8});
|
||||
const {component, bookFileService, dialogRef} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, targetBook],
|
||||
appSettings: null,
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
component.targetBook = targetBook;
|
||||
|
||||
component.attach();
|
||||
|
||||
expect(bookFileService.attachBookFiles).toHaveBeenCalledWith(41, [40], false);
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({success: true});
|
||||
});
|
||||
|
||||
it('resets attaching state when attach fails and preserves the dialog', () => {
|
||||
const sourceBook = buildBook({id: 50, libraryId: 9});
|
||||
const targetBook = buildBook({id: 51, libraryId: 9});
|
||||
const {component, bookFileService, dialogRef} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, targetBook],
|
||||
appSettings: {
|
||||
metadataPersistenceSettings: {
|
||||
moveFilesToLibraryPattern: true,
|
||||
},
|
||||
},
|
||||
attachResult: throwError(() => new Error('attach failed')),
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
component.targetBook = targetBook;
|
||||
|
||||
component.attach();
|
||||
|
||||
expect(bookFileService.attachBookFiles).toHaveBeenCalledWith(51, [50], true);
|
||||
expect(component.isAttaching).toBe(false);
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not attach without a target book and exposes direct close behavior', () => {
|
||||
const sourceBook = buildBook({id: 60});
|
||||
const {component, bookFileService, dialogRef} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook],
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
component.attach();
|
||||
component.closeDialog();
|
||||
|
||||
expect(component.canAttach()).toBe(false);
|
||||
expect(bookFileService.attachBookFiles).not.toHaveBeenCalled();
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
expect(dialogRef.close).toHaveBeenCalledWith();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {BookNote, BookNoteService} from '../../../../shared/service/book-note.service';
|
||||
import {BookNotesComponent} from './book-notes-component';
|
||||
|
||||
interface ConfirmationLike {
|
||||
key?: string;
|
||||
message?: string;
|
||||
header?: string;
|
||||
accept?: () => void;
|
||||
}
|
||||
|
||||
function createNote(id: number, overrides: Partial<BookNote> = {}): BookNote {
|
||||
return {
|
||||
id,
|
||||
userId: 7,
|
||||
bookId: 42,
|
||||
title: `Note ${id}`,
|
||||
content: `Content ${id}`,
|
||||
createdAt: '2026-03-28T09:00:00.000Z',
|
||||
updatedAt: `2026-03-28T09:0${id}:00.000Z`,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookNotesComponent', () => {
|
||||
let component: BookNotesComponent;
|
||||
let bookNoteService: {
|
||||
getNotesForBook: ReturnType<typeof vi.fn>;
|
||||
createOrUpdateNote: ReturnType<typeof vi.fn>;
|
||||
deleteNote: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let messageService: {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let confirmationService: {
|
||||
confirm: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let lastConfirmation: ConfirmationLike | null;
|
||||
|
||||
function createComponent(): BookNotesComponent {
|
||||
return TestBed.runInInjectionContext(() => new BookNotesComponent());
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
lastConfirmation = null;
|
||||
bookNoteService = {
|
||||
getNotesForBook: vi.fn(),
|
||||
createOrUpdateNote: vi.fn(),
|
||||
deleteNote: vi.fn(),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
confirmationService = {
|
||||
confirm: vi.fn((confirmation: ConfirmationLike) => {
|
||||
lastConfirmation = confirmation;
|
||||
}),
|
||||
};
|
||||
translate = vi.fn((key: string, params?: Record<string, unknown>) => (
|
||||
params ? `${key}:${JSON.stringify(params)}` : key
|
||||
));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: BookNoteService, useValue: bookNoteService},
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
component = createComponent();
|
||||
component.bookId = 42;
|
||||
});
|
||||
|
||||
it('skips loading notes when no book is selected', () => {
|
||||
component.bookId = 0;
|
||||
|
||||
component.loadNotes();
|
||||
|
||||
expect(bookNoteService.getNotesForBook).not.toHaveBeenCalled();
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('loads notes and orders them by most recent update first', () => {
|
||||
const oldest = createNote(1, {updatedAt: '2026-03-28T08:00:00.000Z'});
|
||||
const newest = createNote(2, {updatedAt: '2026-03-28T12:00:00.000Z'});
|
||||
const middle = createNote(3, {updatedAt: '2026-03-28T10:00:00.000Z'});
|
||||
bookNoteService.getNotesForBook.mockReturnValue(of([oldest, newest, middle]));
|
||||
|
||||
component.loadNotes();
|
||||
|
||||
expect(bookNoteService.getNotesForBook).toHaveBeenCalledWith(42);
|
||||
expect(component.notes.map(note => note.id)).toEqual([2, 3, 1]);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('shows an error toast when loading notes fails', () => {
|
||||
bookNoteService.getNotesForBook.mockReturnValue(throwError(() => new Error('load failed')));
|
||||
|
||||
component.loadNotes();
|
||||
|
||||
expect(component.loading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.loadFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('blocks note creation when title or content is blank after trimming', () => {
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: ' ',
|
||||
content: ' ',
|
||||
};
|
||||
|
||||
component.createNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'book.notes.toast.validationSummary',
|
||||
detail: 'book.notes.toast.validationDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a note and closes the create dialog on success', () => {
|
||||
const createdNote = createNote(9, {title: 'Created', content: 'Fresh content'});
|
||||
component.notes = [createNote(1)];
|
||||
component.showCreateDialog = true;
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: 'Created',
|
||||
content: 'Fresh content',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(of(createdNote));
|
||||
|
||||
component.createNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).toHaveBeenCalledWith(component.newNote);
|
||||
expect(component.notes[0]).toEqual(createdNote);
|
||||
expect(component.showCreateDialog).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'common.success',
|
||||
detail: 'book.notes.toast.createSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when note creation fails', () => {
|
||||
component.showCreateDialog = true;
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: 'Created',
|
||||
content: 'Fresh content',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(throwError(() => new Error('create failed')));
|
||||
|
||||
component.createNote();
|
||||
|
||||
expect(component.showCreateDialog).toBe(true);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.createFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('blocks note updates when title or content is blank after trimming', () => {
|
||||
component.editNote = {
|
||||
id: 4,
|
||||
bookId: 42,
|
||||
title: ' ',
|
||||
content: ' ',
|
||||
};
|
||||
|
||||
component.updateNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'book.notes.toast.validationSummary',
|
||||
detail: 'book.notes.toast.validationDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('updates an existing note, resorts the list, and clears edit state on success', () => {
|
||||
const staleNote = createNote(1, {updatedAt: '2026-03-28T08:00:00.000Z', title: 'Old title'});
|
||||
const selectedNote = createNote(2, {updatedAt: '2026-03-28T10:00:00.000Z', title: 'Before edit'});
|
||||
const updatedNote = createNote(2, {
|
||||
updatedAt: '2026-03-28T14:00:00.000Z',
|
||||
title: 'After edit',
|
||||
content: 'Updated body',
|
||||
});
|
||||
component.notes = [staleNote, selectedNote];
|
||||
component.selectedNote = selectedNote;
|
||||
component.showEditDialog = true;
|
||||
component.editNote = {
|
||||
id: 2,
|
||||
bookId: 42,
|
||||
title: 'After edit',
|
||||
content: 'Updated body',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(of(updatedNote));
|
||||
|
||||
component.updateNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).toHaveBeenCalledWith(component.editNote);
|
||||
expect(component.notes.map(note => note.id)).toEqual([2, 1]);
|
||||
expect(component.notes[0]).toEqual(updatedNote);
|
||||
expect(component.showEditDialog).toBe(false);
|
||||
expect(component.selectedNote).toBeNull();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'common.success',
|
||||
detail: 'book.notes.toast.updateSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when updating a note fails', () => {
|
||||
const selectedNote = createNote(2, {title: 'Before edit'});
|
||||
component.selectedNote = selectedNote;
|
||||
component.showEditDialog = true;
|
||||
component.editNote = {
|
||||
id: 2,
|
||||
bookId: 42,
|
||||
title: 'After edit',
|
||||
content: 'Updated body',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(throwError(() => new Error('update failed')));
|
||||
|
||||
component.updateNote();
|
||||
|
||||
expect(component.showEditDialog).toBe(true);
|
||||
expect(component.selectedNote).toEqual(selectedNote);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.updateFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('confirms note deletion and removes the note when the accept callback succeeds', () => {
|
||||
const keepNote = createNote(1);
|
||||
const deleteCandidate = createNote(2, {title: 'Delete me'});
|
||||
component.notes = [keepNote, deleteCandidate];
|
||||
bookNoteService.deleteNote.mockReturnValue(of(void 0));
|
||||
|
||||
component.deleteNote(deleteCandidate);
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
key: 'deleteNote',
|
||||
header: 'book.notes.confirm.deleteHeader',
|
||||
message: 'book.notes.confirm.deleteMessage:{"title":"Delete me"}',
|
||||
});
|
||||
expect(bookNoteService.deleteNote).toHaveBeenCalledWith(2);
|
||||
expect(component.notes).toEqual([keepNote]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'common.success',
|
||||
detail: 'book.notes.toast.deleteSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when the confirmed delete fails', () => {
|
||||
const note = createNote(3, {title: 'Delete me'});
|
||||
component.notes = [note];
|
||||
bookNoteService.deleteNote.mockReturnValue(throwError(() => new Error('delete failed')));
|
||||
|
||||
component.deleteNote(note);
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(bookNoteService.deleteNote).toHaveBeenCalledWith(3);
|
||||
expect(component.notes).toEqual([note]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.deleteFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('resets create and edit state when dialogs are cancelled', () => {
|
||||
const selectedNote = createNote(4);
|
||||
component.showCreateDialog = true;
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: 'Draft title',
|
||||
content: 'Draft content',
|
||||
};
|
||||
component.showEditDialog = true;
|
||||
component.selectedNote = selectedNote;
|
||||
component.editNote = {
|
||||
id: selectedNote.id,
|
||||
bookId: 42,
|
||||
title: 'Edited title',
|
||||
content: 'Edited content',
|
||||
};
|
||||
|
||||
component.cancelCreate();
|
||||
component.cancelEdit();
|
||||
|
||||
expect(component.showCreateDialog).toBe(false);
|
||||
expect(component.newNote).toEqual({
|
||||
bookId: 42,
|
||||
title: '',
|
||||
content: '',
|
||||
});
|
||||
expect(component.showEditDialog).toBe(false);
|
||||
expect(component.selectedNote).toBeNull();
|
||||
expect(component.editNote).toEqual({
|
||||
bookId: 42,
|
||||
title: '',
|
||||
content: '',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookReviewService} from './book-review-service';
|
||||
|
||||
describe('BookReviewService', () => {
|
||||
let service: BookReviewService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookReviewService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookReviewService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads reviews for a specific book', () => {
|
||||
let responseBody: unknown;
|
||||
|
||||
service.getByBookId(7).subscribe(response => {
|
||||
responseBody = response;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'GET' && req.url.endsWith('/api/v1/reviews/book/7')
|
||||
);
|
||||
request.flush([{id: 1, title: 'Great review'}]);
|
||||
|
||||
expect(responseBody).toEqual([{id: 1, title: 'Great review'}]);
|
||||
});
|
||||
|
||||
it('refreshes reviews through the refresh endpoint', () => {
|
||||
service.refreshReviews(9).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'POST' && req.url.endsWith('/api/v1/reviews/book/9/refresh')
|
||||
);
|
||||
expect(request.request.body).toEqual({});
|
||||
request.flush([{id: 3, title: 'Fresh review'}]);
|
||||
});
|
||||
|
||||
it('deletes a single review by id', () => {
|
||||
service.delete(11).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'DELETE' && req.url.endsWith('/api/v1/reviews/11')
|
||||
);
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('deletes all reviews for a book', () => {
|
||||
service.deleteAllByBookId(12).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'DELETE' && req.url.endsWith('/api/v1/reviews/book/12')
|
||||
);
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
import {SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {BookReview, BookReviewService} from './book-review-service';
|
||||
import {BookReviewsComponent} from './book-reviews.component';
|
||||
|
||||
interface ConfirmationLike {
|
||||
message?: string;
|
||||
header?: string;
|
||||
accept?: () => void;
|
||||
}
|
||||
|
||||
function createReview(id: number, overrides: Partial<BookReview> = {}): BookReview {
|
||||
return {
|
||||
id,
|
||||
metadataProvider: 'goodreads',
|
||||
reviewerName: `Reviewer ${id}`,
|
||||
title: `Review ${id}`,
|
||||
rating: 4,
|
||||
date: `2026-03-${String(id).padStart(2, '0')}T12:00:00.000Z`,
|
||||
body: `Review body ${id}`,
|
||||
country: 'US',
|
||||
spoiler: false,
|
||||
followersCount: 10,
|
||||
textReviewsCount: 20,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookReviewsComponent', () => {
|
||||
let component: BookReviewsComponent;
|
||||
let reviewService: {
|
||||
getByBookId: ReturnType<typeof vi.fn>;
|
||||
refreshReviews: ReturnType<typeof vi.fn>;
|
||||
delete: ReturnType<typeof vi.fn>;
|
||||
deleteAllByBookId: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookService: {
|
||||
findBookById: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookMetadataManageService: {
|
||||
toggleFieldLocks: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let confirmationService: {
|
||||
confirm: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let messageService: {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {
|
||||
currentUser: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let appSettingsService: {
|
||||
appSettings: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let lastConfirmation: ConfirmationLike | null;
|
||||
|
||||
function createComponent(): BookReviewsComponent {
|
||||
return TestBed.runInInjectionContext(() => new BookReviewsComponent());
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
lastConfirmation = null;
|
||||
reviewService = {
|
||||
getByBookId: vi.fn(),
|
||||
refreshReviews: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteAllByBookId: vi.fn(),
|
||||
};
|
||||
bookService = {
|
||||
findBookById: vi.fn(),
|
||||
};
|
||||
bookMetadataManageService = {
|
||||
toggleFieldLocks: vi.fn(),
|
||||
};
|
||||
confirmationService = {
|
||||
confirm: vi.fn((confirmation: ConfirmationLike) => {
|
||||
lastConfirmation = confirmation;
|
||||
}),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canEditMetadata: true,
|
||||
},
|
||||
})),
|
||||
};
|
||||
appSettingsService = {
|
||||
appSettings: vi.fn(() => ({
|
||||
metadataPublicReviewsSettings: {
|
||||
downloadEnabled: false,
|
||||
},
|
||||
})),
|
||||
};
|
||||
translate = vi.fn((key: string, params?: Record<string, unknown>) => (
|
||||
params ? `${key}:${JSON.stringify(params)}` : key
|
||||
));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: BookReviewService, useValue: reviewService},
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: BookMetadataManageService, useValue: bookMetadataManageService},
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
component = createComponent();
|
||||
component.bookId = 42;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads reviews on book changes, sorts them by date, and mirrors the current lock state', () => {
|
||||
const undated = createReview(1, {date: undefined});
|
||||
const oldest = createReview(2, {date: '2026-03-02T12:00:00.000Z'});
|
||||
const newest = createReview(3, {date: '2026-03-03T12:00:00.000Z'});
|
||||
reviewService.getByBookId.mockReturnValue(of([oldest, undated, newest]));
|
||||
bookService.findBookById.mockReturnValue({
|
||||
metadata: {
|
||||
reviewsLocked: true,
|
||||
},
|
||||
});
|
||||
|
||||
component.ngOnChanges({
|
||||
bookId: new SimpleChange(undefined, 42, true),
|
||||
});
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(bookService.findBookById).toHaveBeenCalledWith(42);
|
||||
expect(reviewService.getByBookId).toHaveBeenCalledWith(42);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([3, 2, 1]);
|
||||
expect(component.reviewsLocked).toBe(true);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('refreshes reviews, clears revealed spoilers, and shows a success toast', () => {
|
||||
const spoilerReview = createReview(5, {spoiler: true, date: '2026-03-05T12:00:00.000Z'});
|
||||
const plainReview = createReview(4, {date: '2026-03-04T12:00:00.000Z'});
|
||||
reviewService.refreshReviews.mockReturnValue(of([plainReview, spoilerReview]));
|
||||
component.revealedSpoilers.add(spoilerReview.id!);
|
||||
component.allSpoilersRevealed = true;
|
||||
|
||||
component.fetchNewReviews();
|
||||
|
||||
expect(reviewService.refreshReviews).toHaveBeenCalledWith(42);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([5, 4]);
|
||||
expect(component.revealedSpoilers.size).toBe(0);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
expect(component.loading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.reviews.toast.reviewsUpdatedSummary',
|
||||
detail: 'book.reviews.toast.reviewsUpdatedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when refreshing reviews fails', () => {
|
||||
const error = new Error('refresh failed');
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
reviewService.refreshReviews.mockReturnValue(throwError(() => error));
|
||||
|
||||
component.fetchNewReviews();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledWith('Failed to fetch new reviews:', error);
|
||||
expect(component.loading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'book.reviews.toast.fetchFailedSummary',
|
||||
detail: 'book.reviews.toast.fetchFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('confirms single-review deletion, removes the review, and recomputes spoiler state', () => {
|
||||
const keepReview = createReview(1, {spoiler: false});
|
||||
const deleteReview = createReview(2, {spoiler: true});
|
||||
reviewService.delete.mockReturnValue(of(void 0));
|
||||
component.reviews = [keepReview, deleteReview];
|
||||
component.revealedSpoilers.add(deleteReview.id!);
|
||||
component.allSpoilersRevealed = true;
|
||||
|
||||
component.deleteReview(deleteReview);
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'book.reviews.confirm.deleteMessage:{"reviewer":"Reviewer 2"}',
|
||||
header: 'book.reviews.confirm.deleteHeader',
|
||||
});
|
||||
expect(reviewService.delete).toHaveBeenCalledWith(2);
|
||||
expect(component.reviews).toEqual([keepReview]);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.reviews.toast.deleteSuccessSummary',
|
||||
detail: 'book.reviews.toast.deleteSuccessDetail',
|
||||
life: 2000,
|
||||
});
|
||||
});
|
||||
|
||||
it('confirms deleting all reviews and clears state after the accept callback succeeds', () => {
|
||||
const firstReview = createReview(7, {spoiler: true});
|
||||
const secondReview = createReview(8, {spoiler: false});
|
||||
reviewService.deleteAllByBookId.mockReturnValue(of(void 0));
|
||||
component.reviews = [firstReview, secondReview];
|
||||
component.revealedSpoilers.add(firstReview.id!);
|
||||
component.allSpoilersRevealed = true;
|
||||
|
||||
component.deleteAllReviews();
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'book.reviews.confirm.deleteAllMessage:{"count":2}',
|
||||
header: 'book.reviews.confirm.deleteAllHeader',
|
||||
});
|
||||
expect(reviewService.deleteAllByBookId).toHaveBeenCalledWith(42);
|
||||
expect(component.reviews).toEqual([]);
|
||||
expect(component.revealedSpoilers.size).toBe(0);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.reviews.toast.allDeletedSummary',
|
||||
detail: 'book.reviews.toast.allDeletedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('sends lock and unlock actions through the metadata service and reports the result', () => {
|
||||
bookMetadataManageService.toggleFieldLocks.mockReturnValue(of(void 0));
|
||||
|
||||
component.reviewsLocked = false;
|
||||
component.toggleReviewsLock();
|
||||
|
||||
component.reviewsLocked = true;
|
||||
component.toggleReviewsLock();
|
||||
|
||||
expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenNthCalledWith(1, [42], {
|
||||
reviewsLocked: 'LOCK',
|
||||
});
|
||||
expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenNthCalledWith(2, [42], {
|
||||
reviewsLocked: 'UNLOCK',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(1, {
|
||||
severity: 'info',
|
||||
summary: 'book.reviews.toast.lockedSummary',
|
||||
detail: 'book.reviews.toast.lockedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(2, {
|
||||
severity: 'info',
|
||||
summary: 'book.reviews.toast.unlockedSummary',
|
||||
detail: 'book.reviews.toast.unlockedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when lock toggling fails', () => {
|
||||
const error = new Error('toggle failed');
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
bookMetadataManageService.toggleFieldLocks.mockReturnValue(throwError(() => error));
|
||||
|
||||
component.toggleReviewsLock();
|
||||
|
||||
expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenCalledWith([42], {
|
||||
reviewsLocked: 'LOCK',
|
||||
});
|
||||
expect(errorSpy).toHaveBeenCalledWith('Failed to toggle lock status:', error);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'book.reviews.toast.lockFailedSummary',
|
||||
detail: 'book.reviews.toast.lockFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('tracks spoiler visibility for individual and bulk reveal flows', () => {
|
||||
const firstSpoiler = createReview(9, {spoiler: true});
|
||||
const secondSpoiler = createReview(10, {spoiler: true});
|
||||
const nonSpoiler = createReview(11, {spoiler: false});
|
||||
component.reviews = [firstSpoiler, secondSpoiler, nonSpoiler];
|
||||
|
||||
component.revealSpoiler(firstSpoiler.id!);
|
||||
expect(component.isSpoilerRevealed(firstSpoiler.id!)).toBe(true);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
|
||||
component.toggleSpoilerVisibility();
|
||||
expect(component.isSpoilerRevealed(secondSpoiler.id!)).toBe(true);
|
||||
expect(component.allSpoilersRevealed).toBe(true);
|
||||
|
||||
component.toggleSpoilerVisibility();
|
||||
expect(component.revealedSpoilers.size).toBe(0);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
});
|
||||
|
||||
it('toggles sort order and reorders dated and undated reviews accordingly', () => {
|
||||
const newest = createReview(12, {date: '2026-03-12T12:00:00.000Z'});
|
||||
const oldest = createReview(13, {date: '2026-03-01T12:00:00.000Z'});
|
||||
const undated = createReview(14, {date: undefined});
|
||||
component.reviews = [newest, undated, oldest];
|
||||
|
||||
component.toggleSortOrder();
|
||||
expect(component.sortAscending).toBe(true);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([14, 13, 12]);
|
||||
|
||||
component.toggleSortOrder();
|
||||
expect(component.sortAscending).toBe(false);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([12, 13, 14]);
|
||||
});
|
||||
|
||||
it('derives permission and app-setting state and exposes helper formatting behavior', () => {
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.hasPermission).toBe(true);
|
||||
expect(component.reviewDownloadEnabled).toBe(false);
|
||||
expect(component.getProviderSeverity('amazon')).toBe('warn');
|
||||
expect(component.getProviderSeverity('goodreads')).toBe('success');
|
||||
expect(component.formatDate('2026-03-28T12:00:00.000Z')).toBe('March 28, 2026');
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around debounced signal-to-observable
|
||||
// search state, global document click listeners, and router navigation so search dropdown behavior
|
||||
// can be tested without a browser-event harness.
|
||||
describe.skip('BookSearcherComponent', () => {
|
||||
it('needs debounce seams to verify filtered-book output, loading state, and active-index reset behavior', () => {
|
||||
// TODO(seam): Cover the debounced search signal and filteredBooks computed state once timing concerns are extracted for direct control.
|
||||
});
|
||||
|
||||
it('needs event seams to verify keyboard navigation, outside-click clearing, and routed book selection', () => {
|
||||
// TODO(seam): Cover onKeydown and onDocumentClick after isolating host listeners and router side effects behind adapters.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,367 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {beforeEach, afterEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {
|
||||
AdditionalFile,
|
||||
AdditionalFileType,
|
||||
Book,
|
||||
BookFile,
|
||||
} from '../../model/book.model';
|
||||
import {BookSenderComponent} from './book-sender.component';
|
||||
import {EmailProvider} from '../../../settings/email-v2/email-provider.model';
|
||||
import {EmailRecipient} from '../../../settings/email-v2/email-recipient.model';
|
||||
import {EmailService} from '../../../settings/email-v2/email.service';
|
||||
import {EmailV2ProviderService} from '../../../settings/email-v2/email-v2-provider/email-v2-provider.service';
|
||||
import {EmailV2RecipientService} from '../../../settings/email-v2/email-v2-recipient/email-v2-recipient.service';
|
||||
|
||||
type EmailBookRequest = Parameters<EmailService['emailBook']>[0];
|
||||
|
||||
describe('BookSenderComponent', () => {
|
||||
let emailProviders: EmailProvider[];
|
||||
let emailRecipients: EmailRecipient[];
|
||||
let emailBookError: Error | null;
|
||||
|
||||
const providerService = {
|
||||
getEmailProviders: vi.fn(() => of(emailProviders)),
|
||||
};
|
||||
const recipientService = {
|
||||
getRecipients: vi.fn(() => of(emailRecipients)),
|
||||
};
|
||||
const emailService = {
|
||||
emailBook: vi.fn((request: EmailBookRequest) => {
|
||||
void request;
|
||||
return emailBookError
|
||||
? throwError(() => emailBookError)
|
||||
: of(void 0);
|
||||
}),
|
||||
};
|
||||
const messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
const dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
const translocoService = {
|
||||
translate: vi.fn((key: string) => key),
|
||||
};
|
||||
const dialogConfig: {data: {book: Book}} = {
|
||||
data: {book: createBook()},
|
||||
};
|
||||
|
||||
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
emailProviders = [
|
||||
createProvider({
|
||||
id: 101,
|
||||
name: 'Primary SMTP',
|
||||
fromAddress: 'books@example.com',
|
||||
host: 'smtp.primary.test',
|
||||
}),
|
||||
createProvider({
|
||||
id: 102,
|
||||
name: 'Fallback SMTP',
|
||||
fromAddress: '',
|
||||
host: 'smtp.fallback.test',
|
||||
}),
|
||||
];
|
||||
emailRecipients = [
|
||||
createRecipient({
|
||||
id: 201,
|
||||
name: 'Alice Reader',
|
||||
email: 'alice@example.com',
|
||||
}),
|
||||
];
|
||||
emailBookError = null;
|
||||
|
||||
providerService.getEmailProviders.mockClear();
|
||||
recipientService.getRecipients.mockClear();
|
||||
emailService.emailBook.mockClear();
|
||||
messageService.add.mockClear();
|
||||
dialogRef.close.mockClear();
|
||||
translocoService.translate.mockClear();
|
||||
|
||||
dialogConfig.data = {book: createBook()};
|
||||
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: EmailV2ProviderService, useValue: providerService},
|
||||
{provide: EmailV2RecipientService, useValue: recipientService},
|
||||
{provide: EmailService, useValue: emailService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: DynamicDialogConfig, useValue: dialogConfig},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleErrorSpy.mockRestore();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('builds emailable files and maps provider and recipient options on init', () => {
|
||||
const component = instantiateComponent(createBook({
|
||||
primaryFile: createBookFile({
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
bookType: 'EPUB',
|
||||
fileSizeKb: 512,
|
||||
}),
|
||||
alternativeFormats: [
|
||||
createAdditionalFile({
|
||||
id: 22,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 4096,
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
}),
|
||||
createAdditionalFile({
|
||||
id: 33,
|
||||
bookId: 1,
|
||||
bookType: 'MOBI',
|
||||
fileSizeKb: 2048,
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
}),
|
||||
],
|
||||
supplementaryFiles: [
|
||||
createAdditionalFile({
|
||||
id: 44,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 128,
|
||||
additionalFileType: AdditionalFileType.SUPPLEMENTARY,
|
||||
}),
|
||||
],
|
||||
}));
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(providerService.getEmailProviders).toHaveBeenCalledOnce();
|
||||
expect(recipientService.getRecipients).toHaveBeenCalledOnce();
|
||||
expect(component.emailProviders).toEqual([
|
||||
{
|
||||
label: 'Primary SMTP | books@example.com',
|
||||
value: emailProviders[0],
|
||||
},
|
||||
{
|
||||
label: 'Fallback SMTP | smtp.fallback.test',
|
||||
value: emailProviders[1],
|
||||
},
|
||||
]);
|
||||
expect(component.emailRecipients).toEqual([
|
||||
{
|
||||
label: 'Alice Reader | alice@example.com',
|
||||
value: emailRecipients[0],
|
||||
},
|
||||
]);
|
||||
expect(component.selectedFileId).toBe(11);
|
||||
expect(component.emailableFiles).toHaveLength(3);
|
||||
expect(component.emailableFiles.map(file => file.id)).toEqual([11, 22, 33]);
|
||||
expect(component.emailableFiles).toMatchObject([
|
||||
{id: 11, bookType: 'EPUB', fileSizeKb: 512, isPrimary: true},
|
||||
{id: 22, bookType: 'PDF', fileSizeKb: 4096, isPrimary: false},
|
||||
{id: 33, bookType: 'MOBI', fileSizeKb: 2048, isPrimary: false},
|
||||
]);
|
||||
});
|
||||
|
||||
it('formats file sizes across empty, kilobyte, and megabyte values', () => {
|
||||
const component = instantiateComponent();
|
||||
|
||||
expect(component.formatFileSize()).toBe('-');
|
||||
expect(component.formatFileSize(512)).toBe('512 KB');
|
||||
expect(component.formatFileSize(1536)).toBe('1.50 MB');
|
||||
});
|
||||
|
||||
it('shows the large-file warning only for selected files above the threshold', () => {
|
||||
const component = instantiateComponent(createBook({
|
||||
primaryFile: createBookFile({
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
fileSizeKb: 512,
|
||||
}),
|
||||
alternativeFormats: [
|
||||
createAdditionalFile({
|
||||
id: 22,
|
||||
bookId: 1,
|
||||
fileSizeKb: 30 * 1024,
|
||||
}),
|
||||
],
|
||||
}));
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.showLargeFileWarning).toBe(false);
|
||||
|
||||
component.selectedFileId = 22;
|
||||
expect(component.showLargeFileWarning).toBe(true);
|
||||
|
||||
component.selectedFileId = undefined;
|
||||
expect(component.showLargeFileWarning).toBe(false);
|
||||
});
|
||||
|
||||
it('shows validation errors and does not send when provider, recipient, or book are missing', () => {
|
||||
const component = instantiateComponent(createBook({id: 0}));
|
||||
|
||||
component.sendBook();
|
||||
|
||||
expect(emailService.emailBook).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledTimes(3);
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(1, {
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.providerMissingSummary',
|
||||
detail: 'book.sender.toast.providerMissingDetail',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(2, {
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.recipientMissingSummary',
|
||||
detail: 'book.sender.toast.recipientMissingDetail',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(3, {
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.bookNotSelectedSummary',
|
||||
detail: 'book.sender.toast.bookNotSelectedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the selected file and closes the dialog after a successful response', () => {
|
||||
const component = instantiateComponent();
|
||||
component.ngOnInit();
|
||||
component.selectedProvider = component.emailProviders[0];
|
||||
component.selectedRecipient = component.emailRecipients[0];
|
||||
component.selectedFileId = 22;
|
||||
|
||||
component.sendBook();
|
||||
|
||||
expect(emailService.emailBook).toHaveBeenCalledWith({
|
||||
bookId: 1,
|
||||
providerId: 101,
|
||||
recipientId: 201,
|
||||
bookFileId: 22,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.sender.toast.emailScheduledSummary',
|
||||
detail: 'book.sender.toast.emailScheduledDetail',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when sending fails', () => {
|
||||
emailBookError = new Error('SMTP rejected request');
|
||||
|
||||
const component = instantiateComponent();
|
||||
component.ngOnInit();
|
||||
component.selectedProvider = component.emailProviders[0];
|
||||
component.selectedRecipient = component.emailRecipients[0];
|
||||
|
||||
component.sendBook();
|
||||
|
||||
expect(emailService.emailBook).toHaveBeenCalledWith({
|
||||
bookId: 1,
|
||||
providerId: 101,
|
||||
recipientId: 201,
|
||||
bookFileId: 11,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.sendingFailedSummary',
|
||||
detail: 'book.sender.toast.sendingFailedDetail',
|
||||
});
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
expect(consoleErrorSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
function instantiateComponent(book: Book = createBook()): BookSenderComponent {
|
||||
dialogConfig.data = {book};
|
||||
return TestBed.runInInjectionContext(() => new BookSenderComponent());
|
||||
}
|
||||
});
|
||||
|
||||
function createBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 1,
|
||||
libraryId: 7,
|
||||
libraryName: 'Main Library',
|
||||
primaryFile: createBookFile({
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
bookType: 'EPUB',
|
||||
fileSizeKb: 512,
|
||||
}),
|
||||
alternativeFormats: [
|
||||
createAdditionalFile({
|
||||
id: 22,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 2048,
|
||||
}),
|
||||
],
|
||||
supplementaryFiles: [
|
||||
createAdditionalFile({
|
||||
id: 44,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 128,
|
||||
additionalFileType: AdditionalFileType.SUPPLEMENTARY,
|
||||
}),
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBookFile(overrides: Partial<BookFile> = {}): BookFile {
|
||||
return {
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
fileName: 'book.epub',
|
||||
bookType: 'EPUB',
|
||||
fileSizeKb: 512,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createAdditionalFile(overrides: Partial<AdditionalFile> = {}): AdditionalFile {
|
||||
return {
|
||||
...createBookFile(),
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createProvider(overrides: Partial<EmailProvider> = {}): EmailProvider {
|
||||
return {
|
||||
isEditing: false,
|
||||
id: 101,
|
||||
userId: 1,
|
||||
name: 'Primary SMTP',
|
||||
host: 'smtp.example.test',
|
||||
port: 587,
|
||||
username: 'mailer',
|
||||
password: 'secret',
|
||||
fromAddress: 'books@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: true,
|
||||
shared: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createRecipient(overrides: Partial<EmailRecipient> = {}): EmailRecipient {
|
||||
return {
|
||||
id: 201,
|
||||
email: 'alice@example.com',
|
||||
name: 'Alice Reader',
|
||||
defaultRecipient: true,
|
||||
isEditing: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around file-reader input, paced async
|
||||
// import loops, metadata lookup retries, and library-service state so ISBN parsing and import
|
||||
// progress can be asserted without browser file APIs and timing-heavy runtime behavior.
|
||||
describe.skip('BulkIsbnImportDialogComponent', () => {
|
||||
it('needs parser seams to verify pasted-text parsing, file parsing, duplicate removal, and already-existing ISBN filtering', () => {
|
||||
// TODO(seam): Cover parseContent and related normalization helpers once file-reader inputs and existing-library lookup state are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs async-loop seams to verify import progress, cancellation, retry timing, and summary transitions', () => {
|
||||
// TODO(seam): Cover startImport and progress bookkeeping after metadata lookup, create-book requests, and delay scheduling are extracted into a stable harness.
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around dialog config/bootstrap state,
|
||||
// paginator state, confirmation flows, and multi-step duplicate merge orchestration so the
|
||||
// component can be tested without building a full dialog-plus-confirmation harness.
|
||||
describe.skip('DuplicateMergerComponent', () => {
|
||||
it('needs scanning seams to verify preset toggles, duplicate detection request shaping, and display-group initialization', () => {
|
||||
// TODO(seam): Cover applyPreset and scan once the dialog config and duplicate scan subscription flow are isolated behind test doubles.
|
||||
});
|
||||
|
||||
it('needs merge seams to verify target selection, dismissal, pagination, and attach-file success and failure handling', () => {
|
||||
// TODO(seam): Cover the merge workflow after extracting confirmation, loader, and dialog-close side effects from the component runtime.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around route-param signals, Angular Query
|
||||
// detail loading, selection state, and the large series dashboard template so the series page
|
||||
// control flow can be asserted without mounting the full browser and query runtime.
|
||||
describe.skip('SeriesPageComponent', () => {
|
||||
it('needs route and query seams to verify filtered series books, cover-book resolution, and description loading', () => {
|
||||
// TODO(seam): Cover the computed series view model once route params and injectQuery data can be driven through a deterministic harness.
|
||||
});
|
||||
|
||||
it('needs interaction seams to verify selection, menu actions, metadata flows, and overflow handling', () => {
|
||||
// TODO(seam): Cover selection state, action menus, and description expansion after overlay, loading-service, and DOM measurement concerns are isolated behind test adapters.
|
||||
});
|
||||
});
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {LoadingService} from '../../../../core/services/loading.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||
import {ShelfAssignerComponent} from './shelf-assigner.component';
|
||||
|
||||
interface CurrentUserLike {
|
||||
id: number;
|
||||
userSettings: {
|
||||
sidebarShelfSorting: {
|
||||
field: string;
|
||||
order: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
describe('ShelfAssignerComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createShelf(overrides: Partial<Shelf> = {}): Shelf {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
userId: 7,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 101,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
shelves: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createCurrentUser(
|
||||
sorting: {field: string; order: string} = {field: 'name', order: 'asc'},
|
||||
id: number = 7,
|
||||
): CurrentUserLike {
|
||||
return {
|
||||
id,
|
||||
userSettings: {
|
||||
sidebarShelfSorting: sorting,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(options: {
|
||||
book?: Book;
|
||||
bookIds?: Set<number>;
|
||||
isMultiBooks?: boolean;
|
||||
shelves?: Shelf[];
|
||||
currentUser?: CurrentUserLike | null;
|
||||
updateResult?: Observable<Book[]>;
|
||||
} = {}) {
|
||||
const shelves = signal(options.shelves ?? []);
|
||||
const currentUser = signal<CurrentUserLike | null>(options.currentUser ?? createCurrentUser());
|
||||
const updateBookShelves = vi.fn(() => options.updateResult ?? of([] as Book[]));
|
||||
const dialogRef = {close: vi.fn()};
|
||||
const messageService = {add: vi.fn()};
|
||||
const bookDialogHelper = {openShelfCreatorDialog: vi.fn()};
|
||||
const loader = document.createElement('div');
|
||||
const loadingService = {
|
||||
show: vi.fn(() => loader),
|
||||
hide: vi.fn(),
|
||||
};
|
||||
const translate = vi.fn(<T = string>(key: string, params?: Record<string, unknown>) => {
|
||||
if (typeof params?.['count'] === 'number') {
|
||||
return `translated:${key}:${String(params['count'])}` as T;
|
||||
}
|
||||
|
||||
return `translated:${key}` as T;
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: ShelfService,
|
||||
useValue: {shelves},
|
||||
},
|
||||
{
|
||||
provide: DynamicDialogConfig,
|
||||
useValue: {
|
||||
data: {
|
||||
book: options.book ?? createBook(),
|
||||
bookIds: options.bookIds ?? new Set<number>(),
|
||||
isMultiBooks: options.isMultiBooks ?? false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: BookService, useValue: {updateBookShelves}},
|
||||
{provide: BookDialogHelperService, useValue: bookDialogHelper},
|
||||
{provide: LoadingService, useValue: loadingService},
|
||||
{provide: UserService, useValue: {currentUser}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new ShelfAssignerComponent());
|
||||
TestBed.flushEffects();
|
||||
|
||||
return {
|
||||
component,
|
||||
shelves,
|
||||
currentUser,
|
||||
updateBookShelves,
|
||||
dialogRef,
|
||||
messageService,
|
||||
bookDialogHelper,
|
||||
loadingService,
|
||||
loader,
|
||||
translate,
|
||||
};
|
||||
}
|
||||
|
||||
it('initializes selected shelves from the injected book once shelf data is available', () => {
|
||||
const unread = createShelf({id: 1, name: 'Unread'});
|
||||
const favorites = createShelf({id: 2, name: 'Favorites'});
|
||||
const foreignShelf = createShelf({id: 3, name: 'Other User Shelf', userId: 8});
|
||||
const book = createBook({
|
||||
shelves: [
|
||||
createShelf({id: 2, name: 'Favorites'}),
|
||||
],
|
||||
});
|
||||
|
||||
const {component} = createHarness({
|
||||
book,
|
||||
shelves: [unread, favorites, foreignShelf],
|
||||
});
|
||||
|
||||
expect(component.selectedShelves).toEqual([favorites]);
|
||||
expect(component.isShelfSelected(favorites)).toBe(true);
|
||||
expect(component.isShelfSelected(unread)).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to name ascending sorting when sidebar preferences are invalid', () => {
|
||||
const {component} = createHarness({
|
||||
currentUser: createCurrentUser({field: 'createdAt', order: 'SIDEWAYS'}),
|
||||
shelves: [
|
||||
createShelf({id: 2, name: 'Zulu'}),
|
||||
createShelf({id: 1, name: 'Alpha'}),
|
||||
createShelf({id: 3, name: 'Hidden', userId: 42}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(component.shelves().map(shelf => shelf.name)).toEqual(['Alpha', 'Zulu']);
|
||||
});
|
||||
|
||||
it('sorts shelves by id descending when the stored sidebar preferences are valid', () => {
|
||||
const {component} = createHarness({
|
||||
currentUser: createCurrentUser({field: 'id', order: 'desc'}),
|
||||
shelves: [
|
||||
createShelf({id: 1, name: 'One'}),
|
||||
createShelf({id: 3, name: 'Three'}),
|
||||
createShelf({id: 2, name: 'Two'}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(component.shelves().map(shelf => shelf.id)).toEqual([3, 2, 1]);
|
||||
});
|
||||
|
||||
it('filters shelves by a trimmed case-insensitive query', () => {
|
||||
const {component} = createHarness();
|
||||
const shelves = [
|
||||
createShelf({id: 1, name: 'Science Fiction'}),
|
||||
createShelf({id: 2, name: 'History'}),
|
||||
createShelf({id: 3, name: 'Sci-Fi Favorites'}),
|
||||
];
|
||||
|
||||
component.searchQuery = ' sci ';
|
||||
|
||||
expect(component.filterShelves(shelves).map(shelf => shelf.name)).toEqual([
|
||||
'Science Fiction',
|
||||
'Sci-Fi Favorites',
|
||||
]);
|
||||
});
|
||||
|
||||
it('maps custom svg and PrimeNG shelf icons to icon-display selections', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
expect(component.getShelfIcon(createShelf({
|
||||
iconType: 'CUSTOM_SVG',
|
||||
icon: 'custom-icons/moon.svg',
|
||||
}))).toEqual({
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
});
|
||||
expect(component.getShelfIcon(createShelf({
|
||||
iconType: 'PRIME_NG',
|
||||
icon: 'bookmark',
|
||||
}))).toEqual({
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-bookmark',
|
||||
});
|
||||
});
|
||||
|
||||
it('shapes assign and unassign payloads for a single-book update and closes with success', () => {
|
||||
const existing = createShelf({id: 1, name: 'Existing'});
|
||||
const added = createShelf({id: 2, name: 'Added'});
|
||||
const removed = createShelf({id: 3, name: 'Removed'});
|
||||
const {component, updateBookShelves, loadingService, loader, messageService, dialogRef, translate} = createHarness({
|
||||
book: createBook({
|
||||
id: 11,
|
||||
shelves: [existing, removed],
|
||||
}),
|
||||
});
|
||||
|
||||
component.selectedShelves = [existing, added];
|
||||
|
||||
component.updateBooksShelves();
|
||||
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfAssigner.loading.updatingShelves', {count: 1});
|
||||
expect(loadingService.show).toHaveBeenCalledWith('translated:book.shelfAssigner.loading.updatingShelves:1');
|
||||
expect(updateBookShelves).toHaveBeenCalledWith(
|
||||
new Set([11]),
|
||||
new Set([1, 2]),
|
||||
new Set([3]),
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith(loader);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'translated:common.success',
|
||||
detail: 'translated:book.shelfAssigner.toast.updateSuccessDetail',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({assigned: true});
|
||||
});
|
||||
|
||||
it('uses the injected multi-book ids, skips unassigns, and closes with failure on update errors', () => {
|
||||
const selected = createShelf({id: 5, name: 'Selected'});
|
||||
const targetBookIds = new Set([41, 42]);
|
||||
const {component, updateBookShelves, loadingService, loader, messageService, dialogRef, translate} = createHarness({
|
||||
book: createBook({
|
||||
id: 11,
|
||||
shelves: [createShelf({id: 9, name: 'Ignored Existing'})],
|
||||
}),
|
||||
bookIds: targetBookIds,
|
||||
isMultiBooks: true,
|
||||
updateResult: throwError(() => new Error('update failed')),
|
||||
});
|
||||
|
||||
component.selectedShelves = [selected];
|
||||
|
||||
component.updateBooksShelves();
|
||||
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfAssigner.loading.updatingShelves', {count: 2});
|
||||
expect(updateBookShelves).toHaveBeenCalledWith(
|
||||
targetBookIds,
|
||||
new Set([5]),
|
||||
new Set(),
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith(loader);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:common.error',
|
||||
detail: 'translated:book.shelfAssigner.toast.updateFailedDetail',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({assigned: false});
|
||||
});
|
||||
});
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {ShelfCreatorComponent} from './shelf-creator.component';
|
||||
|
||||
describe('ShelfCreatorComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createHarness(options: {
|
||||
createResult?: Observable<Shelf>;
|
||||
iconPickerResult?: IconSelection | null;
|
||||
currentUser?: {permissions: {admin: boolean}} | null;
|
||||
} = {}) {
|
||||
const createShelf = vi.fn(() => options.createResult ?? of({
|
||||
name: 'Created Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
}));
|
||||
const dialogRef = {close: vi.fn()};
|
||||
const messageService = {add: vi.fn()};
|
||||
const iconPickerService = {
|
||||
open: vi.fn(() => of(options.iconPickerResult ?? null)),
|
||||
};
|
||||
const getCurrentUser = vi.fn(() => options.currentUser ?? {permissions: {admin: false}});
|
||||
const translate = vi.fn(<T = string>(key: string, params?: Record<string, unknown>) => {
|
||||
if (params?.['name']) {
|
||||
return `translated:${key}:${String(params['name'])}` as T;
|
||||
}
|
||||
|
||||
return `translated:${key}` as T;
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: ShelfService, useValue: {createShelf}},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: IconPickerService, useValue: iconPickerService},
|
||||
{provide: UserService, useValue: {getCurrentUser}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new ShelfCreatorComponent());
|
||||
|
||||
return {
|
||||
component,
|
||||
createShelf,
|
||||
dialogRef,
|
||||
messageService,
|
||||
iconPickerService,
|
||||
translate,
|
||||
};
|
||||
}
|
||||
|
||||
it('picks an icon through the injected icon picker and ignores empty selections', () => {
|
||||
const pickedIcon: IconSelection = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-star',
|
||||
};
|
||||
const {component, iconPickerService} = createHarness({
|
||||
iconPickerResult: pickedIcon,
|
||||
});
|
||||
|
||||
component.openIconPicker();
|
||||
|
||||
expect(iconPickerService.open).toHaveBeenCalledOnce();
|
||||
expect(component.selectedIcon).toEqual(pickedIcon);
|
||||
|
||||
iconPickerService.open.mockReturnValueOnce(of(null));
|
||||
component.openIconPicker();
|
||||
|
||||
expect(component.selectedIcon).toEqual(pickedIcon);
|
||||
});
|
||||
|
||||
it('clears the selected icon directly', () => {
|
||||
const {component} = createHarness();
|
||||
component.selectedIcon = {
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
};
|
||||
|
||||
component.clearSelectedIcon();
|
||||
|
||||
expect(component.selectedIcon).toBeNull();
|
||||
});
|
||||
|
||||
it('closes the dialog without a payload when cancelled', () => {
|
||||
const {component, dialogRef} = createHarness();
|
||||
|
||||
component.cancel();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
expect(dialogRef.close).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it('creates a shelf with the selected icon, shows a success toast, and closes with true', () => {
|
||||
const {component, createShelf, messageService, dialogRef, translate} = createHarness({
|
||||
currentUser: {permissions: {admin: true}},
|
||||
});
|
||||
|
||||
component.shelfName = 'Weekend Reads';
|
||||
component.isPublic = true;
|
||||
component.selectedIcon = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-bookmark',
|
||||
};
|
||||
|
||||
component.createShelf();
|
||||
|
||||
expect(createShelf).toHaveBeenCalledWith({
|
||||
name: 'Weekend Reads',
|
||||
icon: 'pi pi-bookmark',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
});
|
||||
expect(translate).toHaveBeenCalledWith('common.success');
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfCreator.toast.createSuccessDetail', {
|
||||
name: 'Weekend Reads',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'translated:common.success',
|
||||
detail: 'translated:book.shelfCreator.toast.createSuccessDetail:Weekend Reads',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('creates a shelf with null icon fields when no icon is selected', () => {
|
||||
const {component, createShelf} = createHarness();
|
||||
|
||||
component.shelfName = 'Plain Shelf';
|
||||
component.isPublic = false;
|
||||
component.selectedIcon = null;
|
||||
|
||||
component.createShelf();
|
||||
|
||||
expect(createShelf).toHaveBeenCalledWith({
|
||||
name: 'Plain Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when create fails', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const {component, createShelf, messageService, dialogRef, translate} = createHarness({
|
||||
createResult: throwError(() => new Error('create failed')),
|
||||
});
|
||||
|
||||
component.shelfName = 'Broken Shelf';
|
||||
component.selectedIcon = {
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
};
|
||||
component.isPublic = true;
|
||||
|
||||
component.createShelf();
|
||||
|
||||
expect(createShelf).toHaveBeenCalledWith({
|
||||
name: 'Broken Shelf',
|
||||
icon: 'custom-icons/moon.svg',
|
||||
iconType: 'CUSTOM_SVG',
|
||||
publicShelf: true,
|
||||
});
|
||||
expect(translate).toHaveBeenCalledWith('common.error');
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfCreator.toast.createFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:common.error',
|
||||
detail: 'translated:book.shelfCreator.toast.createFailedDetail',
|
||||
});
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
expect(errorSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {ShelfEditDialogComponent} from './shelf-edit-dialog.component';
|
||||
|
||||
describe('ShelfEditDialogComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createShelf(overrides: Partial<Shelf> = {}): Shelf {
|
||||
return {
|
||||
id: 7,
|
||||
name: 'Favorites',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(options: {
|
||||
shelfId?: number;
|
||||
shelvesData?: Shelf[];
|
||||
updateResult?: Observable<Shelf>;
|
||||
iconPickerResult?: IconSelection | null;
|
||||
currentUser?: {permissions: {admin: boolean}} | null;
|
||||
} = {}) {
|
||||
const shelves = signal<Shelf[]>(options.shelvesData ?? []);
|
||||
const updateShelf = vi.fn(() => options.updateResult ?? of(createShelf()));
|
||||
const dialogRef = {close: vi.fn()};
|
||||
const messageService = {add: vi.fn()};
|
||||
const iconPickerService = {
|
||||
open: vi.fn(() => of(options.iconPickerResult ?? null)),
|
||||
};
|
||||
const getCurrentUser = vi.fn(() => options.currentUser ?? {permissions: {admin: false}});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: ShelfService, useValue: {shelves, updateShelf}},
|
||||
{provide: DynamicDialogConfig, useValue: {data: {shelfId: options.shelfId ?? 7}}},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: IconPickerService, useValue: iconPickerService},
|
||||
{provide: UserService, useValue: {getCurrentUser}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new ShelfEditDialogComponent());
|
||||
component.ngOnInit();
|
||||
TestBed.flushEffects();
|
||||
|
||||
return {
|
||||
component,
|
||||
shelves,
|
||||
updateShelf,
|
||||
dialogRef,
|
||||
messageService,
|
||||
iconPickerService,
|
||||
};
|
||||
}
|
||||
|
||||
it('hydrates the dialog from a matching PrimeNG shelf', () => {
|
||||
const shelf = createShelf({
|
||||
id: 42,
|
||||
name: 'Queue',
|
||||
icon: 'bookmark',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
});
|
||||
|
||||
const {component} = createHarness({
|
||||
shelfId: 42,
|
||||
shelvesData: [shelf],
|
||||
});
|
||||
|
||||
expect(component.shelf).toEqual(shelf);
|
||||
expect(component.shelfName).toBe('Queue');
|
||||
expect(component.isPublic).toBe(true);
|
||||
expect(component.selectedIcon).toEqual({
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-bookmark',
|
||||
});
|
||||
});
|
||||
|
||||
it('hydrates custom SVG icons and only initializes once after the shelf becomes available', () => {
|
||||
const {component, shelves} = createHarness({
|
||||
shelfId: 11,
|
||||
shelvesData: [createShelf({id: 99, name: 'Other Shelf'})],
|
||||
});
|
||||
|
||||
expect(component.shelf).toBeUndefined();
|
||||
expect(component.shelfName).toBe('');
|
||||
expect(component.selectedIcon).toBeNull();
|
||||
|
||||
shelves.set([
|
||||
createShelf({
|
||||
id: 11,
|
||||
name: 'Readable',
|
||||
icon: 'custom-icons/moon.svg',
|
||||
iconType: 'CUSTOM_SVG',
|
||||
}),
|
||||
]);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.shelfName).toBe('Readable');
|
||||
expect(component.selectedIcon).toEqual({
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
});
|
||||
|
||||
shelves.set([
|
||||
createShelf({
|
||||
id: 11,
|
||||
name: 'Should Not Replace',
|
||||
icon: 'bookmark',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
}),
|
||||
]);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.shelfName).toBe('Readable');
|
||||
expect(component.isPublic).toBe(false);
|
||||
expect(component.selectedIcon).toEqual({
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
});
|
||||
});
|
||||
|
||||
it('picks and clears icons through the dialog-local icon selection methods', () => {
|
||||
const pickedIcon: IconSelection = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-star',
|
||||
};
|
||||
const {component, iconPickerService} = createHarness({
|
||||
shelvesData: [createShelf()],
|
||||
iconPickerResult: pickedIcon,
|
||||
});
|
||||
|
||||
component.openIconPicker();
|
||||
expect(iconPickerService.open).toHaveBeenCalledOnce();
|
||||
expect(component.selectedIcon).toEqual(pickedIcon);
|
||||
|
||||
component.clearSelectedIcon();
|
||||
expect(component.selectedIcon).toBeNull();
|
||||
});
|
||||
|
||||
it('saves the edited shelf, shows a success toast, and closes the dialog', () => {
|
||||
const {component, updateShelf, messageService, dialogRef} = createHarness({
|
||||
shelfId: 7,
|
||||
shelvesData: [createShelf({id: 7})],
|
||||
});
|
||||
|
||||
component.shelfName = 'Renamed Shelf';
|
||||
component.isPublic = true;
|
||||
component.selectedIcon = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-heart',
|
||||
};
|
||||
|
||||
component.save();
|
||||
|
||||
expect(updateShelf).toHaveBeenCalledWith({
|
||||
name: 'Renamed Shelf',
|
||||
icon: 'pi pi-heart',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
}, 7);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
}));
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when save fails', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const {component, updateShelf, messageService, dialogRef} = createHarness({
|
||||
shelfId: 7,
|
||||
shelvesData: [createShelf({id: 7})],
|
||||
updateResult: throwError(() => new Error('save failed')),
|
||||
});
|
||||
|
||||
component.shelfName = 'Broken Shelf';
|
||||
component.selectedIcon = null;
|
||||
component.isPublic = false;
|
||||
component.save();
|
||||
|
||||
expect(updateShelf).toHaveBeenCalledWith({
|
||||
name: 'Broken Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
}, 7);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
}));
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
expect(errorSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('closes the dialog without saving when cancelled', () => {
|
||||
const {component, dialogRef} = createHarness({
|
||||
shelvesData: [createShelf()],
|
||||
});
|
||||
|
||||
component.closeDialog();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {ReadStatusHelper} from './read-status.helper';
|
||||
|
||||
describe('ReadStatusHelper', () => {
|
||||
const helper = new ReadStatusHelper();
|
||||
|
||||
it('maps statuses to icons and classes', () => {
|
||||
expect(helper.getReadStatusIcon(undefined)).toBe('pi pi-book');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.READ)).toBe('pi pi-check');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.READING)).toBe('pi pi-play');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.RE_READING)).toBe('pi pi-refresh');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.PARTIALLY_READ)).toBe('pi pi-clock');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.PAUSED)).toBe('pi pi-pause');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.ABANDONED)).toBe('pi pi-times');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.WONT_READ)).toBe('pi pi-ban');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.UNREAD)).toBe('pi pi-book');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.UNSET)).toBe('pi pi-book');
|
||||
|
||||
expect(helper.getReadStatusClass(undefined)).toBe('status-unset');
|
||||
expect(helper.getReadStatusClass(ReadStatus.READ)).toBe('status-read');
|
||||
expect(helper.getReadStatusClass(ReadStatus.READING)).toBe('status-reading');
|
||||
expect(helper.getReadStatusClass(ReadStatus.RE_READING)).toBe('status-re-reading');
|
||||
expect(helper.getReadStatusClass(ReadStatus.PARTIALLY_READ)).toBe('status-partially-read');
|
||||
expect(helper.getReadStatusClass(ReadStatus.PAUSED)).toBe('status-paused');
|
||||
expect(helper.getReadStatusClass(ReadStatus.ABANDONED)).toBe('status-abandoned');
|
||||
expect(helper.getReadStatusClass(ReadStatus.WONT_READ)).toBe('status-wont-read');
|
||||
expect(helper.getReadStatusClass(ReadStatus.UNREAD)).toBe('status-unset');
|
||||
expect(helper.getReadStatusClass(ReadStatus.UNSET)).toBe('status-unset');
|
||||
});
|
||||
|
||||
it('maps statuses to tooltips', () => {
|
||||
expect(helper.getReadStatusTooltip(undefined)).toBe('Unset');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.READ)).toBe('Read');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.READING)).toBe('Currently Reading');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.RE_READING)).toBe('Re-reading');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.PARTIALLY_READ)).toBe('Partially Read');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.PAUSED)).toBe('Paused');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.ABANDONED)).toBe('Abandoned');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.WONT_READ)).toBe("Won't Read");
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.UNREAD)).toBe('Unread');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.UNSET)).toBe('Unset');
|
||||
});
|
||||
|
||||
it('always shows the status icon', () => {
|
||||
expect(helper.shouldShowStatusIcon(undefined)).toBe(true);
|
||||
expect(helper.shouldShowStatusIcon(ReadStatus.READ)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {
|
||||
AdditionalFileType,
|
||||
Book,
|
||||
BookMetadata,
|
||||
BookStatusUpdateResponse,
|
||||
BulkMetadataUpdateRequest,
|
||||
computeSeriesReadStatus,
|
||||
CreatePhysicalBookRequest,
|
||||
ReadStatus
|
||||
} from './book.model';
|
||||
|
||||
describe('book.model', () => {
|
||||
it('exposes stable additional file and read-status enums', () => {
|
||||
expect(AdditionalFileType).toEqual({
|
||||
ALTERNATIVE_FORMAT: 'ALTERNATIVE_FORMAT',
|
||||
SUPPLEMENTARY: 'SUPPLEMENTARY'
|
||||
});
|
||||
expect(ReadStatus.UNREAD).toBe('UNREAD');
|
||||
expect(ReadStatus.RE_READING).toBe('RE_READING');
|
||||
});
|
||||
|
||||
it('computes aggregate series status from book states', () => {
|
||||
expect(computeSeriesReadStatus([])).toBe(ReadStatus.UNREAD);
|
||||
expect(computeSeriesReadStatus([{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READ} as Book])).toBe(ReadStatus.READ);
|
||||
expect(computeSeriesReadStatus([
|
||||
{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READ} as Book,
|
||||
{id: 2, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.UNREAD} as Book
|
||||
])).toBe(ReadStatus.PARTIALLY_READ);
|
||||
expect(computeSeriesReadStatus([
|
||||
{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READING} as Book,
|
||||
{id: 2, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.UNREAD} as Book
|
||||
])).toBe(ReadStatus.READING);
|
||||
expect(computeSeriesReadStatus([
|
||||
{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.WONT_READ} as Book
|
||||
])).toBe(ReadStatus.WONT_READ);
|
||||
});
|
||||
|
||||
it('keeps core payload and metadata contracts typed', () => {
|
||||
const metadata: BookMetadata = {
|
||||
bookId: 4,
|
||||
title: 'A Wizard of Earthsea',
|
||||
authors: ['Ursula K. Le Guin'],
|
||||
pageCount: 205
|
||||
};
|
||||
const createRequest: CreatePhysicalBookRequest = {
|
||||
libraryId: 2,
|
||||
title: 'The Tombs of Atuan',
|
||||
authors: ['Ursula K. Le Guin']
|
||||
};
|
||||
const bulkUpdate: BulkMetadataUpdateRequest = {
|
||||
bookIds: [1, 2],
|
||||
genres: ['Fantasy'],
|
||||
mergeCategories: true
|
||||
};
|
||||
const statusUpdate: BookStatusUpdateResponse = {
|
||||
bookId: 1,
|
||||
readStatus: ReadStatus.READ,
|
||||
readStatusModifiedTime: '2026-03-26T10:00:00Z'
|
||||
};
|
||||
|
||||
expect(metadata.authors).toEqual(['Ursula K. Le Guin']);
|
||||
expect(createRequest.libraryId).toBe(2);
|
||||
expect(bulkUpdate.mergeCategories).toBe(true);
|
||||
expect(statusUpdate.readStatus).toBe(ReadStatus.READ);
|
||||
expectTypeOf(metadata.pageCount).toEqualTypeOf<number | null | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {Library, LibraryPath, MetadataSource, OrganizationMode} from './library.model';
|
||||
|
||||
describe('library.model', () => {
|
||||
it('supports a library with paths and optional metadata settings', () => {
|
||||
const library: Library = {
|
||||
id: 1,
|
||||
name: 'Main Library',
|
||||
watch: true,
|
||||
paths: [{id: 10, path: '/books'}],
|
||||
metadataSource: 'PREFER_EMBEDDED',
|
||||
organizationMode: 'AUTO_DETECT'
|
||||
};
|
||||
|
||||
expect(library.paths[0].path).toBe('/books');
|
||||
expect(library.metadataSource).toBe('PREFER_EMBEDDED');
|
||||
expectTypeOf(library.paths).toMatchTypeOf<LibraryPath[]>();
|
||||
});
|
||||
|
||||
it('keeps metadata source and organization mode unions constrained', () => {
|
||||
expectTypeOf<MetadataSource>().toEqualTypeOf<
|
||||
'EMBEDDED' | 'SIDECAR' | 'PREFER_SIDECAR' | 'PREFER_EMBEDDED' | 'NONE'
|
||||
>();
|
||||
expectTypeOf<OrganizationMode>().toEqualTypeOf<
|
||||
'BOOK_PER_FILE' | 'BOOK_PER_FOLDER' | 'AUTO_DETECT'
|
||||
>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {Shelf} from './shelf.model';
|
||||
import {SortDirection} from './sort.model';
|
||||
|
||||
describe('shelf.model', () => {
|
||||
it('supports optional presentation and ownership fields', () => {
|
||||
const shelf: Shelf = {
|
||||
id: 3,
|
||||
name: 'Favorites',
|
||||
icon: 'pi pi-heart',
|
||||
publicShelf: true,
|
||||
userId: 9,
|
||||
bookCount: 24,
|
||||
sort: {
|
||||
label: 'Title',
|
||||
field: 'title',
|
||||
direction: SortDirection.ASCENDING
|
||||
}
|
||||
};
|
||||
|
||||
expect(shelf.name).toBe('Favorites');
|
||||
expect(shelf.sort?.direction).toBe(SortDirection.ASCENDING);
|
||||
});
|
||||
|
||||
it('allows nullable icon values', () => {
|
||||
expectTypeOf<Shelf['icon']>().toEqualTypeOf<string | null | undefined>();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user