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:
James Cox
2026-04-22 17:26:56 -04:00
committed by Zach Yale
parent 09c36dfa0b
commit a3c5da988c
400 changed files with 34010 additions and 807 deletions
@@ -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();
});
});
@@ -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.
});
});
@@ -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');
});
});
@@ -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);
});
});
@@ -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();
});
});
@@ -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}),
})
);
});
});
@@ -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);
});
});
@@ -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},
})
);
});
});
@@ -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);
});
});
@@ -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.
});
});
@@ -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)'}
]);
});
});
@@ -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);
});
});
@@ -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.
});
});
@@ -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]);
});
});
@@ -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
})
}));
});
});
@@ -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',
})
);
});
});
@@ -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]);
});
});
@@ -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');
});
});
@@ -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();
});
});
@@ -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
}));
});
});
@@ -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;
}
@@ -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);
});
});
@@ -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');
});
});
@@ -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,
};
}
@@ -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.
});
});
@@ -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.
});
});
@@ -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});
});
});
@@ -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();
});
});
@@ -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();
});
});