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:
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around signal/effect synchronization,
|
||||
// virtual-scroller behavior, router/route query-param state, and cross-service selection logic so
|
||||
// author browsing can be tested without a full browser shell harness.
|
||||
describe.skip('AuthorBrowserComponent', () => {
|
||||
it('needs state-sync seams to verify author enrichment, filtering, sorting, and active-filter counting', () => {
|
||||
// TODO(seam): Cover enrichAuthors, applyFilters, and applySort once the reactive service graph is isolated for deterministic assertions.
|
||||
});
|
||||
|
||||
it('needs browser-shell seams to verify selection, scroll restoration, route state, and thumbnail cache-busting behavior', () => {
|
||||
// TODO(seam): Cover the virtual-scroller and router orchestration after extracting those concerns behind testable adapters.
|
||||
});
|
||||
});
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
import {ChangeDetectorRef, SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Subject, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AuthorDetails, AuthorSummary} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorCardComponent} from './author-card.component';
|
||||
|
||||
describe('AuthorCardComponent', () => {
|
||||
let getAuthorThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
let quickMatchAuthor: ReturnType<typeof vi.fn>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let markForCheck: ReturnType<typeof vi.fn>;
|
||||
|
||||
const baseAuthor: AuthorSummary = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00ADA',
|
||||
bookCount: 12,
|
||||
hasPhoto: true,
|
||||
};
|
||||
|
||||
const createComponent = (overrides?: {
|
||||
author?: Partial<AuthorSummary>;
|
||||
canQuickMatch?: boolean;
|
||||
canDelete?: boolean;
|
||||
isSelected?: boolean;
|
||||
index?: number;
|
||||
cacheBuster?: number;
|
||||
}) => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorCardComponent());
|
||||
component.author = {
|
||||
...baseAuthor,
|
||||
...overrides?.author,
|
||||
};
|
||||
component.canQuickMatch = overrides?.canQuickMatch ?? false;
|
||||
component.canDelete = overrides?.canDelete ?? false;
|
||||
component.isSelected = overrides?.isSelected ?? false;
|
||||
component.index = overrides?.index ?? 0;
|
||||
component.cacheBuster = overrides?.cacheBuster ?? 0;
|
||||
return component;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
getAuthorThumbnailUrl = vi.fn((authorId: number, cacheBuster?: number) => `/authors/${authorId}/thumbnail?t=${cacheBuster ?? 'none'}`);
|
||||
quickMatchAuthor = vi.fn();
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
translate = vi.fn((key: string) => key);
|
||||
markForCheck = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
getAuthorThumbnailUrl,
|
||||
quickMatchAuthor,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: ChangeDetectorRef,
|
||||
useValue: {
|
||||
markForCheck,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('resets photo state only for meaningful author changes and later cache busters', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.ngOnChanges({
|
||||
author: new SimpleChange(baseAuthor, {...baseAuthor, name: 'Augusta Ada'}, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(false);
|
||||
|
||||
component.ngOnChanges({
|
||||
author: new SimpleChange(baseAuthor, {...baseAuthor, asin: 'B00NEW', hasPhoto: false}, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(false);
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.ngOnChanges({
|
||||
cacheBuster: new SimpleChange(0, 1, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
});
|
||||
|
||||
it('short-circuits clicks that start inside the menu button container', () => {
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.cardClick, 'emit');
|
||||
|
||||
const menuContainer = document.createElement('div');
|
||||
menuContainer.className = 'menu-button-container';
|
||||
const button = document.createElement('button');
|
||||
menuContainer.appendChild(button);
|
||||
|
||||
const event = new Event('click');
|
||||
const stopPropagationSpy = vi.spyOn(event, 'stopPropagation');
|
||||
Object.defineProperty(event, 'target', {
|
||||
configurable: true,
|
||||
value: button,
|
||||
});
|
||||
|
||||
component.onCardClick(event);
|
||||
|
||||
expect(stopPropagationSpy).not.toHaveBeenCalled();
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats modifier clicks as selection toggles instead of opening the author', () => {
|
||||
const component = createComponent({isSelected: false, index: 3});
|
||||
const checkboxEmitSpy = vi.spyOn(component.checkboxClick, 'emit');
|
||||
const cardEmitSpy = vi.spyOn(component.cardClick, 'emit');
|
||||
|
||||
const target = document.createElement('div');
|
||||
const event = new MouseEvent('click', {ctrlKey: true});
|
||||
const preventDefaultSpy = vi.spyOn(event, 'preventDefault');
|
||||
const stopPropagationSpy = vi.spyOn(event, 'stopPropagation');
|
||||
Object.defineProperty(event, 'target', {
|
||||
configurable: true,
|
||||
value: target,
|
||||
});
|
||||
|
||||
component.onCardClick(event);
|
||||
|
||||
expect(preventDefaultSpy).toHaveBeenCalledOnce();
|
||||
expect(stopPropagationSpy).toHaveBeenCalledOnce();
|
||||
expect(cardEmitSpy).not.toHaveBeenCalled();
|
||||
expect(checkboxEmitSpy).toHaveBeenCalledWith({
|
||||
index: 3,
|
||||
author: component.author,
|
||||
selected: true,
|
||||
shiftKey: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('emits cardClick for normal clicks outside the menu controls', () => {
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.cardClick, 'emit');
|
||||
|
||||
const event = new Event('click');
|
||||
const stopPropagationSpy = vi.spyOn(event, 'stopPropagation');
|
||||
Object.defineProperty(event, 'target', {
|
||||
configurable: true,
|
||||
value: document.createElement('div'),
|
||||
});
|
||||
|
||||
component.onCardClick(event);
|
||||
|
||||
expect(stopPropagationSpy).toHaveBeenCalledOnce();
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
});
|
||||
|
||||
it('captures shift state from checkbox clicks and reuses it for selection events', () => {
|
||||
const component = createComponent({index: 5});
|
||||
const emitSpy = vi.spyOn(component.checkboxClick, 'emit');
|
||||
|
||||
const mouseEvent = new MouseEvent('click', {shiftKey: true});
|
||||
const stopPropagationSpy = vi.spyOn(mouseEvent, 'stopPropagation');
|
||||
|
||||
component.captureMouseEvent(mouseEvent);
|
||||
component.toggleSelection({checked: true} as never);
|
||||
|
||||
expect(stopPropagationSpy).toHaveBeenCalledOnce();
|
||||
expect(emitSpy).toHaveBeenCalledWith({
|
||||
index: 5,
|
||||
author: component.author,
|
||||
selected: true,
|
||||
shiftKey: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('lazily initializes the menu once, marks for check, and toggles the Prime menu each time', () => {
|
||||
const component = createComponent({canQuickMatch: true, canDelete: true});
|
||||
const menu = {
|
||||
toggle: vi.fn(),
|
||||
};
|
||||
const event = new Event('click');
|
||||
|
||||
component.onMenuToggle(event, menu as never);
|
||||
component.onMenuToggle(event, menu as never);
|
||||
|
||||
expect(markForCheck).toHaveBeenCalledOnce();
|
||||
expect(menu.toggle).toHaveBeenCalledTimes(2);
|
||||
expect(component.items.map(item => item.label)).toEqual([
|
||||
'authorBrowser.card.menu.viewAuthor',
|
||||
'authorBrowser.card.menu.editAuthor',
|
||||
'authorBrowser.card.menu.quickMatch',
|
||||
'authorBrowser.card.menu.deleteAuthor',
|
||||
]);
|
||||
});
|
||||
|
||||
it('quick-matches through the lazy menu command and reports success state', () => {
|
||||
const quickMatch$ = new Subject<AuthorDetails>();
|
||||
quickMatchAuthor.mockReturnValue(quickMatch$);
|
||||
|
||||
const component = createComponent({canQuickMatch: true});
|
||||
const emitSpy = vi.spyOn(component.quickMatched, 'emit');
|
||||
|
||||
component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never);
|
||||
const quickMatchItem = component.items.find(item => item.label === 'authorBrowser.card.menu.quickMatch');
|
||||
|
||||
quickMatchItem?.command?.({originalEvent: new Event('click'), item: quickMatchItem});
|
||||
|
||||
expect(quickMatchAuthor).toHaveBeenCalledWith(9);
|
||||
expect(component.quickMatching).toBe(true);
|
||||
|
||||
quickMatch$.next({
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00MATCH',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: false,
|
||||
});
|
||||
quickMatch$.complete();
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(component.author).toEqual({
|
||||
...baseAuthor,
|
||||
asin: 'B00MATCH',
|
||||
hasPhoto: true,
|
||||
});
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.toast.quickMatchSuccessSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchSuccessDetail',
|
||||
});
|
||||
|
||||
component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never);
|
||||
expect(markForCheck).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('clears quickMatching and reports an error toast when quick match fails', () => {
|
||||
quickMatchAuthor.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = createComponent({canQuickMatch: true});
|
||||
const emitSpy = vi.spyOn(component.quickMatched, 'emit');
|
||||
|
||||
component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never);
|
||||
const quickMatchItem = component.items.find(item => item.label === 'authorBrowser.card.menu.quickMatch');
|
||||
|
||||
quickMatchItem?.command?.({originalEvent: new Event('click'), item: quickMatchItem});
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.toast.quickMatchFailedSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchFailedDetail',
|
||||
});
|
||||
});
|
||||
});
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
import {ElementRef, signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {ActivatedRoute, convertToParamMap, Router} from '@angular/router';
|
||||
import {Subject, of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import type {AuthorDetails} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
import {AuthorDetailComponent} from './author-detail.component';
|
||||
|
||||
describe('AuthorDetailComponent', () => {
|
||||
let getAuthorDetails: ReturnType<typeof vi.fn>;
|
||||
let getAuthorPhotoUrl: ReturnType<typeof vi.fn>;
|
||||
let patchAuthorInCache: ReturnType<typeof vi.fn>;
|
||||
let quickMatchAuthor: ReturnType<typeof vi.fn>;
|
||||
let getCurrentUser: ReturnType<typeof vi.fn>;
|
||||
let setPageTitle: ReturnType<typeof vi.fn>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let route: {
|
||||
snapshot: {
|
||||
paramMap: ReturnType<typeof convertToParamMap>;
|
||||
queryParamMap: ReturnType<typeof convertToParamMap>;
|
||||
};
|
||||
};
|
||||
|
||||
const baseAuthor: AuthorDetails = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
description: 'Analytical engine pioneer',
|
||||
asin: 'B00ADA',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: false,
|
||||
photoLocked: false,
|
||||
};
|
||||
|
||||
const setRouteState = (authorId = 9, tab?: string) => {
|
||||
route.snapshot.paramMap = convertToParamMap({authorId: String(authorId)});
|
||||
route.snapshot.queryParamMap = convertToParamMap(tab ? {tab} : {});
|
||||
};
|
||||
|
||||
const createComponent = () => TestBed.runInInjectionContext(() => new AuthorDetailComponent());
|
||||
|
||||
beforeEach(() => {
|
||||
getAuthorDetails = vi.fn();
|
||||
getAuthorPhotoUrl = vi.fn((authorId: number) => `/api/authors/${authorId}/photo`);
|
||||
patchAuthorInCache = vi.fn();
|
||||
quickMatchAuthor = vi.fn();
|
||||
getCurrentUser = vi.fn(() => null);
|
||||
setPageTitle = vi.fn();
|
||||
translate = vi.fn((key: string) => key);
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
route = {
|
||||
snapshot: {
|
||||
paramMap: convertToParamMap({authorId: '9'}),
|
||||
queryParamMap: convertToParamMap({}),
|
||||
},
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: route,
|
||||
},
|
||||
{
|
||||
provide: Router,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
getAuthorDetails,
|
||||
getAuthorPhotoUrl,
|
||||
patchAuthorInCache,
|
||||
quickMatchAuthor,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookService,
|
||||
useValue: {
|
||||
books: signal([]),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: CoverScalePreferenceService,
|
||||
useValue: {
|
||||
currentCardSize: vi.fn(() => 'medium'),
|
||||
gridColumnMinWidth: vi.fn(() => '12rem'),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookCardOverlayPreferenceService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {
|
||||
getCurrentUser,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: PageTitleService,
|
||||
useValue: {
|
||||
setPageTitle,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('loads the author from the route, honors the tab query param, and updates page title on success', () => {
|
||||
setRouteState(42, 'series');
|
||||
getAuthorDetails.mockReturnValue(of({...baseAuthor, id: 42, name: 'Grace Hopper'}));
|
||||
|
||||
const component = createComponent();
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(getAuthorDetails).toHaveBeenCalledWith(42);
|
||||
expect(component.tab).toBe('series');
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.author()).toEqual({...baseAuthor, id: 42, name: 'Grace Hopper'});
|
||||
expect(setPageTitle).toHaveBeenCalledWith('Grace Hopper');
|
||||
});
|
||||
|
||||
it('keeps the default tab and clears loading when author load fails', () => {
|
||||
setRouteState(9);
|
||||
getAuthorDetails.mockReturnValue(throwError(() => new Error('load failed')));
|
||||
|
||||
const component = createComponent();
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.tab).toBe('books');
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.author()).toBeNull();
|
||||
expect(setPageTitle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('derives photoUrl from the loaded author state and gates canEditMetadata from user permissions', () => {
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(321);
|
||||
const component = createComponent();
|
||||
|
||||
expect(component.photoUrl).toBe('');
|
||||
expect(component.canEditMetadata).toBe(false);
|
||||
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
expect(component.photoUrl).toBe('/api/authors/9/photo&t=321');
|
||||
|
||||
getCurrentUser.mockReturnValue({permissions: {admin: false, canEditMetadata: true}});
|
||||
expect(component.canEditMetadata).toBe(true);
|
||||
|
||||
getCurrentUser.mockReturnValue({permissions: {admin: true, canEditMetadata: false}});
|
||||
expect(component.canEditMetadata).toBe(true);
|
||||
});
|
||||
|
||||
it('detects description overflow from the assigned element ref only while collapsed', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.descriptionContentRef = {
|
||||
nativeElement: {
|
||||
scrollHeight: 120,
|
||||
clientHeight: 60,
|
||||
},
|
||||
} as unknown as ElementRef<HTMLElement>;
|
||||
|
||||
component.ngAfterViewChecked();
|
||||
|
||||
expect(component.isOverflowing).toBe(true);
|
||||
|
||||
component.isExpanded = true;
|
||||
component.descriptionContentRef = {
|
||||
nativeElement: {
|
||||
scrollHeight: 20,
|
||||
clientHeight: 80,
|
||||
},
|
||||
} as unknown as ElementRef<HTMLElement>;
|
||||
|
||||
component.ngAfterViewChecked();
|
||||
|
||||
expect(component.isOverflowing).toBe(true);
|
||||
});
|
||||
|
||||
it('patches the cached author summary and refreshes photo state when the author is updated', () => {
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(777);
|
||||
const component = createComponent();
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.photoTimestamp = 10;
|
||||
|
||||
component.onAuthorUpdated({
|
||||
...baseAuthor,
|
||||
asin: 'B00UPDATED',
|
||||
});
|
||||
|
||||
expect(component.author()).toEqual({
|
||||
...baseAuthor,
|
||||
asin: 'B00UPDATED',
|
||||
});
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(777);
|
||||
expect(patchAuthorInCache).toHaveBeenCalledWith(9, {
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00UPDATED',
|
||||
hasPhoto: true,
|
||||
});
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('guards quickMatch when there is no author loaded or a match is already in flight', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.quickMatch();
|
||||
expect(quickMatchAuthor).not.toHaveBeenCalled();
|
||||
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
vi.clearAllMocks();
|
||||
component.quickMatching = true;
|
||||
|
||||
component.quickMatch();
|
||||
|
||||
expect(quickMatchAuthor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('quick-matches the loaded author, patches state, and reports a translated success toast', () => {
|
||||
const quickMatch$ = new Subject<AuthorDetails>();
|
||||
const matchedAuthor: AuthorDetails = {
|
||||
...baseAuthor,
|
||||
asin: 'B00MATCH',
|
||||
};
|
||||
quickMatchAuthor.mockReturnValue(quickMatch$);
|
||||
|
||||
const component = createComponent();
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
vi.clearAllMocks();
|
||||
|
||||
component.quickMatch();
|
||||
|
||||
expect(quickMatchAuthor).toHaveBeenCalledWith(9);
|
||||
expect(component.quickMatching).toBe(true);
|
||||
|
||||
quickMatch$.next(matchedAuthor);
|
||||
quickMatch$.complete();
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(component.author()).toEqual(matchedAuthor);
|
||||
expect(patchAuthorInCache).toHaveBeenCalledWith(9, {
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00MATCH',
|
||||
hasPhoto: true,
|
||||
});
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchSuccessSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchSuccessDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.toast.quickMatchSuccessSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the in-flight quick-match flag and reports a translated error toast on failure', () => {
|
||||
quickMatchAuthor.mockReturnValue(throwError(() => new Error('quick match failed')));
|
||||
|
||||
const component = createComponent();
|
||||
component.onAuthorUpdated(baseAuthor);
|
||||
vi.clearAllMocks();
|
||||
|
||||
component.quickMatch();
|
||||
|
||||
expect(component.quickMatching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchFailedSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.toast.quickMatchFailedSummary',
|
||||
detail: 'authorBrowser.toast.quickMatchFailedDetail',
|
||||
});
|
||||
});
|
||||
});
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import {SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {Subject, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AuthorDetails} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorPhotoSearchComponent} from '../author-photo-search/author-photo-search.component';
|
||||
import {AuthorEditorComponent} from './author-editor.component';
|
||||
|
||||
describe('AuthorEditorComponent', () => {
|
||||
let updateAuthor: ReturnType<typeof vi.fn>;
|
||||
let dialogOpen: ReturnType<typeof vi.fn>;
|
||||
let dialogClose$: Subject<boolean>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
|
||||
const baseAuthor: AuthorDetails = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
description: 'Analytical engine pioneer',
|
||||
asin: 'B00ADA',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: false,
|
||||
photoLocked: false,
|
||||
};
|
||||
|
||||
const createComponent = (overrides?: {authorId?: number; author?: Partial<AuthorDetails>}) => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorEditorComponent());
|
||||
component.authorId = overrides?.authorId ?? 9;
|
||||
component.author = {
|
||||
...baseAuthor,
|
||||
...overrides?.author,
|
||||
};
|
||||
return component;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
updateAuthor = vi.fn();
|
||||
dialogClose$ = new Subject<boolean>();
|
||||
dialogOpen = vi.fn(() => ({onClose: dialogClose$}));
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
updateAuthor,
|
||||
getAuthorPhotoUrl: vi.fn((authorId: number) => `/api/authors/${authorId}/photo`),
|
||||
getUploadAuthorPhotoUrl: vi.fn((authorId: number) => `/api/authors/${authorId}/photo/upload`),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: DialogService,
|
||||
useValue: {
|
||||
open: dialogOpen,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('initializes the form and disables controls whose lock flags start enabled', () => {
|
||||
const component = createComponent({
|
||||
author: {
|
||||
nameLocked: true,
|
||||
asinLocked: true,
|
||||
},
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.form.get('name')?.value).toBe('Ada Lovelace');
|
||||
expect(component.form.get('description')?.value).toBe('Analytical engine pioneer');
|
||||
expect(component.form.get('asin')?.value).toBe('B00ADA');
|
||||
expect(component.form.get('name')?.disabled).toBe(true);
|
||||
expect(component.form.get('description')?.disabled).toBe(false);
|
||||
expect(component.form.get('asin')?.disabled).toBe(true);
|
||||
expect(component.form.get('photoLocked')?.value).toBe(false);
|
||||
});
|
||||
|
||||
it('restores photo state when a later author input change arrives', () => {
|
||||
const component = createComponent();
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(777);
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.photoTimestamp = 10;
|
||||
component.ngOnChanges({
|
||||
author: new SimpleChange(baseAuthor, {...baseAuthor, name: 'Updated Ada'}, false),
|
||||
});
|
||||
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(777);
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shapes the save request from raw form values, emits the updated author, and reports success', () => {
|
||||
const updatedAuthor: AuthorDetails = {
|
||||
...baseAuthor,
|
||||
description: 'Updated description',
|
||||
asin: 'B00NEW',
|
||||
nameLocked: true,
|
||||
asinLocked: true,
|
||||
photoLocked: true,
|
||||
};
|
||||
const save$ = new Subject<AuthorDetails>();
|
||||
updateAuthor.mockReturnValue(save$);
|
||||
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
|
||||
component.ngOnInit();
|
||||
component.form.patchValue({
|
||||
name: ' ',
|
||||
description: ' Updated description ',
|
||||
asin: ' B00NEW ',
|
||||
nameLocked: true,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: true,
|
||||
});
|
||||
|
||||
component.onSave();
|
||||
|
||||
expect(component.isSaving).toBe(true);
|
||||
expect(updateAuthor).toHaveBeenCalledWith(9, {
|
||||
name: undefined,
|
||||
description: 'Updated description',
|
||||
asin: 'B00NEW',
|
||||
nameLocked: true,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: true,
|
||||
});
|
||||
|
||||
save$.next(updatedAuthor);
|
||||
save$.complete();
|
||||
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(emitSpy).toHaveBeenCalledWith(updatedAuthor);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.editor.toast.successSummary',
|
||||
detail: 'authorBrowser.editor.toast.successDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the saving flag and reports an error toast when saveMetadata fails', () => {
|
||||
updateAuthor.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
component.ngOnInit();
|
||||
|
||||
component.onSave();
|
||||
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.editor.toast.errorSummary',
|
||||
detail: 'authorBrowser.editor.toast.errorDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('opens the photo search dialog and refreshes photo state when it closes with success', () => {
|
||||
const component = createComponent({authorId: 42});
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(888);
|
||||
|
||||
component.hasPhoto = false;
|
||||
component.photoTimestamp = 12;
|
||||
|
||||
component.openPhotoSearch();
|
||||
|
||||
expect(dialogOpen).toHaveBeenCalledWith(AuthorPhotoSearchComponent, {
|
||||
data: {authorId: 42, authorName: 'Ada Lovelace'},
|
||||
header: 'authorBrowser.editor.searchPhotoTitle',
|
||||
width: '70vw',
|
||||
height: '80vh',
|
||||
modal: true,
|
||||
closable: true,
|
||||
dismissableMask: true,
|
||||
contentStyle: {'overflow': 'hidden', 'padding': '0', 'display': 'flex', 'flex-direction': 'column'},
|
||||
});
|
||||
|
||||
dialogClose$.next(true);
|
||||
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(888);
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks upload success, refreshes the photo timestamp, and shows a success toast', () => {
|
||||
const component = createComponent();
|
||||
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(999);
|
||||
|
||||
component.isUploading = true;
|
||||
component.hasPhoto = false;
|
||||
|
||||
component.onUpload();
|
||||
|
||||
expect(component.isUploading).toBe(false);
|
||||
expect(component.hasPhoto).toBe(true);
|
||||
expect(component.photoTimestamp).toBe(999);
|
||||
expect(emitSpy).toHaveBeenCalledWith(component.author);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.editor.toast.photoUploadedSummary',
|
||||
detail: 'authorBrowser.editor.toast.photoUploadedDetail',
|
||||
});
|
||||
expect(nowSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears upload progress and shows an error toast when upload fails', () => {
|
||||
const component = createComponent();
|
||||
component.isUploading = true;
|
||||
|
||||
component.onUploadError();
|
||||
|
||||
expect(component.isUploading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.editor.toast.errorSummary',
|
||||
detail: 'authorBrowser.editor.toast.photoUploadErrorDetail',
|
||||
});
|
||||
});
|
||||
});
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Subject, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AuthorDetails, AuthorSearchResult} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorMatchComponent} from './author-match.component';
|
||||
|
||||
describe('AuthorMatchComponent', () => {
|
||||
let searchAuthorMetadata: ReturnType<typeof vi.fn>;
|
||||
let matchAuthor: ReturnType<typeof vi.fn>;
|
||||
let messageService: Pick<MessageService, 'add'>;
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
|
||||
const createComponent = (overrides?: {authorId?: number; authorName?: string}) => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorMatchComponent());
|
||||
component.authorId = overrides?.authorId ?? 9;
|
||||
component.authorName = overrides?.authorName ?? 'Ada Lovelace';
|
||||
return component;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
searchAuthorMetadata = vi.fn();
|
||||
matchAuthor = vi.fn();
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
searchAuthorMetadata,
|
||||
matchAuthor,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MessageService,
|
||||
useValue: messageService,
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('bootstraps searchQuery from authorName and gates canSearch on trimmed query inputs', () => {
|
||||
const component = createComponent({authorName: ' Ada Lovelace '});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.searchQuery).toBe(' Ada Lovelace ');
|
||||
expect(component.canSearch).toBe(true);
|
||||
|
||||
component.searchQuery = ' ';
|
||||
component.asinQuery = ' ';
|
||||
expect(component.canSearch).toBe(false);
|
||||
|
||||
component.asinQuery = ' B00TEST ';
|
||||
expect(component.canSearch).toBe(true);
|
||||
});
|
||||
|
||||
it('does not search when both query inputs are blank after trimming', () => {
|
||||
const component = createComponent();
|
||||
component.searchQuery = ' ';
|
||||
component.asinQuery = ' ';
|
||||
component.results = [{source: 'seed', asin: 'old', name: 'Existing'}];
|
||||
|
||||
component.search();
|
||||
|
||||
expect(searchAuthorMetadata).not.toHaveBeenCalled();
|
||||
expect(component.searching).toBe(false);
|
||||
expect(component.hasSearched).toBe(false);
|
||||
expect(component.results).toEqual([{source: 'seed', asin: 'old', name: 'Existing'}]);
|
||||
});
|
||||
|
||||
it('searches with trimmed values, clears stale results, and stores returned matches', () => {
|
||||
const results$ = new Subject<AuthorSearchResult[]>();
|
||||
searchAuthorMetadata.mockReturnValue(results$);
|
||||
|
||||
const component = createComponent();
|
||||
component.searchQuery = ' Ada ';
|
||||
component.asinQuery = ' B00MATCH ';
|
||||
component.selectedRegion = 'uk';
|
||||
component.results = [{source: 'seed', asin: 'old', name: 'Existing'}];
|
||||
|
||||
component.search();
|
||||
|
||||
expect(searchAuthorMetadata).toHaveBeenCalledWith(9, 'Ada', 'uk', 'B00MATCH');
|
||||
expect(component.searching).toBe(true);
|
||||
expect(component.hasSearched).toBe(true);
|
||||
expect(component.results).toEqual([]);
|
||||
|
||||
results$.next([
|
||||
{source: 'amazon', asin: 'B00MATCH', name: 'Ada Lovelace'},
|
||||
{source: 'amazon', asin: 'B00OTHER', name: 'A. Lovelace'},
|
||||
]);
|
||||
results$.complete();
|
||||
|
||||
expect(component.results).toEqual([
|
||||
{source: 'amazon', asin: 'B00MATCH', name: 'Ada Lovelace'},
|
||||
{source: 'amazon', asin: 'B00OTHER', name: 'A. Lovelace'},
|
||||
]);
|
||||
expect(component.searching).toBe(false);
|
||||
});
|
||||
|
||||
it('reports a translated search failure toast when metadata search errors', () => {
|
||||
searchAuthorMetadata.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = createComponent();
|
||||
component.searchQuery = 'Ada';
|
||||
|
||||
component.search();
|
||||
|
||||
expect(component.searching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.searchFailedSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.searchFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.match.toast.searchFailedSummary',
|
||||
detail: 'authorBrowser.match.toast.searchFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('shapes the match request, emits the updated author, and reports success on matchAuthor', () => {
|
||||
const updatedAuthor: AuthorDetails = {
|
||||
id: 9,
|
||||
name: 'Ada Lovelace',
|
||||
asin: 'B00MATCH',
|
||||
nameLocked: false,
|
||||
descriptionLocked: false,
|
||||
asinLocked: true,
|
||||
photoLocked: false,
|
||||
};
|
||||
const match$ = new Subject<AuthorDetails>();
|
||||
matchAuthor.mockReturnValue(match$);
|
||||
|
||||
const component = createComponent();
|
||||
component.selectedRegion = 'de';
|
||||
const emitSpy = vi.spyOn(component.authorMatched, 'emit');
|
||||
|
||||
component.matchAuthor({
|
||||
source: 'amazon',
|
||||
asin: 'B00MATCH',
|
||||
name: 'Ada Lovelace',
|
||||
description: 'Pioneer',
|
||||
});
|
||||
|
||||
expect(matchAuthor).toHaveBeenCalledWith(9, {
|
||||
source: 'amazon',
|
||||
asin: 'B00MATCH',
|
||||
region: 'de',
|
||||
});
|
||||
expect(component.matching).toBe(true);
|
||||
|
||||
match$.next(updatedAuthor);
|
||||
match$.complete();
|
||||
|
||||
expect(component.matching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchSuccessSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchSuccessDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.match.toast.matchSuccessSummary',
|
||||
detail: 'authorBrowser.match.toast.matchSuccessDetail',
|
||||
life: 3000,
|
||||
});
|
||||
expect(emitSpy).toHaveBeenCalledWith(updatedAuthor);
|
||||
});
|
||||
|
||||
it('reports a translated failure toast when matchAuthor errors', () => {
|
||||
matchAuthor.mockReturnValue(throwError(() => new Error('nope')));
|
||||
|
||||
const component = createComponent();
|
||||
|
||||
component.matchAuthor({
|
||||
source: 'amazon',
|
||||
asin: 'B00FAIL',
|
||||
name: 'Ada Lovelace',
|
||||
});
|
||||
|
||||
expect(component.matching).toBe(false);
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchFailedSummary');
|
||||
expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'authorBrowser.match.toast.matchFailedSummary',
|
||||
detail: 'authorBrowser.match.toast.matchFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
});
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import type {AuthorPhotoResult} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorPhotoSearchComponent} from './author-photo-search.component';
|
||||
import {
|
||||
createDynamicDialogHarness,
|
||||
createMessageServiceProvider,
|
||||
createMessageServiceSpy,
|
||||
} from '../../../../core/testing/dialog-testing';
|
||||
|
||||
describe('AuthorPhotoSearchComponent', () => {
|
||||
let searchAuthorPhotos: ReturnType<typeof vi.fn>;
|
||||
let uploadAuthorPhotoFromUrl: ReturnType<typeof vi.fn>;
|
||||
let dialogHarness: ReturnType<typeof createDynamicDialogHarness<{authorId: number; authorName?: string}>>;
|
||||
let messageService: ReturnType<typeof createMessageServiceSpy>;
|
||||
|
||||
beforeEach(() => {
|
||||
searchAuthorPhotos = vi.fn(() => of([]));
|
||||
uploadAuthorPhotoFromUrl = vi.fn(() => of(undefined));
|
||||
dialogHarness = createDynamicDialogHarness({authorId: 9, authorName: 'Ada'});
|
||||
messageService = createMessageServiceSpy();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...dialogHarness.providers,
|
||||
{
|
||||
provide: AuthorService,
|
||||
useValue: {
|
||||
searchAuthorPhotos,
|
||||
uploadAuthorPhotoFromUrl,
|
||||
},
|
||||
},
|
||||
createMessageServiceProvider(messageService),
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate: (<T = string>(key: string) => key as T) as TranslocoService['translate'],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('hydrates the initial author query, performs the bootstrap search, and sorts the returned photos', () => {
|
||||
searchAuthorPhotos.mockReturnValue(of<AuthorPhotoResult[]>([
|
||||
{index: 3, url: 'three', width: 300, height: 400},
|
||||
{index: 1, url: 'one', width: 100, height: 200},
|
||||
{index: 2, url: 'two', width: 200, height: 300},
|
||||
]));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent());
|
||||
component.ngOnInit();
|
||||
|
||||
expect(searchAuthorPhotos).toHaveBeenCalledWith(9, 'Ada');
|
||||
expect(component.searchForm.value.query).toBe('Ada');
|
||||
expect(component.photos.map(photo => photo.index)).toEqual([1, 2, 3]);
|
||||
expect(component.hasSearched).toBe(true);
|
||||
expect(component.searching).toBe(false);
|
||||
});
|
||||
|
||||
it('clears results when searching fails and resets the form state on clear', () => {
|
||||
searchAuthorPhotos.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent());
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.photos).toEqual([]);
|
||||
expect(component.hasSearched).toBe(true);
|
||||
|
||||
component.onClear();
|
||||
|
||||
expect(component.searchForm.value.query).toBeNull();
|
||||
expect(component.photos).toEqual([]);
|
||||
expect(component.hasSearched).toBe(false);
|
||||
});
|
||||
|
||||
it('uploads a selected photo, reports success, and closes the dialog', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent());
|
||||
component.ngOnInit();
|
||||
|
||||
component.selectAndUploadPhoto({index: 1, url: 'https://example.com/photo.jpg', width: 640, height: 480});
|
||||
|
||||
expect(uploadAuthorPhotoFromUrl).toHaveBeenCalledWith(9, 'https://example.com/photo.jpg');
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'authorBrowser.editor.toast.photoUploadedSummary',
|
||||
}));
|
||||
expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {
|
||||
AuthorDetails,
|
||||
AuthorFilters,
|
||||
AuthorMatchRequest,
|
||||
AuthorSummary,
|
||||
AuthorUpdateRequest,
|
||||
DEFAULT_AUTHOR_FILTERS,
|
||||
EnrichedAuthor
|
||||
} from './author.model';
|
||||
|
||||
describe('author.model', () => {
|
||||
it('provides all-author defaults for author filtering', () => {
|
||||
expect(DEFAULT_AUTHOR_FILTERS).toEqual({
|
||||
matchStatus: 'all',
|
||||
photoStatus: 'all',
|
||||
readStatus: 'all',
|
||||
bookCount: 'all',
|
||||
library: 'all',
|
||||
genre: 'all'
|
||||
} satisfies AuthorFilters);
|
||||
});
|
||||
|
||||
it('supports enriched authors extending the summary shape', () => {
|
||||
const enriched: EnrichedAuthor = {
|
||||
id: 7,
|
||||
name: 'Ursula K. Le Guin',
|
||||
bookCount: 12,
|
||||
hasPhoto: true,
|
||||
libraryIds: new Set([1, 2]),
|
||||
libraryNames: ['Main', 'Archive'],
|
||||
categories: ['Fantasy', 'Sci-Fi'],
|
||||
readStatus: 'some-read',
|
||||
hasSeries: true,
|
||||
seriesCount: 2,
|
||||
latestAddedOn: '2026-03-26',
|
||||
lastReadTime: '2026-03-25T20:15:00Z',
|
||||
readingProgress: 75,
|
||||
avgPersonalRating: 4.5
|
||||
};
|
||||
|
||||
expect(enriched.libraryIds.has(2)).toBe(true);
|
||||
expect(enriched.readStatus).toBe('some-read');
|
||||
expectTypeOf(enriched).toMatchTypeOf<AuthorSummary>();
|
||||
});
|
||||
|
||||
it('keeps author request and update payloads structurally typed', () => {
|
||||
const matchRequest: AuthorMatchRequest = {
|
||||
source: 'hardcover',
|
||||
asin: 'B001234',
|
||||
region: 'US'
|
||||
};
|
||||
const updateRequest: AuthorUpdateRequest = {
|
||||
name: 'New Name',
|
||||
descriptionLocked: true
|
||||
};
|
||||
const details: AuthorDetails = {
|
||||
id: 4,
|
||||
name: 'Author',
|
||||
nameLocked: false,
|
||||
descriptionLocked: true,
|
||||
asinLocked: false,
|
||||
photoLocked: false
|
||||
};
|
||||
|
||||
expect(matchRequest.region).toBe('US');
|
||||
expect(updateRequest.descriptionLocked).toBe(true);
|
||||
expect(details.nameLocked).toBe(false);
|
||||
expectTypeOf(updateRequest.name).toEqualTypeOf<string | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {AUTHORS_QUERY_KEY} from './author-query-keys';
|
||||
import {patchAuthorInCache} from './author-query-cache';
|
||||
|
||||
describe('patchAuthorInCache', () => {
|
||||
it('patches the matching author while keeping the rest intact', () => {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(AUTHORS_QUERY_KEY, [
|
||||
{id: 1, name: 'Ada', bookCount: 1, hasPhoto: false},
|
||||
{id: 2, name: 'Bert', bookCount: 2, hasPhoto: true},
|
||||
]);
|
||||
|
||||
patchAuthorInCache(queryClient, 2, {name: 'Bert Updated', hasPhoto: false});
|
||||
|
||||
expect(queryClient.getQueryData(AUTHORS_QUERY_KEY)).toEqual([
|
||||
{id: 1, name: 'Ada', bookCount: 1, hasPhoto: false},
|
||||
{id: 2, name: 'Bert Updated', bookCount: 2, hasPhoto: false},
|
||||
]);
|
||||
});
|
||||
|
||||
it('initializes an empty cache when there is no existing author list', () => {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
patchAuthorInCache(queryClient, 3, {name: 'Cy'});
|
||||
|
||||
expect(queryClient.getQueryData(AUTHORS_QUERY_KEY)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {AUTHORS_QUERY_KEY} from './author-query-keys';
|
||||
|
||||
describe('AUTHORS_QUERY_KEY', () => {
|
||||
it('uses a stable cache key for the author browser', () => {
|
||||
expect(AUTHORS_QUERY_KEY).toEqual(['authors']);
|
||||
});
|
||||
});
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
||||
import {AuthorScalePreferenceService} from './author-scale-preference.service';
|
||||
|
||||
describe('AuthorScalePreferenceService', () => {
|
||||
const localStorageService = {
|
||||
get: vi.fn(),
|
||||
set: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.restoreAllMocks();
|
||||
localStorageService.get.mockReset();
|
||||
localStorageService.set.mockReset();
|
||||
localStorageService.get.mockReturnValue(1.5);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
AuthorScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the persisted scale and does not persist unchanged values', () => {
|
||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
||||
|
||||
expect(service.scaleFactor()).toBe(1.5);
|
||||
|
||||
service.setScale(1.5);
|
||||
vi.runAllTimers();
|
||||
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('debounces and persists the most recent scale value', () => {
|
||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
||||
|
||||
service.setScale(1.2);
|
||||
service.setScale(1.4);
|
||||
|
||||
vi.advanceTimersByTime(999);
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
|
||||
expect(localStorageService.set).toHaveBeenCalledOnce();
|
||||
expect(localStorageService.set).toHaveBeenCalledWith('authorScalePreference', 1.4);
|
||||
});
|
||||
|
||||
it('falls back to the default scale when storage contains an invalid value', () => {
|
||||
localStorageService.get.mockReturnValue(Number.NaN);
|
||||
|
||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
||||
|
||||
expect(service.scaleFactor()).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {AuthorSelectionService} from './author-selection.service';
|
||||
|
||||
describe('AuthorSelectionService', () => {
|
||||
const authors = [
|
||||
{id: 1, name: 'Ada', bookCount: 1, hasPhoto: false},
|
||||
{id: 2, name: 'Bert', bookCount: 2, hasPhoto: true},
|
||||
{id: 3, name: 'Cy', bookCount: 3, hasPhoto: false},
|
||||
{id: 4, name: 'Dee', bookCount: 4, hasPhoto: true},
|
||||
];
|
||||
|
||||
it('selects and deselects authors and exposes the selected count', () => {
|
||||
const service = new AuthorSelectionService();
|
||||
service.setCurrentAuthors(authors);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 1,
|
||||
author: authors[1],
|
||||
selected: true,
|
||||
shiftKey: false,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([2]);
|
||||
expect(service.selectedCount()).toBe(1);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 1,
|
||||
author: authors[1],
|
||||
selected: false,
|
||||
shiftKey: false,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([]);
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('supports shift-click range selection and deselection', () => {
|
||||
const service = new AuthorSelectionService();
|
||||
service.setCurrentAuthors(authors);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 1,
|
||||
author: authors[1],
|
||||
selected: true,
|
||||
shiftKey: false,
|
||||
});
|
||||
service.handleCheckboxClick({
|
||||
index: 3,
|
||||
author: authors[3],
|
||||
selected: true,
|
||||
shiftKey: true,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([2, 3, 4]);
|
||||
|
||||
service.handleCheckboxClick({
|
||||
index: 2,
|
||||
author: authors[2],
|
||||
selected: false,
|
||||
shiftKey: true,
|
||||
});
|
||||
|
||||
expect(service.getSelectedIds()).toEqual([4]);
|
||||
});
|
||||
|
||||
it('selects and clears the full current author list', () => {
|
||||
const service = new AuthorSelectionService();
|
||||
service.setCurrentAuthors(authors);
|
||||
|
||||
service.selectAll();
|
||||
expect(service.getSelectedIds()).toEqual([1, 2, 3, 4]);
|
||||
|
||||
service.deselectAll();
|
||||
expect(service.getSelectedIds()).toEqual([]);
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {SseClient} from 'ngx-sse-client';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {AuthorService} from './author.service';
|
||||
|
||||
describe('AuthorService', () => {
|
||||
const httpClient = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
};
|
||||
|
||||
const authService = {
|
||||
token: vi.fn(),
|
||||
getInternalAccessToken: vi.fn(),
|
||||
};
|
||||
|
||||
const sseClient = {
|
||||
stream: vi.fn(),
|
||||
};
|
||||
|
||||
const queryClient = {
|
||||
removeQueries: vi.fn(),
|
||||
invalidateQueries: vi.fn(),
|
||||
};
|
||||
|
||||
let service: AuthorService;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClient.get.mockReset();
|
||||
httpClient.post.mockReset();
|
||||
httpClient.put.mockReset();
|
||||
httpClient.delete.mockReset();
|
||||
authService.token.mockReset();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
sseClient.stream.mockReset();
|
||||
queryClient.removeQueries.mockReset();
|
||||
queryClient.invalidateQueries.mockReset();
|
||||
|
||||
authService.token.mockReturnValue('token-123');
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
httpClient.get.mockReturnValue(of([]));
|
||||
httpClient.post.mockReturnValue(of({}));
|
||||
httpClient.put.mockReturnValue(of({}));
|
||||
httpClient.delete.mockReturnValue(of(undefined));
|
||||
sseClient.stream.mockReturnValue(of({type: 'message', data: '{"id":7,"name":"Ada"}'}));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
AuthorService,
|
||||
{provide: HttpClient, useValue: httpClient},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: SseClient, useValue: sseClient},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(AuthorService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('builds metadata search params with q or asin depending on the request', () => {
|
||||
service.searchAuthorMetadata(9, 'Ada', 'us');
|
||||
|
||||
expect(httpClient.get).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/9/search-metadata`,
|
||||
{params: {region: 'us', q: 'Ada'}},
|
||||
);
|
||||
|
||||
service.searchAuthorMetadata(9, 'Ada', 'us', 'B000123');
|
||||
|
||||
expect(httpClient.get).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/9/search-metadata`,
|
||||
{params: {region: 'us', asin: 'B000123'}},
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the default region for quick matches and preserves custom regions', () => {
|
||||
service.quickMatchAuthor(11);
|
||||
service.quickMatchAuthor(11, 'gb');
|
||||
|
||||
expect(httpClient.post).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/11/quick-match`,
|
||||
null,
|
||||
{params: {region: 'us'}},
|
||||
);
|
||||
expect(httpClient.post).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/11/quick-match`,
|
||||
null,
|
||||
{params: {region: 'gb'}},
|
||||
);
|
||||
});
|
||||
|
||||
it('maps SSE auto-match responses and throws on error events', () => {
|
||||
sseClient.stream.mockReturnValueOnce(of({type: 'message', data: '{"id":3,"name":"Grace"}'}));
|
||||
|
||||
const results: unknown[] = [];
|
||||
service.autoMatchAuthors([1, 2]).subscribe(value => results.push(value));
|
||||
|
||||
expect(sseClient.stream).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/authors/auto-match`,
|
||||
expect.objectContaining({keepAlive: false, reconnectionDelay: 1000, responseType: 'event'}),
|
||||
expect.objectContaining({
|
||||
body: [1, 2],
|
||||
withCredentials: true,
|
||||
}),
|
||||
'POST',
|
||||
);
|
||||
expect(results).toEqual([{id: 3, name: 'Grace'}]);
|
||||
|
||||
sseClient.stream.mockReturnValueOnce(of({type: 'error', message: 'boom'}));
|
||||
|
||||
const errors: Error[] = [];
|
||||
service.autoMatchAuthors([7]).subscribe({
|
||||
next: () => undefined,
|
||||
error: error => errors.push(error),
|
||||
});
|
||||
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]).toEqual(new Error('boom'));
|
||||
});
|
||||
|
||||
it('builds tokenized author media urls with and without cache busters', () => {
|
||||
expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo?token=token-123`);
|
||||
expect(service.getAuthorThumbnailUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123`);
|
||||
expect(service.getAuthorThumbnailUrl(5, 99)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123&t=99`);
|
||||
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo`);
|
||||
expect(service.getAuthorThumbnailUrl(5, 99)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?t=99`);
|
||||
});
|
||||
});
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import type {AutoCompleteCompleteEvent} from 'primeng/autocomplete';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, Subject, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {Book, BookMetadata} from '../../model/book.model';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {BookMetadataService} from '../../service/book-metadata.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {AddPhysicalBookDialogComponent} from './add-physical-book-dialog.component';
|
||||
|
||||
describe('AddPhysicalBookDialogComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createLibrary(overrides: Partial<Library> = {}): Library {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'Main Library',
|
||||
watch: true,
|
||||
paths: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 99,
|
||||
libraryId: 2,
|
||||
libraryName: 'Branch Library',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createMetadata(overrides: Partial<BookMetadata> = {}): BookMetadata {
|
||||
return {
|
||||
bookId: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(options: {
|
||||
dialogData?: {libraryId?: number};
|
||||
librariesData?: Library[];
|
||||
metadataValues?: {
|
||||
authors: string[];
|
||||
categories: string[];
|
||||
moods: string[];
|
||||
tags: string[];
|
||||
publishers: string[];
|
||||
series: string[];
|
||||
};
|
||||
lookupResult$?: Observable<BookMetadata>;
|
||||
createResult$?: Observable<Book>;
|
||||
} = {}) {
|
||||
const libraries = signal<Library[]>(options.librariesData ?? [
|
||||
createLibrary({id: 1, name: 'Main Library'}),
|
||||
createLibrary({id: 2, name: 'Branch Library'}),
|
||||
]);
|
||||
const uniqueMetadata = signal(options.metadataValues ?? {
|
||||
authors: ['Ursula Le Guin', 'Octavia Butler', 'Robin Hobb'],
|
||||
categories: ['Science Fiction', 'Epic Fantasy', 'Mystery'],
|
||||
moods: [],
|
||||
tags: [],
|
||||
publishers: [],
|
||||
series: [],
|
||||
});
|
||||
const lookupResult$ = options.lookupResult$ ?? new Subject<BookMetadata>();
|
||||
const createResult$ = options.createResult$ ?? new Subject<Book>();
|
||||
const lookupByIsbn = vi.fn(() => lookupResult$);
|
||||
const createPhysicalBook = vi.fn(() => createResult$);
|
||||
const dialogRef = {close: vi.fn()};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: DynamicDialogConfig, useValue: {data: options.dialogData ?? {}}},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: BookService, useValue: {uniqueMetadata, createPhysicalBook}},
|
||||
{provide: BookMetadataService, useValue: {lookupByIsbn}},
|
||||
{provide: LibraryService, useValue: {libraries}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new AddPhysicalBookDialogComponent());
|
||||
TestBed.flushEffects();
|
||||
|
||||
return {
|
||||
component,
|
||||
libraries,
|
||||
uniqueMetadata,
|
||||
lookupResult$,
|
||||
createResult$,
|
||||
lookupByIsbn,
|
||||
createPhysicalBook,
|
||||
dialogRef,
|
||||
};
|
||||
}
|
||||
|
||||
function triggerEnter(component: AddPhysicalBookDialogComponent, fieldName: 'authors' | 'categories', value: string): HTMLInputElement {
|
||||
const input = document.createElement('input');
|
||||
input.value = value;
|
||||
|
||||
component.onAutoCompleteKeyUp(fieldName, {
|
||||
key: 'Enter',
|
||||
target: input,
|
||||
} as unknown as KeyboardEvent);
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
function triggerSelect(component: AddPhysicalBookDialogComponent, fieldName: 'authors' | 'categories', value: string): HTMLInputElement {
|
||||
const input = document.createElement('input');
|
||||
input.value = value;
|
||||
|
||||
component.onAutoCompleteSelect(fieldName, {
|
||||
value,
|
||||
originalEvent: {target: input} as unknown as Event,
|
||||
});
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
it('prefers the dialog library selection when one is provided', () => {
|
||||
const {component} = createHarness({
|
||||
dialogData: {libraryId: 2},
|
||||
});
|
||||
|
||||
expect(component.selectedLibraryId).toBe(2);
|
||||
});
|
||||
|
||||
it('defaults to the first available library when the dialog does not provide one', () => {
|
||||
const {component} = createHarness({
|
||||
dialogData: {},
|
||||
});
|
||||
|
||||
expect(component.selectedLibraryId).toBe(1);
|
||||
});
|
||||
|
||||
it('filters authors and categories with case-insensitive substring matches', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
component.filterAuthors({query: 'taV', originalEvent: new Event('input')} as AutoCompleteCompleteEvent);
|
||||
component.filterCategories({query: 'fic', originalEvent: new Event('input')} as AutoCompleteCompleteEvent);
|
||||
|
||||
expect(component.filteredAuthors).toEqual(['Octavia Butler']);
|
||||
expect(component.filteredCategories).toEqual(['Science Fiction']);
|
||||
});
|
||||
|
||||
it('adds entered autocomplete values once and clears the input after Enter', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
const firstInput = triggerEnter(component, 'authors', ' N. K. Jemisin ');
|
||||
const duplicateInput = triggerEnter(component, 'authors', 'N. K. Jemisin');
|
||||
|
||||
expect(component.authors).toEqual(['N. K. Jemisin']);
|
||||
expect(firstInput.value).toBe('');
|
||||
expect(duplicateInput.value).toBe('');
|
||||
});
|
||||
|
||||
it('adds selected autocomplete values once and clears the input after selection', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
const firstInput = triggerSelect(component, 'categories', 'Mythic Fantasy');
|
||||
const duplicateInput = triggerSelect(component, 'categories', 'Mythic Fantasy');
|
||||
|
||||
expect(component.categories).toEqual(['Mythic Fantasy']);
|
||||
expect(firstInput.value).toBe('');
|
||||
expect(duplicateInput.value).toBe('');
|
||||
});
|
||||
|
||||
it('trims the isbn, hydrates metadata fields, and clears the fetching flag on success', () => {
|
||||
const lookupResult$ = new Subject<BookMetadata>();
|
||||
const {component, lookupByIsbn} = createHarness({lookupResult$});
|
||||
|
||||
component.isbn = ' 9780441172719 ';
|
||||
component.fetchMetadataByIsbn();
|
||||
|
||||
expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719');
|
||||
expect(component.isFetchingMetadata).toBe(true);
|
||||
|
||||
lookupResult$.next(createMetadata({
|
||||
title: 'Dune',
|
||||
authors: ['Frank Herbert'],
|
||||
description: 'Arrakis.',
|
||||
publisher: 'Ace',
|
||||
publishedDate: '1965',
|
||||
language: 'en',
|
||||
pageCount: 412,
|
||||
categories: ['Science Fiction'],
|
||||
thumbnailUrl: 'https://covers.example/dune.jpg',
|
||||
}));
|
||||
lookupResult$.complete();
|
||||
|
||||
expect(component.title).toBe('Dune');
|
||||
expect(component.authors).toEqual(['Frank Herbert']);
|
||||
expect(component.description).toBe('Arrakis.');
|
||||
expect(component.publisher).toBe('Ace');
|
||||
expect(component.publishedDate).toBe('1965');
|
||||
expect(component.language).toBe('en');
|
||||
expect(component.pageCount).toBe(412);
|
||||
expect(component.categories).toEqual(['Science Fiction']);
|
||||
expect(component.coverUrl).toBe('https://covers.example/dune.jpg');
|
||||
expect(component.isFetchingMetadata).toBe(false);
|
||||
});
|
||||
|
||||
it('does not start isbn lookup for blank or in-flight requests and clears the flag on error', () => {
|
||||
const {component, lookupByIsbn} = createHarness();
|
||||
|
||||
component.isbn = ' ';
|
||||
component.fetchMetadataByIsbn();
|
||||
expect(lookupByIsbn).not.toHaveBeenCalled();
|
||||
|
||||
component.isbn = '9780441172719';
|
||||
component.isFetchingMetadata = true;
|
||||
component.fetchMetadataByIsbn();
|
||||
expect(lookupByIsbn).not.toHaveBeenCalled();
|
||||
|
||||
component.isFetchingMetadata = false;
|
||||
lookupByIsbn.mockReturnValueOnce(throwError(() => new Error('lookup failed')));
|
||||
|
||||
component.fetchMetadataByIsbn();
|
||||
|
||||
expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719');
|
||||
expect(component.isFetchingMetadata).toBe(false);
|
||||
});
|
||||
|
||||
it('gates creation on required fields and does not submit when already loading', () => {
|
||||
const {component, createPhysicalBook} = createHarness();
|
||||
|
||||
expect(component.canCreate()).toBe(false);
|
||||
component.createBook();
|
||||
expect(createPhysicalBook).not.toHaveBeenCalled();
|
||||
|
||||
component.selectedLibraryId = 2;
|
||||
component.title = 'Physical Copy';
|
||||
expect(component.canCreate()).toBe(true);
|
||||
|
||||
component.isLoading = true;
|
||||
component.createBook();
|
||||
|
||||
expect(createPhysicalBook).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shapes the create payload, resets loading, and closes with the created book on success', () => {
|
||||
const createResult$ = new Subject<Book>();
|
||||
const createdBook = createBook({
|
||||
id: 321,
|
||||
libraryId: 2,
|
||||
libraryName: 'Branch Library',
|
||||
metadata: {bookId: 321, title: 'The Left Hand of Darkness'},
|
||||
});
|
||||
const {component, createPhysicalBook, dialogRef} = createHarness({createResult$});
|
||||
|
||||
component.selectedLibraryId = 2;
|
||||
component.title = ' The Left Hand of Darkness ';
|
||||
component.isbn = ' ';
|
||||
component.authors = ['Ursula Le Guin'];
|
||||
component.description = ' ';
|
||||
component.publisher = ' Ace Books ';
|
||||
component.publishedDate = ' 1969 ';
|
||||
component.language = ' en ';
|
||||
component.pageCount = 304;
|
||||
component.categories = ['Science Fiction'];
|
||||
component.coverUrl = 'https://covers.example/left-hand.jpg';
|
||||
|
||||
component.createBook();
|
||||
|
||||
expect(component.isLoading).toBe(true);
|
||||
expect(createPhysicalBook).toHaveBeenCalledWith({
|
||||
libraryId: 2,
|
||||
title: 'The Left Hand of Darkness',
|
||||
isbn: undefined,
|
||||
authors: ['Ursula Le Guin'],
|
||||
description: undefined,
|
||||
publisher: 'Ace Books',
|
||||
publishedDate: '1969',
|
||||
language: 'en',
|
||||
pageCount: 304,
|
||||
categories: ['Science Fiction'],
|
||||
thumbnailUrl: 'https://covers.example/left-hand.jpg',
|
||||
});
|
||||
|
||||
createResult$.next(createdBook);
|
||||
createResult$.complete();
|
||||
|
||||
expect(component.isLoading).toBe(false);
|
||||
expect(dialogRef.close).toHaveBeenCalledWith(createdBook);
|
||||
});
|
||||
|
||||
it('resets loading and keeps the dialog open when create fails', () => {
|
||||
const {component, createPhysicalBook, dialogRef} = createHarness();
|
||||
createPhysicalBook.mockReturnValueOnce(throwError(() => new Error('create failed')));
|
||||
|
||||
component.selectedLibraryId = 2;
|
||||
component.isbn = '9780441172719';
|
||||
|
||||
component.createBook();
|
||||
|
||||
expect(createPhysicalBook).toHaveBeenCalledWith({
|
||||
libraryId: 2,
|
||||
title: undefined,
|
||||
isbn: '9780441172719',
|
||||
authors: undefined,
|
||||
description: undefined,
|
||||
publisher: undefined,
|
||||
publishedDate: undefined,
|
||||
language: undefined,
|
||||
pageCount: undefined,
|
||||
categories: undefined,
|
||||
thumbnailUrl: undefined,
|
||||
});
|
||||
expect(component.isLoading).toBe(false);
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around PrimeNG file-upload callbacks,
|
||||
// dialog bootstrapping, and upload stream orchestration so single-file validation and upload state
|
||||
// transitions can be asserted without browser File objects and the live upload widget runtime.
|
||||
describe.skip('AdditionalFileUploaderComponent', () => {
|
||||
it('needs upload-widget seams to verify file-type resets, size validation, and file list management', () => {
|
||||
// TODO(seam): Cover onFileTypeChange, onFilesSelect, onClear, and badge/status helpers after FileUpload callbacks and browser File objects are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs upload-service seams to verify upload success, upload failure, and dialog close behavior', () => {
|
||||
// TODO(seam): Cover uploadFiles and closeDialog after BookFileService streams and dialog refs are exposed through a stable test harness.
|
||||
});
|
||||
});
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {convertToParamMap} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookBrowserEntityService} from './book-browser-entity.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {EntityType} from './book-browser.component';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {MagicShelfService, MagicShelf} from '../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {bookId: id, title: `Book ${id}`},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookBrowserEntityService', () => {
|
||||
let service: BookBrowserEntityService;
|
||||
let libraryService: {libraries: ReturnType<typeof vi.fn>};
|
||||
let shelfService: {shelves: ReturnType<typeof vi.fn>};
|
||||
let magicShelfService: {findShelfById: ReturnType<typeof vi.fn>};
|
||||
let bookRuleEvaluatorService: {evaluateGroup: ReturnType<typeof vi.fn>};
|
||||
|
||||
const library = {
|
||||
id: 1,
|
||||
name: 'Library',
|
||||
watch: true,
|
||||
paths: [{path: '/books'}]
|
||||
} as Library;
|
||||
const shelf = {id: 2, name: 'Shelf'} as Shelf;
|
||||
const magicShelf = {
|
||||
id: 3,
|
||||
name: 'Magic Shelf',
|
||||
filterJson: JSON.stringify({group: 'all'})
|
||||
} as MagicShelf;
|
||||
|
||||
beforeEach(() => {
|
||||
libraryService = {
|
||||
libraries: vi.fn(() => [library])
|
||||
};
|
||||
shelfService = {
|
||||
shelves: vi.fn(() => [shelf])
|
||||
};
|
||||
magicShelfService = {
|
||||
findShelfById: vi.fn((id: number) => id === 3 ? magicShelf : null)
|
||||
};
|
||||
bookRuleEvaluatorService = {
|
||||
evaluateGroup: vi.fn((book: Book) => book.id === 2)
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookBrowserEntityService,
|
||||
{provide: LibraryService, useValue: libraryService},
|
||||
{provide: ShelfService, useValue: shelfService},
|
||||
{provide: MagicShelfService, useValue: magicShelfService},
|
||||
{provide: BookRuleEvaluatorService, useValue: bookRuleEvaluatorService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookBrowserEntityService);
|
||||
});
|
||||
|
||||
it('resolves entity ids from route params in priority order', () => {
|
||||
const allParams = convertToParamMap({
|
||||
libraryId: '1',
|
||||
shelfId: '2',
|
||||
magicShelfId: '3'
|
||||
});
|
||||
const shelfFirstParams = convertToParamMap({
|
||||
shelfId: '2',
|
||||
magicShelfId: '3'
|
||||
});
|
||||
const emptyParams = convertToParamMap({});
|
||||
|
||||
expect(service.getEntityInfo(allParams)).toEqual({
|
||||
entityId: 1,
|
||||
entityType: EntityType.LIBRARY
|
||||
});
|
||||
expect(service.getEntityInfo(shelfFirstParams)).toEqual({
|
||||
entityId: 2,
|
||||
entityType: EntityType.SHELF
|
||||
});
|
||||
expect(service.getEntityInfo(emptyParams)).toEqual({
|
||||
entityId: NaN,
|
||||
entityType: EntityType.ALL_BOOKS
|
||||
});
|
||||
});
|
||||
|
||||
it('returns entity records and recognizes library and magic shelf types', () => {
|
||||
expect(service.getEntity(1, EntityType.LIBRARY)).toBe(library);
|
||||
expect(service.getEntity(2, EntityType.SHELF)).toBe(shelf);
|
||||
expect(service.getEntity(3, EntityType.MAGIC_SHELF)).toBe(magicShelf);
|
||||
expect(service.getEntity(999, EntityType.ALL_BOOKS)).toBeNull();
|
||||
|
||||
expect(service.isLibrary(library)).toBe(true);
|
||||
expect(service.isLibrary(shelf as Library | Shelf | MagicShelf)).toBe(false);
|
||||
expect(service.isMagicShelf(magicShelf)).toBe(true);
|
||||
expect(service.isMagicShelf(null)).toBe(false);
|
||||
});
|
||||
|
||||
it('filters books by entity type and handles magic shelf parsing failures', () => {
|
||||
const books = [
|
||||
makeBook(1, {libraryId: 1, shelves: [{id: 2} as never]}),
|
||||
makeBook(2, {libraryId: 1, shelves: []}),
|
||||
makeBook(3, {libraryId: 2, shelves: [{id: 2} as never]})
|
||||
];
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
|
||||
expect(service.getBooksByEntity(books, 1, EntityType.LIBRARY)).toEqual([
|
||||
books[0],
|
||||
books[1]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 2, EntityType.SHELF)).toEqual([
|
||||
books[0],
|
||||
books[2]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 0, EntityType.UNSHELVED)).toEqual([
|
||||
books[1]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 0, EntityType.ALL_BOOKS)).toBe(books);
|
||||
|
||||
expect(service.getBooksByEntity(books, 3, EntityType.MAGIC_SHELF)).toEqual([
|
||||
books[1]
|
||||
]);
|
||||
expect(bookRuleEvaluatorService.evaluateGroup).toHaveBeenCalledWith(
|
||||
books[0],
|
||||
{group: 'all'},
|
||||
books
|
||||
);
|
||||
|
||||
magicShelfService.findShelfById.mockReturnValueOnce({
|
||||
id: 4,
|
||||
name: 'Broken Magic Shelf',
|
||||
filterJson: '{broken json'
|
||||
} as MagicShelf);
|
||||
|
||||
expect(service.getBooksByEntity(books, 4, EntityType.MAGIC_SHELF)).toEqual([]);
|
||||
expect(warnSpy).toHaveBeenCalledWith('Invalid filterJson for MagicShelf');
|
||||
});
|
||||
});
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {EntityType} from './book-browser.component';
|
||||
import {
|
||||
BookBrowserQueryParamsService,
|
||||
QUERY_PARAMS,
|
||||
VIEW_MODES
|
||||
} from './book-browser-query-params.service';
|
||||
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||
import {EntityViewPreferences} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('BookBrowserQueryParamsService', () => {
|
||||
let service: BookBrowserQueryParamsService;
|
||||
let routerNavigate: ReturnType<typeof vi.fn>;
|
||||
let routeSnapshot: {
|
||||
queryParams: Record<string, string | null>;
|
||||
queryParamMap: ParamMap;
|
||||
};
|
||||
let activatedRoute: {snapshot: typeof routeSnapshot};
|
||||
|
||||
const sortOptions: SortOption[] = [
|
||||
{label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING},
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
{label: 'Authors', field: 'author', direction: SortDirection.ASCENDING}
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
routerNavigate = vi.fn();
|
||||
routeSnapshot = {
|
||||
queryParams: {},
|
||||
queryParamMap: convertToParamMap({})
|
||||
};
|
||||
activatedRoute = {snapshot: routeSnapshot};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookBrowserQueryParamsService,
|
||||
{provide: Router, useValue: {navigate: routerNavigate}},
|
||||
{provide: ActivatedRoute, useValue: activatedRoute}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookBrowserQueryParamsService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('parses explicit query params, filters, and toggle state', () => {
|
||||
const result = service.parseQueryParams(
|
||||
convertToParamMap({
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE,
|
||||
[QUERY_PARAMS.SORT]: 'title:desc,author:asc',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi,series:A%3AB',
|
||||
[QUERY_PARAMS.FMODE]: 'or',
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
}),
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
viewMode: VIEW_MODES.TABLE,
|
||||
sortOption: {label: 'Title', field: 'title', direction: SortDirection.DESCENDING},
|
||||
sortCriteria: [
|
||||
{label: 'Title', field: 'title', direction: SortDirection.DESCENDING},
|
||||
{label: 'Authors', field: 'author', direction: SortDirection.ASCENDING}
|
||||
],
|
||||
filters: {
|
||||
tag: ['fiction', 'sci fi'],
|
||||
series: ['A:B']
|
||||
},
|
||||
filterMode: 'or',
|
||||
viewModeFromToggle: true
|
||||
});
|
||||
});
|
||||
|
||||
it('uses entity overrides, legacy preferences, and default sort fallback', () => {
|
||||
const userPrefs: EntityViewPreferences = {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
sortCriteria: [
|
||||
{field: 'title', direction: 'DESC'}
|
||||
],
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 7,
|
||||
preferences: {
|
||||
sortKey: 'authors',
|
||||
sortDir: 'DESC',
|
||||
sortCriteria: [
|
||||
{field: 'authors', direction: 'DESC'}
|
||||
],
|
||||
view: 'GRID',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: false
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const overrideResult = service.parseQueryParams(
|
||||
convertToParamMap({
|
||||
[QUERY_PARAMS.FMODE]: 'single'
|
||||
}),
|
||||
userPrefs,
|
||||
EntityType.LIBRARY,
|
||||
7,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(overrideResult.viewMode).toBe(VIEW_MODES.GRID);
|
||||
expect(overrideResult.filterMode).toBe('single');
|
||||
expect(overrideResult.sortCriteria).toEqual([
|
||||
{label: 'authors', field: 'authors', direction: SortDirection.DESCENDING}
|
||||
]);
|
||||
|
||||
const legacyResult = service.parseQueryParams(
|
||||
convertToParamMap({}),
|
||||
{
|
||||
global: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'DESC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(legacyResult.sortOption).toEqual({
|
||||
label: 'Title',
|
||||
field: 'title',
|
||||
direction: SortDirection.DESCENDING
|
||||
});
|
||||
expect(legacyResult.viewMode).toBe('table');
|
||||
|
||||
const fallbackResult = service.parseQueryParams(
|
||||
convertToParamMap({}),
|
||||
{
|
||||
global: {
|
||||
sortKey: 'missing',
|
||||
sortDir: 'DESC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(fallbackResult.sortOption).toEqual({
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
});
|
||||
});
|
||||
|
||||
it('serializes and deserializes sorts and filters while ignoring malformed input', () => {
|
||||
expect(service.serializeSort([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
{label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING}
|
||||
])).toBe('title:asc,addedOn:desc');
|
||||
|
||||
expect(service.deserializeSort('title:desc,missing:asc', sortOptions)).toEqual([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.DESCENDING}
|
||||
]);
|
||||
|
||||
expect(service.serializeFilters({
|
||||
tag: ['sci fi', 'new:release'],
|
||||
series: ['A/B']
|
||||
})).toBe('tag:sci%20fi|new%3Arelease,series:A%2FB');
|
||||
|
||||
expect(service.deserializeFilters('tag:sci%20fi|new%3Arelease,broken,series:A%2FB')).toEqual({
|
||||
tag: ['sci fi', 'new:release'],
|
||||
series: ['A/B']
|
||||
});
|
||||
});
|
||||
|
||||
it('updates query params for view mode, sort, filters, and sync changes', () => {
|
||||
routeSnapshot.queryParams = {
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'title:asc',
|
||||
[QUERY_PARAMS.DIRECTION]: 'desc',
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.GRID,
|
||||
[QUERY_PARAMS.FMODE]: 'and',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
};
|
||||
routeSnapshot.queryParamMap = convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
});
|
||||
|
||||
service.updateViewMode(VIEW_MODES.TABLE);
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE,
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
}));
|
||||
|
||||
service.updateSort({label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: expect.objectContaining({
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'addedOn:desc',
|
||||
[QUERY_PARAMS.DIRECTION]: null
|
||||
}),
|
||||
replaceUrl: true
|
||||
}));
|
||||
|
||||
routerNavigate.mockClear();
|
||||
routeSnapshot.queryParamMap = convertToParamMap({});
|
||||
service.updateFilters(null);
|
||||
expect(routerNavigate).not.toHaveBeenCalled();
|
||||
|
||||
routeSnapshot.queryParamMap = convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
});
|
||||
service.updateFilters({tag: ['fiction', 'sci fi']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {[QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi'},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
service.updateFilterMode('single', {tag: ['fiction', 'sci fi']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.FMODE]: 'single',
|
||||
[QUERY_PARAMS.FILTER]: null
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
service.updateFilterMode('or', {tag: ['fiction']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.FMODE]: 'or'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
routerNavigate.mockClear();
|
||||
service.syncQueryParams('grid', 'and', {tag: ['fiction']});
|
||||
expect(routerNavigate).not.toHaveBeenCalled();
|
||||
|
||||
service.syncQueryParams('table', 'single', {tag: ['fiction']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: {
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'title:asc',
|
||||
[QUERY_PARAMS.DIRECTION]: 'desc',
|
||||
[QUERY_PARAMS.VIEW]: 'table',
|
||||
[QUERY_PARAMS.FMODE]: 'single',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
},
|
||||
replaceUrl: true
|
||||
}));
|
||||
});
|
||||
|
||||
it('detects when a series filter should force expansion', () => {
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({}))).toBe(false);
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction,series:space-opera'
|
||||
}))).toBe(true);
|
||||
});
|
||||
});
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookBrowserScrollService} from './book-browser-scroll.service';
|
||||
|
||||
describe('BookBrowserScrollService', () => {
|
||||
const service = new BookBrowserScrollService();
|
||||
|
||||
it('stores, retrieves, clears, and creates stable keys', () => {
|
||||
expect(service.getPosition('books')).toBeUndefined();
|
||||
|
||||
service.savePosition('books', 144);
|
||||
service.savePosition('books:library', 288);
|
||||
|
||||
expect(service.getPosition('books')).toBe(144);
|
||||
expect(service.getPosition('books:library')).toBe(288);
|
||||
expect(service.createKey('/books', {libraryId: '1', shelfId: '2'})).toBe('/books:1-2');
|
||||
expect(service.createKey('/books', {})).toBe('/books');
|
||||
|
||||
service.clearPosition('books');
|
||||
expect(service.getPosition('books')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This needs a routed integration harness for the query-backed book browser,
|
||||
// PrimeNG overlays, and the persisted filter/sidebar preference services before the
|
||||
// control-flow branches can be exercised without brittle template scaffolding.
|
||||
describe.skip('BookBrowserComponent', () => {
|
||||
it('needs a browser-level harness for routed query state, filters, and overlay actions', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service';
|
||||
|
||||
describe('BookCardOverlayPreferenceService', () => {
|
||||
let service: BookCardOverlayPreferenceService;
|
||||
let userService: {
|
||||
currentUser: unknown;
|
||||
getCurrentUser: ReturnType<typeof vi.fn>;
|
||||
updateUserSetting: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let user: {
|
||||
id: number;
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
overlayBookType?: boolean;
|
||||
showBookTypePill?: boolean;
|
||||
};
|
||||
overrides: unknown[];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
user = {
|
||||
id: 7,
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
overlayBookType: false,
|
||||
},
|
||||
overrides: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
userService = {
|
||||
currentUser: signal(user),
|
||||
getCurrentUser: vi.fn(() => user),
|
||||
updateUserSetting: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookCardOverlayPreferenceService,
|
||||
{provide: UserService, useValue: userService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookCardOverlayPreferenceService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('updates the exposed signal immediately when the overlay preference changes', () => {
|
||||
service.setShowBookTypePill(false);
|
||||
|
||||
expect(service.showBookTypePill()).toBe(false);
|
||||
});
|
||||
|
||||
it('persists the updated global overlay preference after the debounce delay', () => {
|
||||
service.setShowBookTypePill(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(
|
||||
7,
|
||||
'entityViewPreferences',
|
||||
expect.objectContaining({
|
||||
global: expect.objectContaining({overlayBookType: true}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
import {NO_ERRORS_SCHEMA, SimpleChange, SimpleChanges} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {User, UserService} from '../../../../settings/user-management/user.service';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model';
|
||||
import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||
import {BookCardComponent} from './book-card.component';
|
||||
import {BookFileService} from '../../../service/book-file.service';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
|
||||
function makeBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 41,
|
||||
libraryId: 2,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: 41,
|
||||
title: 'Book Title',
|
||||
seriesName: 'Series Name',
|
||||
coverUpdatedOn: '2024-01-01',
|
||||
audiobookCoverUpdatedOn: '2024-01-02',
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeUser(metadataCenterViewMode: 'route' | 'dialog'): User {
|
||||
return {
|
||||
id: 1,
|
||||
username: 'tester',
|
||||
name: 'Tester',
|
||||
email: 'tester@example.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false,
|
||||
},
|
||||
userSettings: {
|
||||
metadataCenterViewMode,
|
||||
perBookSetting: {} as never,
|
||||
pdfReaderSetting: {} as never,
|
||||
epubReaderSetting: {} as never,
|
||||
ebookReaderSetting: {} as never,
|
||||
cbxReaderSetting: {} as never,
|
||||
newPdfReaderSetting: {} as never,
|
||||
sidebarLibrarySorting: {} as never,
|
||||
sidebarShelfSorting: {} as never,
|
||||
sidebarMagicShelfSorting: {} as never,
|
||||
filterMode: 'and',
|
||||
enableSeriesView: false,
|
||||
entityViewPreferences: {global: {} as never, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookCardComponent', () => {
|
||||
let component: BookCardComponent;
|
||||
let bookService: {
|
||||
readBook: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookFileService: {
|
||||
downloadFile: ReturnType<typeof vi.fn>;
|
||||
downloadAdditionalFile: ReturnType<typeof vi.fn>;
|
||||
deleteAdditionalFile: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookMetadataManageService: {
|
||||
regenerateCover: ReturnType<typeof vi.fn>;
|
||||
generateCustomCover: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let taskHelperService: {
|
||||
refreshMetadataTask: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {
|
||||
currentUser: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let emailService: {
|
||||
emailBookQuick: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let messageService: {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let router: {
|
||||
navigate: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let urlHelper: {
|
||||
getThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let confirmationService: {
|
||||
confirm: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookDialogHelperService: {
|
||||
openShelfAssignerDialog: ReturnType<typeof vi.fn>;
|
||||
openBookDetailsDialog: ReturnType<typeof vi.fn>;
|
||||
openCustomSendDialog: ReturnType<typeof vi.fn>;
|
||||
openMetadataRefreshDialog: ReturnType<typeof vi.fn>;
|
||||
openFileMoverDialog: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookNavigationService: {
|
||||
availableBookIds: ReturnType<typeof vi.fn>;
|
||||
setNavigationContext: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let appSettingsService: {
|
||||
appSettings: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translocoService: {
|
||||
translate: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let queryClient: {
|
||||
fetchQuery: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let cdr: {
|
||||
markForCheck: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
bookService = {
|
||||
readBook: vi.fn(),
|
||||
};
|
||||
bookFileService = {
|
||||
downloadFile: vi.fn(),
|
||||
downloadAdditionalFile: vi.fn(),
|
||||
deleteAdditionalFile: vi.fn(),
|
||||
};
|
||||
bookMetadataManageService = {
|
||||
regenerateCover: vi.fn(),
|
||||
generateCustomCover: vi.fn(),
|
||||
};
|
||||
taskHelperService = {
|
||||
refreshMetadataTask: vi.fn(),
|
||||
};
|
||||
userService = {
|
||||
currentUser: vi.fn(() => null),
|
||||
};
|
||||
emailService = {
|
||||
emailBookQuick: vi.fn(),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
router = {
|
||||
navigate: vi.fn(),
|
||||
};
|
||||
urlHelper = {
|
||||
getThumbnailUrl: vi.fn((bookId: number, coverUpdatedOn?: string) => `thumb:${bookId}:${coverUpdatedOn ?? 'none'}`),
|
||||
getAudiobookThumbnailUrl: vi.fn((bookId: number, audiobookCoverUpdatedOn?: string) => `audio-thumb:${bookId}:${audiobookCoverUpdatedOn ?? 'none'}`),
|
||||
};
|
||||
confirmationService = {
|
||||
confirm: vi.fn(),
|
||||
};
|
||||
bookDialogHelperService = {
|
||||
openShelfAssignerDialog: vi.fn(),
|
||||
openBookDetailsDialog: vi.fn(),
|
||||
openCustomSendDialog: vi.fn(),
|
||||
openMetadataRefreshDialog: vi.fn(),
|
||||
openFileMoverDialog: vi.fn(),
|
||||
};
|
||||
bookNavigationService = {
|
||||
availableBookIds: vi.fn(() => []),
|
||||
setNavigationContext: vi.fn(),
|
||||
};
|
||||
appSettingsService = {
|
||||
appSettings: vi.fn(() => ({diskType: 'LOCAL'})),
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string, params?: Record<string, unknown>) => (params ? `${key}:${JSON.stringify(params)}` : key)),
|
||||
};
|
||||
queryClient = {
|
||||
fetchQuery: vi.fn(),
|
||||
};
|
||||
cdr = {
|
||||
markForCheck: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BookCardComponent],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
providers: [
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: BookFileService, useValue: bookFileService},
|
||||
{provide: BookMetadataManageService, useValue: bookMetadataManageService},
|
||||
{provide: TaskHelperService, useValue: taskHelperService},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: EmailService, useValue: emailService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UrlHelperService, useValue: urlHelper},
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: BookDialogHelperService, useValue: bookDialogHelperService},
|
||||
{provide: BookNavigationService, useValue: bookNavigationService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
{provide: BookCardComponent, useValue: BookCardComponent},
|
||||
{provide: 'ChangeDetectorRef', useValue: cdr},
|
||||
],
|
||||
});
|
||||
|
||||
component = TestBed.createComponent(BookCardComponent).componentInstance;
|
||||
(component as unknown as {cdr: typeof cdr}).cdr = cdr;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('derives progress, audiobook, and series display state from inputs and changes', () => {
|
||||
component.book = makeBook({
|
||||
id: 8,
|
||||
metadata: {
|
||||
bookId: 8,
|
||||
title: 'Volume One',
|
||||
seriesName: 'Series Saga',
|
||||
coverUpdatedOn: '2024-04-01',
|
||||
audiobookCoverUpdatedOn: '2024-04-02',
|
||||
},
|
||||
seriesCount: 2,
|
||||
primaryFile: {
|
||||
id: 81,
|
||||
bookId: 8,
|
||||
bookType: 'AUDIOBOOK',
|
||||
extension: 'm4b',
|
||||
filePath: 'books/volume-one.m4b',
|
||||
},
|
||||
pdfProgress: {page: 11, percentage: 42},
|
||||
koreaderProgress: {percentage: 11},
|
||||
koboProgress: {percentage: 7},
|
||||
readStatus: ReadStatus.READING,
|
||||
});
|
||||
component.seriesViewEnabled = true;
|
||||
component.isSeriesCollapsed = true;
|
||||
component.forceEbookMode = false;
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.hasProgress).toBe(true);
|
||||
expect(component.displayTitle).toBe('Series Saga');
|
||||
expect(component.titleTooltip).toContain('Series Saga');
|
||||
expect(component.coverImageUrl).toBe('audio-thumb:8:2024-04-02');
|
||||
expect(component.progressTooltip).toBe('42% (Grimmory) | 11% (KOReader) | 7% (Kobo)');
|
||||
expect(component.readButtonIcon).toBe('pi pi-forward');
|
||||
|
||||
component.isSeriesCollapsed = false;
|
||||
component.ngOnChanges({
|
||||
isSeriesCollapsed: new SimpleChange(true, false, false),
|
||||
} as SimpleChanges);
|
||||
|
||||
expect(component.displayTitle).toBe('Volume One');
|
||||
expect(component.titleTooltip).toContain('Volume One');
|
||||
});
|
||||
|
||||
it('uses forced ebook mode for audiobook reads and falls back to the normal read flow otherwise', () => {
|
||||
const audiobookWithAlternativeFormat = makeBook({
|
||||
id: 12,
|
||||
primaryFile: {
|
||||
id: 121,
|
||||
bookId: 12,
|
||||
bookType: 'AUDIOBOOK',
|
||||
extension: 'm4b',
|
||||
filePath: 'books/audiobook.m4b',
|
||||
},
|
||||
alternativeFormats: [
|
||||
{
|
||||
id: 122,
|
||||
bookId: 12,
|
||||
bookType: 'PDF',
|
||||
fileName: 'A PDF',
|
||||
filePath: 'books/audiobook.pdf',
|
||||
fileSizeKb: 2048,
|
||||
} as AdditionalFile,
|
||||
],
|
||||
});
|
||||
|
||||
component.forceEbookMode = true;
|
||||
component.readBook(audiobookWithAlternativeFormat);
|
||||
|
||||
expect(bookService.readBook).toHaveBeenCalledWith(12, undefined, 'PDF');
|
||||
|
||||
component.forceEbookMode = false;
|
||||
component.readBook(makeBook({id: 13}));
|
||||
|
||||
expect(bookService.readBook).toHaveBeenCalledWith(13);
|
||||
});
|
||||
|
||||
it('derives display format from missing primary files, extensions, paths, and forced audiobook ebook types', () => {
|
||||
component.book = makeBook({id: 20, primaryFile: undefined});
|
||||
component.forceEbookMode = false;
|
||||
expect(component.getDisplayFormat()).toBe('PHY');
|
||||
|
||||
component.book = makeBook({
|
||||
id: 21,
|
||||
primaryFile: {
|
||||
id: 211,
|
||||
bookId: 21,
|
||||
bookType: 'PDF',
|
||||
extension: 'pdf',
|
||||
filePath: 'books/volume-one.pdf',
|
||||
},
|
||||
});
|
||||
expect(component.getDisplayFormat()).toBe('PDF');
|
||||
|
||||
component.book = makeBook({
|
||||
id: 22,
|
||||
primaryFile: {
|
||||
id: 221,
|
||||
bookId: 22,
|
||||
bookType: 'EPUB',
|
||||
filePath: 'books/volume-one.mobi',
|
||||
},
|
||||
});
|
||||
expect(component.getDisplayFormat()).toBe('MOBI');
|
||||
|
||||
component.book = makeBook({
|
||||
id: 23,
|
||||
primaryFile: {
|
||||
id: 231,
|
||||
bookId: 23,
|
||||
bookType: 'AUDIOBOOK',
|
||||
filePath: 'books/volume-one.m4b',
|
||||
},
|
||||
epubProgress: {cfi: 'epub', percentage: 73},
|
||||
});
|
||||
component.forceEbookMode = true;
|
||||
expect(component.getDisplayFormat()).toBe('EPUB');
|
||||
});
|
||||
|
||||
it('guards card selection and preserves shift metadata for ctrl-initiated changes only', () => {
|
||||
component.book = makeBook({id: 30});
|
||||
component.index = 4;
|
||||
component.isCheckboxEnabled = false;
|
||||
component.isSelected = false;
|
||||
component.onBookSelect = vi.fn();
|
||||
|
||||
const emitSpy = vi.spyOn(component.checkboxClick, 'emit');
|
||||
|
||||
component.toggleCardSelection(true);
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
expect(component.onBookSelect).not.toHaveBeenCalled();
|
||||
|
||||
component.isCheckboxEnabled = true;
|
||||
component.captureMouseEvent(new MouseEvent('mousedown', {shiftKey: true}));
|
||||
|
||||
component.onCardClick(new MouseEvent('click', {ctrlKey: false}));
|
||||
expect(emitSpy).not.toHaveBeenCalled();
|
||||
|
||||
component.onCardClick(new MouseEvent('click', {ctrlKey: true}));
|
||||
|
||||
expect(component.isSelected).toBe(true);
|
||||
expect(emitSpy).toHaveBeenCalledWith({
|
||||
index: 4,
|
||||
book: component.book,
|
||||
selected: true,
|
||||
shiftKey: true,
|
||||
});
|
||||
expect(component.onBookSelect).toHaveBeenCalledWith(component.book, true);
|
||||
});
|
||||
|
||||
it('routes series info and book details through the correct destination', () => {
|
||||
const book = makeBook({
|
||||
id: 44,
|
||||
metadata: {
|
||||
bookId: 44,
|
||||
title: 'Volume Four',
|
||||
seriesName: 'The Series',
|
||||
coverUpdatedOn: '2024-05-01',
|
||||
audiobookCoverUpdatedOn: '2024-05-02',
|
||||
},
|
||||
});
|
||||
|
||||
userService.currentUser.mockReturnValue(makeUser('route'));
|
||||
component.book = book;
|
||||
component.isSeriesCollapsed = true;
|
||||
component.ngOnInit();
|
||||
|
||||
component.openSeriesInfo();
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/series', 'The Series']);
|
||||
|
||||
bookNavigationService.availableBookIds.mockReturnValue([2, 44, 77]);
|
||||
component.isSeriesCollapsed = false;
|
||||
component.openSeriesInfo();
|
||||
|
||||
expect(bookNavigationService.setNavigationContext).toHaveBeenCalledWith([2, 44, 77], 44);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/book', 44], {
|
||||
queryParams: {tab: 'view'},
|
||||
});
|
||||
|
||||
userService.currentUser.mockReturnValue(makeUser('dialog'));
|
||||
const dialogComponent = component as unknown as {metadataCenterViewMode: 'route' | 'dialog'};
|
||||
dialogComponent.metadataCenterViewMode = 'dialog';
|
||||
router.navigate.mockClear();
|
||||
bookNavigationService.setNavigationContext.mockClear();
|
||||
|
||||
component.openBookInfo(book);
|
||||
|
||||
expect(bookDialogHelperService.openBookDetailsDialog).toHaveBeenCalledWith(44);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
expect(bookNavigationService.setNavigationContext).toHaveBeenCalledWith([2, 44, 77], 44);
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
|
||||
describe('BookDialogHelperService', () => {
|
||||
let service: BookDialogHelperService;
|
||||
let dialogLauncherService: {openDialog: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
dialogLauncherService = {
|
||||
openDialog: vi.fn(() => ({id: 'dialog-ref'})),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookDialogHelperService,
|
||||
{provide: DialogLauncherService, useValue: dialogLauncherService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookDialogHelperService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('opens the book details dialog with the expected payload', () => {
|
||||
const dialogRef = service.openBookDetailsDialog(42);
|
||||
|
||||
expect(dialogLauncherService.openDialog).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
expect.objectContaining({
|
||||
showHeader: false,
|
||||
data: {bookId: 42},
|
||||
})
|
||||
);
|
||||
expect(dialogRef).toEqual({id: 'dialog-ref'});
|
||||
});
|
||||
|
||||
it('returns null instead of opening the shelf assigner when no inputs are provided', () => {
|
||||
const dialogRef = service.openShelfAssignerDialog(null, null);
|
||||
|
||||
expect(dialogRef).toBeNull();
|
||||
expect(dialogLauncherService.openDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens the bulk file attacher with the provided source books', () => {
|
||||
const sourceBooks = [{id: 1}, {id: 2}] as never[];
|
||||
|
||||
service.openBulkBookFileAttacherDialog(sourceBooks);
|
||||
|
||||
expect(dialogLauncherService.openDialog).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
expect.objectContaining({
|
||||
showHeader: false,
|
||||
data: {sourceBooks},
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {convertToParamMap} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookFilterOrchestrationService} from './book-filter-orchestration.service';
|
||||
import {SortService} from '../../service/sort.service';
|
||||
|
||||
describe('BookFilterOrchestrationService', () => {
|
||||
let service: BookFilterOrchestrationService;
|
||||
let sortService: {applyMultiSort: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
sortService = {
|
||||
applyMultiSort: vi.fn((books: unknown[]) => books),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookFilterOrchestrationService,
|
||||
{provide: SortService, useValue: sortService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookFilterOrchestrationService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('passes searched and collapsed books through the sorter', () => {
|
||||
const books = [
|
||||
{id: 1, metadata: {title: 'Alpha Flight'}},
|
||||
{id: 2, metadata: {title: 'Beta Test'}},
|
||||
] as never[];
|
||||
const seriesCollapseFilter = {
|
||||
collapseBooks: vi.fn((items: unknown[]) => items),
|
||||
};
|
||||
const sortCriteria = [{property: 'title', direction: 'ASC'}] as never[];
|
||||
|
||||
const result = service.applyFilters(
|
||||
books,
|
||||
'alpha',
|
||||
null,
|
||||
'and',
|
||||
seriesCollapseFilter as never,
|
||||
false,
|
||||
false,
|
||||
sortCriteria
|
||||
);
|
||||
|
||||
expect(seriesCollapseFilter.collapseBooks).toHaveBeenCalledWith(
|
||||
[books[0]],
|
||||
false,
|
||||
false
|
||||
);
|
||||
expect(sortService.applyMultiSort).toHaveBeenCalledWith([books[0]], sortCriteria);
|
||||
expect(result).toEqual([books[0]]);
|
||||
});
|
||||
|
||||
it('forces series expansion only when a series filter is present in the query string', () => {
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({filter: 'author:42,series:Saga'}))).toBe(true);
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({filter: 'author:42'}))).toBe(false);
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({}))).toBe(false);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around reset streams, user-setting effects,
|
||||
// and virtual-scroll accordion rendering so filter-mode changes and panel expansion can be
|
||||
// asserted without the full book-browser sidebar runtime.
|
||||
describe.skip('BookFilterComponent', () => {
|
||||
it('needs signal seams to verify visible filter hydration, mode changes, and emitted active-filter payloads', () => {
|
||||
// TODO(seam): Cover selectedFilterMode, setFilters, and emitFilters after the user-settings signal and filter service signals are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs UI-shell seams to verify reset handling, panel expansion, and multi-select filter clicks', () => {
|
||||
// TODO(seam): Cover handleFilterClick, clearActiveFilter, and accordion expansion after the virtual-scroll and select-button runtime is removed from the test surface.
|
||||
});
|
||||
});
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {
|
||||
CONTENT_RATING_LABELS,
|
||||
FILTER_CONFIGS,
|
||||
FILTER_EXTRACTORS,
|
||||
FILTER_LABEL_KEYS,
|
||||
MATCH_SCORE_RANGES,
|
||||
NUMERIC_ID_FILTER_TYPES,
|
||||
RATING_OPTIONS_10,
|
||||
READ_STATUS_LABELS
|
||||
} from './book-filter.config';
|
||||
|
||||
const makeBook = (overrides: Partial<Book> = {}): Book => ({
|
||||
id: 1,
|
||||
libraryId: 9,
|
||||
libraryName: 'Main',
|
||||
...overrides
|
||||
});
|
||||
|
||||
describe('book-filter.config', () => {
|
||||
it('covers every read status with a label', () => {
|
||||
expect(READ_STATUS_LABELS[ReadStatus.UNREAD]).toBe('Unread');
|
||||
expect(READ_STATUS_LABELS[ReadStatus.UNSET]).toBe('Unset');
|
||||
expect(Object.keys(READ_STATUS_LABELS)).toHaveLength(Object.keys(ReadStatus).length);
|
||||
});
|
||||
|
||||
it('defines 10 one-step rating buckets', () => {
|
||||
expect(RATING_OPTIONS_10).toHaveLength(10);
|
||||
expect(RATING_OPTIONS_10[0]).toMatchObject({id: 1, label: '1', min: 1, max: 2, sortIndex: 0});
|
||||
expect(RATING_OPTIONS_10.at(-1)).toMatchObject({id: 10, label: '10', min: 10, max: 11, sortIndex: 9});
|
||||
});
|
||||
|
||||
it('keeps filter labels and configs aligned', () => {
|
||||
const configKeys = Object.keys(FILTER_CONFIGS).sort();
|
||||
const labelKeysWithoutLibrary = Object.keys(FILTER_LABEL_KEYS).filter((key) => key !== 'library').sort();
|
||||
|
||||
expect(labelKeysWithoutLibrary).toEqual(configKeys);
|
||||
expect(FILTER_LABEL_KEYS.library).toBe('book.filter.labels.library');
|
||||
expect(NUMERIC_ID_FILTER_TYPES.has('pageCount')).toBe(true);
|
||||
expect(NUMERIC_ID_FILTER_TYPES.has('author')).toBe(false);
|
||||
});
|
||||
|
||||
it('normalizes read status, metadata match score, and content ratings', () => {
|
||||
expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: ReadStatus.READING}))).toEqual([
|
||||
{id: ReadStatus.READING, name: 'Reading'}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: 'INVALID' as ReadStatus}))).toEqual([
|
||||
{id: ReadStatus.UNSET, name: 'Unset'}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.matchScore(makeBook({metadataMatchScore: 92}))).toEqual([
|
||||
{id: MATCH_SCORE_RANGES[1].id, name: MATCH_SCORE_RANGES[1].label, sortIndex: MATCH_SCORE_RANGES[1].sortIndex}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.contentRating(makeBook({
|
||||
metadata: {bookId: 1, contentRating: 'EVERYONE'}
|
||||
}))).toEqual([{id: 'EVERYONE', name: CONTENT_RATING_LABELS['EVERYONE']}]);
|
||||
});
|
||||
|
||||
it('builds comic creator filters with role-aware labels', () => {
|
||||
const filters = FILTER_EXTRACTORS.comicCreator(makeBook({
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
comicMetadata: {
|
||||
pencillers: ['Jane Artist'],
|
||||
editors: ['Max Editor']
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
expect(filters).toEqual([
|
||||
{id: 'Jane Artist:penciller', name: 'Jane Artist (Penciller)'},
|
||||
{id: 'Max Editor:editor', name: 'Max Editor (Editor)'}
|
||||
]);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around the live book, library, and
|
||||
// magic-shelf signal graph so dynamic filter aggregation can be asserted without recreating the
|
||||
// full sidebar filter runtime and evaluator dependencies.
|
||||
describe.skip('BookFilterService', () => {
|
||||
it('needs signal seams to verify library, shelf, and magic-shelf entity filtering across active sidebar filters', () => {
|
||||
// TODO(seam): Cover createFilterSignals and filterBooksByEntity once the dependent signals and evaluator service are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs aggregation seams to verify filter count sorting, numeric-id coercion, and invalid magic-shelf fallback handling', () => {
|
||||
// TODO(seam): Cover buildAndSortFilters, processFilterValue, and filterByMagicShelf after extractor inputs and service state are exposed through a stable harness.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookSelectionService} from './book-selection.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {bookId: id, title: `Book ${id}`},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookSelectionService', () => {
|
||||
let service: BookSelectionService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [BookSelectionService]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookSelectionService);
|
||||
});
|
||||
|
||||
it('selects and deselects single books and series groups', () => {
|
||||
const singleBook = makeBook(1);
|
||||
const seriesBook = makeBook(2, {
|
||||
seriesBooks: [makeBook(2), makeBook(3)]
|
||||
});
|
||||
|
||||
service.selectBook(singleBook);
|
||||
service.selectBook(seriesBook);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set([1, 2, 3]));
|
||||
expect(service.selectedCount()).toBe(3);
|
||||
|
||||
service.deselectBook(makeBook(1));
|
||||
service.deselectBook(seriesBook);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('tracks checkbox clicks with and without shift selection', () => {
|
||||
const books = [makeBook(1), makeBook(2), makeBook(3), makeBook(4)];
|
||||
service.setCurrentBooks(books);
|
||||
|
||||
service.handleCheckboxClick({index: 1, book: books[1], selected: true, shiftKey: false});
|
||||
expect(service.selectedBooks()).toEqual(new Set([2]));
|
||||
|
||||
service.handleCheckboxClick({index: 3, book: books[3], selected: true, shiftKey: true});
|
||||
expect(service.selectedBooks()).toEqual(new Set([2, 3, 4]));
|
||||
|
||||
service.handleCheckboxClick({index: 3, book: books[3], selected: false, shiftKey: true});
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
});
|
||||
|
||||
it('selects all current books, resets selection, and clones selected ids', () => {
|
||||
expect(() => service.selectAll()).not.toThrow();
|
||||
|
||||
const books = [makeBook(1), makeBook(2)];
|
||||
service.setCurrentBooks(books);
|
||||
service.selectAll();
|
||||
expect(service.selectedBooks()).toEqual(new Set([1, 2]));
|
||||
|
||||
const selectedIds = new Set([4, 5]);
|
||||
service.setSelectedBooks(selectedIds);
|
||||
selectedIds.add(6);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set([4, 5]));
|
||||
|
||||
service.deselectAll();
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around DOM sizing, table selection events,
|
||||
// router-link rendering, and metadata-lock helpers so table interactions can be asserted without
|
||||
// mounting the full PrimeNG virtual-table runtime.
|
||||
describe.skip('BookTableComponent', () => {
|
||||
it('needs browser seams to verify responsive scroll-height updates and virtual scroller resizing', () => {
|
||||
// TODO(seam): Cover setScrollHeight and ngOnChanges after window/document globals are isolated behind deterministic adapters.
|
||||
});
|
||||
|
||||
it('needs table-event seams to verify row selection, bulk selection, and clickable metadata cell generation', () => {
|
||||
// TODO(seam): Cover selection methods and getCellClickableValue after the PrimeNG table event surface is extracted into a stable test harness.
|
||||
});
|
||||
});
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||
|
||||
describe('CoverScalePreferenceService', () => {
|
||||
let service: CoverScalePreferenceService;
|
||||
let localStorageService: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
|
||||
let messageService: { add: ReturnType<typeof vi.fn> };
|
||||
let translocoService: { translate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
localStorageService = {
|
||||
get: vi.fn(),
|
||||
set: vi.fn()
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string, params?: Record<string, unknown>) =>
|
||||
params ? `${key}:${JSON.stringify(params)}` : `t:${key}`
|
||||
)
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the saved scale and derives the card metrics', () => {
|
||||
localStorageService.get.mockReturnValue(1.5);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CoverScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(CoverScalePreferenceService);
|
||||
|
||||
expect(service.scaleFactor()).toBe(1.5);
|
||||
expect(service.currentCardSize()).toEqual({width: 203, height: 330});
|
||||
expect(service.gridColumnMinWidth()).toBe('203px');
|
||||
expect(service.getCardHeight({} as never)).toBe(330);
|
||||
});
|
||||
|
||||
it('falls back to the default scale and skips persistence when unchanged', () => {
|
||||
localStorageService.get.mockReturnValue(null);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CoverScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(CoverScalePreferenceService);
|
||||
|
||||
service.setScale(1.0);
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
expect(messageService.add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('persists updated scale after debounce and reports failures', () => {
|
||||
localStorageService.get.mockReturnValue(1.0);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CoverScalePreferenceService,
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(CoverScalePreferenceService);
|
||||
|
||||
service.setScale(1.2);
|
||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
expect(localStorageService.set).toHaveBeenCalledWith('coverScalePreference', 1.2);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 't:book.coverPref.toast.savedSummary',
|
||||
detail: 'book.coverPref.toast.savedDetail:{"scale":"1.20"}',
|
||||
life: 1500
|
||||
}));
|
||||
|
||||
vi.clearAllMocks();
|
||||
localStorageService.set.mockImplementation(() => {
|
||||
throw new Error('storage unavailable');
|
||||
});
|
||||
|
||||
service.setScale(1.3);
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 't:book.coverPref.toast.saveFailedSummary',
|
||||
detail: 't:book.coverPref.toast.saveFailedDetail',
|
||||
life: 3000
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {FilterLabelHelper} from './filter-label.helper';
|
||||
|
||||
describe('FilterLabelHelper', () => {
|
||||
it('returns friendly names for known filter types and capitalizes unknown names', () => {
|
||||
expect(FilterLabelHelper.getFilterTypeName('personalRating')).toBe('Personal Rating');
|
||||
expect(FilterLabelHelper.getFilterTypeName('customFilter')).toBe('CustomFilter');
|
||||
});
|
||||
|
||||
it('maps numeric ids to configured range labels', () => {
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 1)).toBe('1–10 MB');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 3)).toBe('200–400 pages');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 0)).toBe('Outstanding (95–100%)');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('personalRating', 7)).toBe('7');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 5)).toBe('4.5+');
|
||||
});
|
||||
|
||||
it('falls back to the raw value when a numeric id is not recognized', () => {
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 999)).toBe('999');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('tag', 'favorite')).toBe('favorite');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {filterBooksBySearchTerm, normalizeSearchTerm} from './HeaderFilter';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
fileName: `Book ${id}.epub`,
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Title ${id}`,
|
||||
seriesName: `Series ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
categories: [`Category ${id}`],
|
||||
isbn10: `ISBN10-${id}`,
|
||||
isbn13: `ISBN13-${id}`
|
||||
},
|
||||
primaryFile: {id, bookId: id, fileName: `Book ${id}.epub`, bookType: 'EPUB'},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('HeaderFilter', () => {
|
||||
it('normalizes unicode, punctuation, whitespace, and empty input', () => {
|
||||
expect(normalizeSearchTerm('')).toBe('');
|
||||
expect(normalizeSearchTerm(' Ætna øresund! ')).toBe('aetna oresund');
|
||||
expect(normalizeSearchTerm('Łódź / Straße')).toBe('lodz strasse');
|
||||
});
|
||||
|
||||
it('keeps the full book list for short terms and filters by searchable fields', () => {
|
||||
const books = [
|
||||
makeBook(1),
|
||||
makeBook(2, {
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'The Other Title',
|
||||
seriesName: 'Other Series',
|
||||
authors: ['Different Author'],
|
||||
categories: ['Biography'],
|
||||
isbn10: '999',
|
||||
isbn13: '888'
|
||||
},
|
||||
primaryFile: {id: 2, bookId: 2, fileName: 'Notes.txt', bookType: 'EPUB'}
|
||||
}),
|
||||
makeBook(3, {
|
||||
metadata: {
|
||||
bookId: 3,
|
||||
title: 'Completely Different',
|
||||
seriesName: 'Third Series',
|
||||
authors: ['Series Match'],
|
||||
categories: ['History'],
|
||||
isbn10: '111',
|
||||
isbn13: '222'
|
||||
},
|
||||
primaryFile: {id: 3, bookId: 3, fileName: 'Search Target.epub', bookType: 'EPUB'}
|
||||
})
|
||||
];
|
||||
|
||||
expect(filterBooksBySearchTerm(books, '')).toBe(books);
|
||||
expect(filterBooksBySearchTerm(books, 'a')).toBe(books);
|
||||
|
||||
expect(filterBooksBySearchTerm(books, 'other title').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, 'other series').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, 'series match').map(book => book.id)).toEqual([3]);
|
||||
expect(filterBooksBySearchTerm(books, 'biography').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, '222').map(book => book.id)).toEqual([3]);
|
||||
expect(filterBooksBySearchTerm(books, 'search target').map(book => book.id)).toEqual([3]);
|
||||
});
|
||||
});
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
import {SeriesCollapseFilter} from './SeriesCollapseFilter';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {Book} from '../../../model/book.model';
|
||||
|
||||
function makeBook(id: number, seriesName?: string, seriesNumber?: number): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
seriesName,
|
||||
seriesNumber
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('SeriesCollapseFilter', () => {
|
||||
let userService: {currentUser: ReturnType<typeof vi.fn>; getCurrentUser: ReturnType<typeof vi.fn>; updateUserSetting: ReturnType<typeof vi.fn>};
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let service: SeriesCollapseFilter;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({id: 1})),
|
||||
getCurrentUser: vi.fn(() => null),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
messageService = {add: vi.fn()};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SeriesCollapseFilter,
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: MessageService, useValue: messageService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(SeriesCollapseFilter);
|
||||
});
|
||||
|
||||
it('returns books unchanged when collapse is disabled or series expansion is forced', () => {
|
||||
const books = [makeBook(1), makeBook(2, 'Series', 2)];
|
||||
|
||||
expect(service.collapseBooks(books, false, false)).toBe(books);
|
||||
expect(service.collapseBooks([], false, true)).toEqual([]);
|
||||
expect(service.collapseBooks(books, true, true)).toBe(books);
|
||||
});
|
||||
|
||||
it('collapses series into grouped books with the lowest numbered entry first', () => {
|
||||
const books = [
|
||||
makeBook(1, 'Series', 2),
|
||||
makeBook(2, 'Series', 1),
|
||||
makeBook(3),
|
||||
makeBook(4, 'Other Series', 5)
|
||||
];
|
||||
|
||||
const collapsed = service.collapseBooks(books, false, true);
|
||||
|
||||
expect(collapsed).toEqual([
|
||||
makeBook(3),
|
||||
{
|
||||
...makeBook(2, 'Series', 1),
|
||||
seriesBooks: [books[0], books[1]],
|
||||
seriesCount: 2
|
||||
},
|
||||
{
|
||||
...makeBook(4, 'Other Series', 5),
|
||||
seriesBooks: [books[3]],
|
||||
seriesCount: 1
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
it('persists context-aware and global preferences with legacy fallbacks', () => {
|
||||
const user = {
|
||||
id: 1,
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1,
|
||||
seriesCollapse: true
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 99,
|
||||
preferences: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'ASC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
userService.getCurrentUser.mockReturnValue(user);
|
||||
|
||||
service.setContext('LIBRARY', 99);
|
||||
expect(service.seriesCollapsed()).toBe(false);
|
||||
|
||||
service.setCollapsed(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({
|
||||
overrides: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 99,
|
||||
preferences: expect.objectContaining({
|
||||
seriesCollapsed: true
|
||||
})
|
||||
})
|
||||
])
|
||||
}));
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved'
|
||||
}));
|
||||
|
||||
userService.updateUserSetting.mockClear();
|
||||
messageService.add.mockClear();
|
||||
|
||||
service.setContext(null, null);
|
||||
service.setCollapsed(false);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({
|
||||
global: expect.objectContaining({
|
||||
seriesCollapsed: false
|
||||
})
|
||||
}));
|
||||
});
|
||||
});
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
||||
import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service';
|
||||
|
||||
describe('SidebarFilterTogglePrefService', () => {
|
||||
let originalInnerWidth: number;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let localStorageService: {
|
||||
get: ReturnType<typeof vi.fn>;
|
||||
set: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
const setViewport = (width: number) => {
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
configurable: true,
|
||||
value: width,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
originalInnerWidth = window.innerWidth;
|
||||
messageService = {add: vi.fn()};
|
||||
localStorageService = {
|
||||
get: vi.fn(() => null),
|
||||
set: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setViewport(originalInnerWidth);
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
const createService = () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SidebarFilterTogglePrefService,
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: TranslocoService, useValue: {translate: (key: string) => key}},
|
||||
],
|
||||
});
|
||||
|
||||
return TestBed.inject(SidebarFilterTogglePrefService);
|
||||
};
|
||||
|
||||
it('loads the stored preference on wide screens', () => {
|
||||
setViewport(1280);
|
||||
localStorageService.get.mockReturnValue(false);
|
||||
|
||||
const service = createService();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.get).toHaveBeenCalledWith('showSidebarFilter');
|
||||
});
|
||||
|
||||
it('forces the filter closed on narrow screens', () => {
|
||||
setViewport(640);
|
||||
|
||||
const service = createService();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('toggles the visibility and persists the updated value', () => {
|
||||
setViewport(1280);
|
||||
const service = createService();
|
||||
|
||||
service.toggle();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.set).toHaveBeenCalledWith('showSidebarFilter', false);
|
||||
});
|
||||
|
||||
it('shows an error toast when persistence fails', () => {
|
||||
setViewport(1280);
|
||||
localStorageService.set.mockImplementation(() => {
|
||||
throw new Error('storage failed');
|
||||
});
|
||||
const service = createService();
|
||||
|
||||
service.setShowFilter(false);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 'book.filterPref.toast.saveFailedSummary',
|
||||
detail: 'book.filterPref.toast.saveFailedDetail',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {
|
||||
doesBookMatchFilter,
|
||||
doesBookMatchReadStatus,
|
||||
filterBooksByFilters,
|
||||
isFileSizeInRange,
|
||||
isMatchScoreInRange,
|
||||
isPageCountInRange,
|
||||
isRatingInRange,
|
||||
isRatingInRange10
|
||||
} from './sidebar-filter';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
readStatus: ReadStatus.UNREAD,
|
||||
fileSizeKb: 1500,
|
||||
metadataMatchScore: 87,
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Title ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
categories: [`Category ${id}`],
|
||||
seriesName: `Series ${id}`,
|
||||
publisher: 'Publisher',
|
||||
publishedDate: '2024-02-01',
|
||||
pageCount: 230,
|
||||
language: 'en',
|
||||
tags: ['tag-a'],
|
||||
moods: ['mood-a'],
|
||||
amazonRating: 4.3,
|
||||
goodreadsRating: 4.1,
|
||||
hardcoverRating: 4.2,
|
||||
narrator: 'Narrator',
|
||||
ageRating: 16,
|
||||
contentRating: 'PG-13',
|
||||
comicMetadata: {
|
||||
characters: ['hero'],
|
||||
teams: ['team-a'],
|
||||
locations: ['earth'],
|
||||
pencillers: ['Penciller'],
|
||||
inkers: ['Inker'],
|
||||
colorists: ['Colorist'],
|
||||
letterers: ['Letterer'],
|
||||
coverArtists: ['Cover'],
|
||||
editors: ['Editor']
|
||||
}
|
||||
},
|
||||
shelves: [{id: 7, name: 'Favorites'}],
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('sidebar-filter', () => {
|
||||
it('covers the numeric helper ranges and read status matching', () => {
|
||||
expect(isRatingInRange(null, 1)).toBe(false);
|
||||
expect(isRatingInRange(4.3, '4')).toBe(true);
|
||||
expect(isRatingInRange10(4.4, 4)).toBe(true);
|
||||
expect(isFileSizeInRange(undefined, 1)).toBe(false);
|
||||
expect(isFileSizeInRange(1500, 1)).toBe(true);
|
||||
expect(isPageCountInRange(230, '3')).toBe(true);
|
||||
expect(isMatchScoreInRange(87, 2)).toBe(true);
|
||||
expect(isMatchScoreInRange(87, 9)).toBe(false);
|
||||
expect(doesBookMatchReadStatus(makeBook(1), [ReadStatus.UNREAD])).toBe(true);
|
||||
expect(doesBookMatchReadStatus(makeBook(1, {readStatus: undefined}), [ReadStatus.UNSET])).toBe(true);
|
||||
});
|
||||
|
||||
it('matches all filter branches across or, and, and not modes', () => {
|
||||
const book = makeBook(1);
|
||||
const books = [book, makeBook(2, {
|
||||
readStatus: ReadStatus.READING,
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Other',
|
||||
authors: ['Other Author'],
|
||||
categories: ['Other Category'],
|
||||
seriesName: 'Other Series',
|
||||
publisher: 'Other Publisher',
|
||||
publishedDate: '2021-01-01',
|
||||
pageCount: 50,
|
||||
language: 'fr',
|
||||
tags: ['other-tag'],
|
||||
moods: ['other-mood'],
|
||||
amazonRating: 3.1,
|
||||
goodreadsRating: 3.2,
|
||||
hardcoverRating: 3.3,
|
||||
narrator: 'Someone Else',
|
||||
ageRating: 12,
|
||||
contentRating: 'R',
|
||||
comicMetadata: {
|
||||
characters: ['villain'],
|
||||
teams: ['team-b'],
|
||||
locations: ['mars'],
|
||||
pencillers: ['Alt Penciller'],
|
||||
inkers: ['Alt Inker'],
|
||||
colorists: ['Alt Colorist'],
|
||||
letterers: ['Alt Letterer'],
|
||||
coverArtists: ['Alt Cover'],
|
||||
editors: ['Alt Editor']
|
||||
}
|
||||
},
|
||||
shelves: []
|
||||
})];
|
||||
|
||||
expect(doesBookMatchFilter(book, 'author', ['Author 1'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'category', ['Category 1'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'series', ['Series 1'], 'not')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'bookType', ['PHYSICAL'], 'or')).toBe(false);
|
||||
expect(doesBookMatchFilter(book, 'readStatus', [ReadStatus.UNREAD], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'publisher', ['Publisher'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'matchScore', [2], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'library', [1], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'shelf', [7], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'shelfStatus', ['shelved'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(makeBook(3, {shelves: []}), 'shelfStatus', ['unshelved'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'tag', ['tag-a'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'publishedDate', ['2024'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'fileSize', [1], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'amazonRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'goodreadsRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'hardcoverRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'language', ['en'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'pageCount', [3], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'mood', ['mood-a'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'ageRating', ['16'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'contentRating', ['PG-13'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'narrator', ['Narrator'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicCharacter', ['hero'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicTeam', ['team-a'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicLocation', ['earth'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicCreator', ['Penciller:penciller'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'unknown', ['x'], 'or')).toBe(false);
|
||||
|
||||
expect(doesBookMatchFilter(makeBook(4, {isPhysical: true}), 'bookType', ['PHYSICAL'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'author', [], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'author', [], 'and')).toBe(false);
|
||||
|
||||
expect(filterBooksByFilters(books, null, 'or')).toBe(books);
|
||||
expect(filterBooksByFilters(books, {author: ['Author 1']}, 'or')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Other Author']}, 'not')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Author 1'], category: ['Category 1']}, 'and')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Other Author'], category: ['Category 1']}, 'or', 'author')).toEqual([book]);
|
||||
});
|
||||
});
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LoadingService} from '../../../../../core/services/loading.service';
|
||||
import {
|
||||
createDynamicDialogHarness,
|
||||
createMessageServiceProvider,
|
||||
createMessageServiceSpy,
|
||||
} from '../../../../../core/testing/dialog-testing';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog.component';
|
||||
|
||||
describe('LockUnlockMetadataDialogComponent', () => {
|
||||
let toggleFieldLocks: ReturnType<typeof vi.fn>;
|
||||
let dialogHarness: ReturnType<typeof createDynamicDialogHarness<{bookIds: Set<number>}>>;
|
||||
let messageService: ReturnType<typeof createMessageServiceSpy>;
|
||||
let loadingService: {
|
||||
show: ReturnType<typeof vi.fn>;
|
||||
hide: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translate: TranslocoService['translate'];
|
||||
|
||||
beforeEach(() => {
|
||||
toggleFieldLocks = vi.fn(() => of(void 0));
|
||||
dialogHarness = createDynamicDialogHarness({bookIds: new Set([7, 9])});
|
||||
messageService = createMessageServiceSpy();
|
||||
loadingService = {
|
||||
show: vi.fn(() => 'loader-token'),
|
||||
hide: vi.fn(),
|
||||
};
|
||||
translate = (<T = string>(key: string) => `translated:${key}` as T) as TranslocoService['translate'];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createComponent() {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...dialogHarness.providers,
|
||||
{
|
||||
provide: BookMetadataManageService,
|
||||
useValue: {
|
||||
toggleFieldLocks,
|
||||
},
|
||||
},
|
||||
createMessageServiceProvider(messageService),
|
||||
{
|
||||
provide: LoadingService,
|
||||
useValue: loadingService,
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new LockUnlockMetadataDialogComponent());
|
||||
component.ngOnInit();
|
||||
return component;
|
||||
}
|
||||
|
||||
it('toggles every lockable field between locked and unlocked states', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.toggleLockAll('LOCK');
|
||||
expect(component.lockableFields.every(field => component.fieldLocks[field] === true)).toBe(true);
|
||||
|
||||
component.toggleLockAll('UNLOCK');
|
||||
expect(component.lockableFields.every(field => component.fieldLocks[field] === false)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns translated labels and icons for unselected, locked, and unlocked states', () => {
|
||||
const component = createComponent();
|
||||
|
||||
expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.unselected');
|
||||
expect(component.getLockIcon('titleLocked')).toBe('');
|
||||
|
||||
component.fieldLocks['titleLocked'] = true;
|
||||
expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.locked');
|
||||
expect(component.getLockIcon('titleLocked')).toBe('pi pi-lock');
|
||||
|
||||
component.fieldLocks['titleLocked'] = false;
|
||||
expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.unlocked');
|
||||
expect(component.getLockIcon('titleLocked')).toBe('pi pi-lock-open');
|
||||
});
|
||||
|
||||
it('resets every field lock back to an unselected state', () => {
|
||||
const component = createComponent();
|
||||
component.toggleLockAll('LOCK');
|
||||
|
||||
component.resetFieldLocks();
|
||||
|
||||
expect(component.lockableFields.every(field => component.fieldLocks[field] === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it('cycles a field through locked, unlocked, and cleared states', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.cycleLockState('titleLocked');
|
||||
expect(component.fieldLocks['titleLocked']).toBe(true);
|
||||
|
||||
component.cycleLockState('titleLocked');
|
||||
expect(component.fieldLocks['titleLocked']).toBe(false);
|
||||
|
||||
component.cycleLockState('titleLocked');
|
||||
expect(component.fieldLocks['titleLocked']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('applies selected field locks, shows a success toast, and closes the dialog', () => {
|
||||
const component = createComponent();
|
||||
component.fieldLocks['titleLocked'] = true;
|
||||
component.fieldLocks['authorsLocked'] = false;
|
||||
component.fieldLocks['subtitleLocked'] = undefined;
|
||||
|
||||
component.applyFieldLocks();
|
||||
|
||||
expect(toggleFieldLocks).toHaveBeenCalledWith(new Set([7, 9]), {
|
||||
titleLocked: 'LOCK',
|
||||
authorsLocked: 'UNLOCK',
|
||||
});
|
||||
expect(loadingService.show).toHaveBeenCalledWith(
|
||||
'translated:book.lockUnlockDialog.toast.updatingFieldLocks'
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-token');
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:book.lockUnlockDialog.toast.updatedSummary',
|
||||
detail: 'translated:book.lockUnlockDialog.toast.updatedDetail',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith('fields-updated');
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when saving fails', () => {
|
||||
toggleFieldLocks.mockReturnValueOnce(throwError(() => new Error('save failed')));
|
||||
const component = createComponent();
|
||||
component.fieldLocks['titleLocked'] = false;
|
||||
|
||||
component.applyFieldLocks();
|
||||
|
||||
expect(toggleFieldLocks).toHaveBeenCalledWith(new Set([7, 9]), {
|
||||
titleLocked: 'UNLOCK',
|
||||
});
|
||||
expect(loadingService.show).toHaveBeenCalledWith(
|
||||
'translated:book.lockUnlockDialog.toast.updatingFieldLocks'
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-token');
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:book.lockUnlockDialog.toast.failedSummary',
|
||||
detail: 'translated:book.lockUnlockDialog.toast.failedDetail',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {CdkDragDrop} from '@angular/cdk/drag-drop';
|
||||
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
import {BookSorter} from './BookSorter';
|
||||
|
||||
describe('BookSorter', () => {
|
||||
it('uses default labels when no transloco service is provided', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
|
||||
expect(sorter.sortOptions[0]).toMatchObject({
|
||||
field: 'title',
|
||||
label: 'Title',
|
||||
direction: SortDirection.ASCENDING
|
||||
});
|
||||
});
|
||||
|
||||
it('uses translated labels when transloco is available', () => {
|
||||
const transloco = {
|
||||
translate: vi.fn((key: string) => `translated:${key}`)
|
||||
} as unknown as TranslocoService;
|
||||
|
||||
const sorter = new BookSorter(() => undefined, transloco);
|
||||
|
||||
expect(sorter.sortOptions[0].label).toBe('translated:book.sorting.options.title');
|
||||
});
|
||||
|
||||
it('supports legacy selectedSort getter and setter', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
const sort: SortOption = {label: 'Title', field: 'title', direction: SortDirection.ASCENDING};
|
||||
|
||||
sorter.selectedSort = sort;
|
||||
expect(sorter.selectedSort).toEqual(sort);
|
||||
|
||||
sorter.selectedSort = undefined;
|
||||
expect(sorter.selectedSortCriteria).toEqual([]);
|
||||
});
|
||||
|
||||
it('sorts by a field and toggles the primary direction on repeat', () => {
|
||||
const onSortChange = vi.fn();
|
||||
const sorter = new BookSorter(onSortChange);
|
||||
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.selectedSortCriteria).toEqual([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING}
|
||||
]);
|
||||
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.selectedSortCriteria[0].direction).toBe(SortDirection.DESCENDING);
|
||||
expect(onSortChange).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('adds, removes, toggles, and reorders criteria', () => {
|
||||
const onSortChange = vi.fn();
|
||||
const sorter = new BookSorter(onSortChange);
|
||||
|
||||
sorter.addSortCriterion('title');
|
||||
sorter.addSortCriterion('author');
|
||||
sorter.addSortCriterion('title');
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title', 'author']);
|
||||
|
||||
sorter.toggleCriterionDirection(1);
|
||||
expect(sorter.selectedSortCriteria[1].direction).toBe(SortDirection.DESCENDING);
|
||||
|
||||
sorter.reorderCriteria({
|
||||
previousIndex: 1,
|
||||
currentIndex: 0
|
||||
} as unknown as CdkDragDrop<SortOption[]>);
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['author', 'title']);
|
||||
|
||||
sorter.removeSortCriterion(0);
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title']);
|
||||
});
|
||||
|
||||
it('omits already-used fields from available options and marks the primary icon', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
|
||||
sorter.setSortCriteria([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING}
|
||||
]);
|
||||
|
||||
const titleOption = sorter.sortOptions.find((option) => option.field === 'title') as SortOption & {icon?: string};
|
||||
|
||||
expect(sorter.getAvailableSortOptions().some((option) => option.field === 'title')).toBe(false);
|
||||
expect(titleOption.icon).toBe('pi pi-arrow-up');
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This popover needs a PrimeNG overlay and drag-drop harness so the
|
||||
// multi-sort reorder and apply flows can be tested against real emitted events.
|
||||
describe.skip('MultiSortPopoverComponent', () => {
|
||||
it('needs an overlay harness for drag-drop reorder and sort application flows', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('TableColumnPreferenceService', () => {
|
||||
let service: TableColumnPreferenceService;
|
||||
let userService: { getCurrentUser: ReturnType<typeof vi.fn>; updateUserSetting: ReturnType<typeof vi.fn> };
|
||||
let messageService: { add: ReturnType<typeof vi.fn> };
|
||||
let translocoService: { translate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
userService = {
|
||||
getCurrentUser: vi.fn(),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string) => `t:${key}`)
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TableColumnPreferenceService,
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(TableColumnPreferenceService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('merges saved preferences with all available columns', () => {
|
||||
const savedPrefs: TableColumnPreference[] = [
|
||||
{field: 'title', visible: false, order: 4},
|
||||
{field: 'authors', visible: true, order: 1},
|
||||
{field: 'fileName', visible: true, order: 0}
|
||||
];
|
||||
|
||||
service.initPreferences(savedPrefs);
|
||||
|
||||
expect(service.preferences().find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: false,
|
||||
order: 4
|
||||
});
|
||||
expect(service.preferences().find(pref => pref.field === 'authors')).toEqual({
|
||||
field: 'authors',
|
||||
visible: true,
|
||||
order: 1
|
||||
});
|
||||
expect(service.allColumns[0]).toEqual({
|
||||
field: 'readStatus',
|
||||
header: 't:book.columnPref.columns.readStatus'
|
||||
});
|
||||
expect(service.visibleColumns.map(column => column.field).slice(0, 2)).toEqual(['readStatus', 'fileName']);
|
||||
});
|
||||
|
||||
it('falls back to defaults when no saved preferences exist', () => {
|
||||
service.initPreferences(undefined);
|
||||
|
||||
expect(service.preferences().length).toBe(service.allColumns.length);
|
||||
expect(service.visibleColumns[0]).toEqual({
|
||||
field: 'readStatus',
|
||||
header: 't:book.columnPref.columns.readStatus'
|
||||
});
|
||||
});
|
||||
|
||||
it('skips persistence when there is no current user', () => {
|
||||
userService.getCurrentUser.mockReturnValue(null);
|
||||
|
||||
service.saveVisibleColumns([{field: 'title'}]);
|
||||
|
||||
expect(userService.updateUserSetting).not.toHaveBeenCalled();
|
||||
expect(messageService.add).not.toHaveBeenCalled();
|
||||
expect(service.preferences().find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: true,
|
||||
order: 0
|
||||
});
|
||||
});
|
||||
|
||||
it('saves preferences and shows a success toast for the current user', () => {
|
||||
userService.getCurrentUser.mockReturnValue({id: 42});
|
||||
|
||||
service.saveVisibleColumns([{field: 'title'}, {field: 'authors'}]);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', expect.any(Array));
|
||||
const savedPrefs = userService.updateUserSetting.mock.calls[0][2] as TableColumnPreference[];
|
||||
expect(savedPrefs.find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: true,
|
||||
order: 0
|
||||
});
|
||||
expect(savedPrefs.find(pref => pref.field === 'authors')).toEqual({
|
||||
field: 'authors',
|
||||
visible: true,
|
||||
order: 1
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 't:book.columnPref.toast.savedSummary',
|
||||
detail: 't:book.columnPref.toast.savedDetail',
|
||||
life: 1500
|
||||
}));
|
||||
});
|
||||
});
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {BookCardLiteComponent} from './book-card-lite-component';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('BookCardLiteComponent', () => {
|
||||
let fixture: ComponentFixture<BookCardLiteComponent>;
|
||||
let component: BookCardLiteComponent;
|
||||
let router: {navigate: ReturnType<typeof vi.fn>};
|
||||
let urlHelper: {
|
||||
getThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {currentUser: ReturnType<typeof vi.fn>};
|
||||
let hostService: {requestBookSwitch: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
router = {navigate: vi.fn()};
|
||||
urlHelper = {
|
||||
getThumbnailUrl: vi.fn(() => '/covers/1'),
|
||||
getAudiobookThumbnailUrl: vi.fn(() => '/covers/audio/1'),
|
||||
};
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({userSettings: {metadataCenterViewMode: 'route'}})),
|
||||
};
|
||||
hostService = {
|
||||
requestBookSwitch: vi.fn(),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [BookCardLiteComponent],
|
||||
providers: [
|
||||
{provide: Router, useValue: router},
|
||||
{provide: UrlHelperService, useValue: urlHelper},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: BookMetadataHostService, useValue: hostService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(BookCardLiteComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('treats a book as audiobook-only when no non-audiobook alternative format exists', () => {
|
||||
component.book = buildBook({
|
||||
primaryFile: {id: 10, bookId: 1, bookType: 'AUDIOBOOK'},
|
||||
alternativeFormats: [{id: 11, bookId: 1, bookType: 'AUDIOBOOK'}],
|
||||
});
|
||||
|
||||
expect(component.isAudiobookOnly()).toBe(true);
|
||||
expect(component.getThumbnailUrl()).toBe('/covers/audio/1');
|
||||
expect(urlHelper.getAudiobookThumbnailUrl).toHaveBeenCalledWith(1, '2026-01-02');
|
||||
});
|
||||
|
||||
it('uses the standard thumbnail when the book has an ebook format available', () => {
|
||||
component.book = buildBook({
|
||||
primaryFile: {id: 10, bookId: 1, bookType: 'AUDIOBOOK'},
|
||||
alternativeFormats: [{id: 11, bookId: 1, bookType: 'EPUB'}],
|
||||
});
|
||||
|
||||
expect(component.isAudiobookOnly()).toBe(false);
|
||||
expect(component.getThumbnailUrl()).toBe('/covers/1');
|
||||
expect(urlHelper.getThumbnailUrl).toHaveBeenCalledWith(1, '2026-01-01');
|
||||
});
|
||||
|
||||
it('navigates to the route-based metadata center when that mode is active', () => {
|
||||
const book = buildBook();
|
||||
|
||||
component.openBookInfo(book);
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/book', 1], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
expect(hostService.requestBookSwitch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('delegates to the metadata host when the user prefers dialog mode', () => {
|
||||
userService.currentUser.mockReturnValue({userSettings: {metadataCenterViewMode: 'dialog'}});
|
||||
const book = buildBook();
|
||||
|
||||
component.openBookInfo(book);
|
||||
|
||||
expect(hostService.requestBookSwitch).toHaveBeenCalledWith(1);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
function buildBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 1,
|
||||
fileName: 'Example Book',
|
||||
metadata: {
|
||||
title: 'Example Book',
|
||||
coverUpdatedOn: '2026-01-01',
|
||||
audiobookCoverUpdatedOn: '2026-01-02',
|
||||
...overrides.metadata,
|
||||
},
|
||||
primaryFile: {
|
||||
id: 10,
|
||||
bookType: 'EPUB',
|
||||
...overrides.primaryFile,
|
||||
},
|
||||
alternativeFormats: overrides.alternativeFormats ?? [],
|
||||
...overrides,
|
||||
} as Book;
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {BookFileService} from '../../service/book-file.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookFileAttacherComponent} from './book-file-attacher.component';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
|
||||
interface DialogData {
|
||||
sourceBook?: Book;
|
||||
sourceBooks?: Book[];
|
||||
}
|
||||
|
||||
type AppSettingsLike = {
|
||||
metadataPersistenceSettings?: {
|
||||
moveFilesToLibraryPattern?: boolean;
|
||||
};
|
||||
} | null;
|
||||
|
||||
function buildBook(overrides: Partial<Book> = {}): Book {
|
||||
const id = overrides.id ?? 1;
|
||||
return {
|
||||
id,
|
||||
libraryId: overrides.libraryId ?? 10,
|
||||
libraryName: overrides.libraryName ?? 'Main Library',
|
||||
metadata: overrides.metadata ?? {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
},
|
||||
primaryFile: overrides.primaryFile,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function setup(options: {
|
||||
dialogData?: DialogData;
|
||||
books?: Book[];
|
||||
appSettings?: AppSettingsLike;
|
||||
attachResult?: Observable<{updatedBook: Book; deletedSourceBookIds: number[]}>;
|
||||
} = {}) {
|
||||
const dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
const config = {
|
||||
data: options.dialogData ?? {},
|
||||
};
|
||||
const booksSignal = signal<Book[]>(options.books ?? []);
|
||||
const bookFileService = {
|
||||
attachBookFiles: vi.fn().mockReturnValue(
|
||||
options.attachResult ?? of({updatedBook: buildBook({id: 999}), deletedSourceBookIds: []})
|
||||
),
|
||||
};
|
||||
const appSettingsService = {
|
||||
appSettings: vi.fn(() => options.appSettings ?? null),
|
||||
};
|
||||
const translocoService = {
|
||||
translate: vi.fn((key: string) => key),
|
||||
};
|
||||
const messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: DynamicDialogConfig, useValue: config},
|
||||
{provide: BookService, useValue: {books: booksSignal}},
|
||||
{provide: BookFileService, useValue: bookFileService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new BookFileAttacherComponent());
|
||||
|
||||
return {
|
||||
component,
|
||||
dialogRef,
|
||||
bookFileService,
|
||||
appSettingsService,
|
||||
translocoService,
|
||||
booksSignal,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookFileAttacherComponent', () => {
|
||||
it('bootstraps a single source book, filters candidates by library/source ids, and applies the moveFiles setting', () => {
|
||||
const sourceBook = buildBook({id: 1, libraryId: 7, metadata: {bookId: 1, title: 'Source', authors: ['Origin']}});
|
||||
const siblingCandidate = buildBook({id: 2, libraryId: 7, metadata: {bookId: 2, title: 'Sibling', authors: ['Match']}});
|
||||
const foreignLibraryBook = buildBook({id: 3, libraryId: 99, metadata: {bookId: 3, title: 'Foreign', authors: ['Other']}});
|
||||
const {component} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, siblingCandidate, foreignLibraryBook],
|
||||
appSettings: {
|
||||
metadataPersistenceSettings: {
|
||||
moveFilesToLibraryPattern: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.sourceBooks).toEqual([sourceBook]);
|
||||
expect(component.isBulkMode).toBe(false);
|
||||
expect(component.moveFiles).toBe(true);
|
||||
expect(component.filteredBooks).toEqual([siblingCandidate]);
|
||||
});
|
||||
|
||||
it('bootstraps bulk mode from sourceBooks and defaults moveFiles to false when settings are unavailable', () => {
|
||||
const sourceA = buildBook({id: 10, libraryId: 4});
|
||||
const sourceB = buildBook({id: 11, libraryId: 4});
|
||||
const target = buildBook({id: 12, libraryId: 4});
|
||||
const {component} = setup({
|
||||
dialogData: {sourceBooks: [sourceA, sourceB]},
|
||||
books: [sourceA, sourceB, target],
|
||||
appSettings: null,
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.sourceBooks).toEqual([sourceA, sourceB]);
|
||||
expect(component.isBulkMode).toBe(true);
|
||||
expect(component.moveFiles).toBe(false);
|
||||
expect(component.filteredBooks).toEqual([target]);
|
||||
});
|
||||
|
||||
it('closes immediately when no source payload is provided', () => {
|
||||
const {component, dialogRef, appSettingsService} = setup({
|
||||
dialogData: {},
|
||||
books: [buildBook({id: 20})],
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
expect(dialogRef.close).toHaveBeenCalledWith();
|
||||
expect(appSettingsService.appSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters candidate books by title and author and resets blank queries to the first twenty matches', () => {
|
||||
const sourceBook = buildBook({id: 1, libraryId: 5, metadata: {bookId: 1, title: 'Source', authors: ['Keeper']}});
|
||||
const matchingByTitle = buildBook({id: 2, libraryId: 5, metadata: {bookId: 2, title: 'Dune Messiah', authors: ['Frank Herbert']}});
|
||||
const matchingByAuthor = buildBook({id: 3, libraryId: 5, metadata: {bookId: 3, title: 'Fahrenheit 451', authors: ['Ray Bradbury']}});
|
||||
const fillerBooks = Array.from({length: 25}, (_, index) =>
|
||||
buildBook({
|
||||
id: index + 10,
|
||||
libraryId: 5,
|
||||
metadata: {bookId: index + 10, title: `Candidate ${index}`, authors: [`Writer ${index}`]},
|
||||
})
|
||||
);
|
||||
const {component} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, matchingByTitle, matchingByAuthor, ...fillerBooks],
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.filteredBooks).toHaveLength(20);
|
||||
|
||||
component.filterBooks({query: ' dune '});
|
||||
expect(component.filteredBooks).toEqual([matchingByTitle]);
|
||||
|
||||
component.filterBooks({query: 'bradbury'});
|
||||
expect(component.filteredBooks).toEqual([matchingByAuthor]);
|
||||
|
||||
component.filterBooks({query: ' '});
|
||||
expect(component.filteredBooks).toHaveLength(20);
|
||||
expect(component.filteredBooks[0]).toEqual(matchingByTitle);
|
||||
});
|
||||
|
||||
it('handles lightweight selection events and formats display helpers with fallbacks', () => {
|
||||
const selectedBook = buildBook({
|
||||
id: 30,
|
||||
metadata: {bookId: 30, title: 'The Left Hand of Darkness', authors: ['Ursula K. Le Guin', 'Guest Author']},
|
||||
primaryFile: {id: 301, bookId: 30, extension: 'epub', fileName: 'left-hand.epub'},
|
||||
});
|
||||
const untitledBook = buildBook({id: 31, metadata: undefined, primaryFile: undefined});
|
||||
const {component, translocoService} = setup();
|
||||
|
||||
component.onBookSelect({value: selectedBook} as never);
|
||||
expect(component.targetBook).toEqual(selectedBook);
|
||||
|
||||
component.onBookClear();
|
||||
expect(component.targetBook).toBeNull();
|
||||
|
||||
expect(component.getBookDisplayName(selectedBook)).toBe('The Left Hand of Darkness - Ursula K. Le Guin, Guest Author');
|
||||
expect(component.getBookDisplayName(untitledBook)).toBe('Book #31');
|
||||
expect(component.getSourceFileInfo(selectedBook)).toBe('EPUB - left-hand.epub');
|
||||
expect(component.getSourceFileInfo(untitledBook)).toBe('book.fileAttacher.unknownFile');
|
||||
expect(translocoService.translate).toHaveBeenCalledWith('book.fileAttacher.unknownFile');
|
||||
});
|
||||
|
||||
it('uses the target selection and defaulted moveFiles value when attach succeeds', () => {
|
||||
const sourceBook = buildBook({id: 40, libraryId: 8});
|
||||
const targetBook = buildBook({id: 41, libraryId: 8});
|
||||
const {component, bookFileService, dialogRef} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, targetBook],
|
||||
appSettings: null,
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
component.targetBook = targetBook;
|
||||
|
||||
component.attach();
|
||||
|
||||
expect(bookFileService.attachBookFiles).toHaveBeenCalledWith(41, [40], false);
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({success: true});
|
||||
});
|
||||
|
||||
it('resets attaching state when attach fails and preserves the dialog', () => {
|
||||
const sourceBook = buildBook({id: 50, libraryId: 9});
|
||||
const targetBook = buildBook({id: 51, libraryId: 9});
|
||||
const {component, bookFileService, dialogRef} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook, targetBook],
|
||||
appSettings: {
|
||||
metadataPersistenceSettings: {
|
||||
moveFilesToLibraryPattern: true,
|
||||
},
|
||||
},
|
||||
attachResult: throwError(() => new Error('attach failed')),
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
component.targetBook = targetBook;
|
||||
|
||||
component.attach();
|
||||
|
||||
expect(bookFileService.attachBookFiles).toHaveBeenCalledWith(51, [50], true);
|
||||
expect(component.isAttaching).toBe(false);
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not attach without a target book and exposes direct close behavior', () => {
|
||||
const sourceBook = buildBook({id: 60});
|
||||
const {component, bookFileService, dialogRef} = setup({
|
||||
dialogData: {sourceBook},
|
||||
books: [sourceBook],
|
||||
});
|
||||
|
||||
component.ngOnInit();
|
||||
component.attach();
|
||||
component.closeDialog();
|
||||
|
||||
expect(component.canAttach()).toBe(false);
|
||||
expect(bookFileService.attachBookFiles).not.toHaveBeenCalled();
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
expect(dialogRef.close).toHaveBeenCalledWith();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {BookNote, BookNoteService} from '../../../../shared/service/book-note.service';
|
||||
import {BookNotesComponent} from './book-notes-component';
|
||||
|
||||
interface ConfirmationLike {
|
||||
key?: string;
|
||||
message?: string;
|
||||
header?: string;
|
||||
accept?: () => void;
|
||||
}
|
||||
|
||||
function createNote(id: number, overrides: Partial<BookNote> = {}): BookNote {
|
||||
return {
|
||||
id,
|
||||
userId: 7,
|
||||
bookId: 42,
|
||||
title: `Note ${id}`,
|
||||
content: `Content ${id}`,
|
||||
createdAt: '2026-03-28T09:00:00.000Z',
|
||||
updatedAt: `2026-03-28T09:0${id}:00.000Z`,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookNotesComponent', () => {
|
||||
let component: BookNotesComponent;
|
||||
let bookNoteService: {
|
||||
getNotesForBook: ReturnType<typeof vi.fn>;
|
||||
createOrUpdateNote: ReturnType<typeof vi.fn>;
|
||||
deleteNote: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let messageService: {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let confirmationService: {
|
||||
confirm: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let lastConfirmation: ConfirmationLike | null;
|
||||
|
||||
function createComponent(): BookNotesComponent {
|
||||
return TestBed.runInInjectionContext(() => new BookNotesComponent());
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
lastConfirmation = null;
|
||||
bookNoteService = {
|
||||
getNotesForBook: vi.fn(),
|
||||
createOrUpdateNote: vi.fn(),
|
||||
deleteNote: vi.fn(),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
confirmationService = {
|
||||
confirm: vi.fn((confirmation: ConfirmationLike) => {
|
||||
lastConfirmation = confirmation;
|
||||
}),
|
||||
};
|
||||
translate = vi.fn((key: string, params?: Record<string, unknown>) => (
|
||||
params ? `${key}:${JSON.stringify(params)}` : key
|
||||
));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: BookNoteService, useValue: bookNoteService},
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
component = createComponent();
|
||||
component.bookId = 42;
|
||||
});
|
||||
|
||||
it('skips loading notes when no book is selected', () => {
|
||||
component.bookId = 0;
|
||||
|
||||
component.loadNotes();
|
||||
|
||||
expect(bookNoteService.getNotesForBook).not.toHaveBeenCalled();
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('loads notes and orders them by most recent update first', () => {
|
||||
const oldest = createNote(1, {updatedAt: '2026-03-28T08:00:00.000Z'});
|
||||
const newest = createNote(2, {updatedAt: '2026-03-28T12:00:00.000Z'});
|
||||
const middle = createNote(3, {updatedAt: '2026-03-28T10:00:00.000Z'});
|
||||
bookNoteService.getNotesForBook.mockReturnValue(of([oldest, newest, middle]));
|
||||
|
||||
component.loadNotes();
|
||||
|
||||
expect(bookNoteService.getNotesForBook).toHaveBeenCalledWith(42);
|
||||
expect(component.notes.map(note => note.id)).toEqual([2, 3, 1]);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('shows an error toast when loading notes fails', () => {
|
||||
bookNoteService.getNotesForBook.mockReturnValue(throwError(() => new Error('load failed')));
|
||||
|
||||
component.loadNotes();
|
||||
|
||||
expect(component.loading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.loadFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('blocks note creation when title or content is blank after trimming', () => {
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: ' ',
|
||||
content: ' ',
|
||||
};
|
||||
|
||||
component.createNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'book.notes.toast.validationSummary',
|
||||
detail: 'book.notes.toast.validationDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a note and closes the create dialog on success', () => {
|
||||
const createdNote = createNote(9, {title: 'Created', content: 'Fresh content'});
|
||||
component.notes = [createNote(1)];
|
||||
component.showCreateDialog = true;
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: 'Created',
|
||||
content: 'Fresh content',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(of(createdNote));
|
||||
|
||||
component.createNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).toHaveBeenCalledWith(component.newNote);
|
||||
expect(component.notes[0]).toEqual(createdNote);
|
||||
expect(component.showCreateDialog).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'common.success',
|
||||
detail: 'book.notes.toast.createSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when note creation fails', () => {
|
||||
component.showCreateDialog = true;
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: 'Created',
|
||||
content: 'Fresh content',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(throwError(() => new Error('create failed')));
|
||||
|
||||
component.createNote();
|
||||
|
||||
expect(component.showCreateDialog).toBe(true);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.createFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('blocks note updates when title or content is blank after trimming', () => {
|
||||
component.editNote = {
|
||||
id: 4,
|
||||
bookId: 42,
|
||||
title: ' ',
|
||||
content: ' ',
|
||||
};
|
||||
|
||||
component.updateNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'book.notes.toast.validationSummary',
|
||||
detail: 'book.notes.toast.validationDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('updates an existing note, resorts the list, and clears edit state on success', () => {
|
||||
const staleNote = createNote(1, {updatedAt: '2026-03-28T08:00:00.000Z', title: 'Old title'});
|
||||
const selectedNote = createNote(2, {updatedAt: '2026-03-28T10:00:00.000Z', title: 'Before edit'});
|
||||
const updatedNote = createNote(2, {
|
||||
updatedAt: '2026-03-28T14:00:00.000Z',
|
||||
title: 'After edit',
|
||||
content: 'Updated body',
|
||||
});
|
||||
component.notes = [staleNote, selectedNote];
|
||||
component.selectedNote = selectedNote;
|
||||
component.showEditDialog = true;
|
||||
component.editNote = {
|
||||
id: 2,
|
||||
bookId: 42,
|
||||
title: 'After edit',
|
||||
content: 'Updated body',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(of(updatedNote));
|
||||
|
||||
component.updateNote();
|
||||
|
||||
expect(bookNoteService.createOrUpdateNote).toHaveBeenCalledWith(component.editNote);
|
||||
expect(component.notes.map(note => note.id)).toEqual([2, 1]);
|
||||
expect(component.notes[0]).toEqual(updatedNote);
|
||||
expect(component.showEditDialog).toBe(false);
|
||||
expect(component.selectedNote).toBeNull();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'common.success',
|
||||
detail: 'book.notes.toast.updateSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when updating a note fails', () => {
|
||||
const selectedNote = createNote(2, {title: 'Before edit'});
|
||||
component.selectedNote = selectedNote;
|
||||
component.showEditDialog = true;
|
||||
component.editNote = {
|
||||
id: 2,
|
||||
bookId: 42,
|
||||
title: 'After edit',
|
||||
content: 'Updated body',
|
||||
};
|
||||
bookNoteService.createOrUpdateNote.mockReturnValue(throwError(() => new Error('update failed')));
|
||||
|
||||
component.updateNote();
|
||||
|
||||
expect(component.showEditDialog).toBe(true);
|
||||
expect(component.selectedNote).toEqual(selectedNote);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.updateFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('confirms note deletion and removes the note when the accept callback succeeds', () => {
|
||||
const keepNote = createNote(1);
|
||||
const deleteCandidate = createNote(2, {title: 'Delete me'});
|
||||
component.notes = [keepNote, deleteCandidate];
|
||||
bookNoteService.deleteNote.mockReturnValue(of(void 0));
|
||||
|
||||
component.deleteNote(deleteCandidate);
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
key: 'deleteNote',
|
||||
header: 'book.notes.confirm.deleteHeader',
|
||||
message: 'book.notes.confirm.deleteMessage:{"title":"Delete me"}',
|
||||
});
|
||||
expect(bookNoteService.deleteNote).toHaveBeenCalledWith(2);
|
||||
expect(component.notes).toEqual([keepNote]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'common.success',
|
||||
detail: 'book.notes.toast.deleteSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when the confirmed delete fails', () => {
|
||||
const note = createNote(3, {title: 'Delete me'});
|
||||
component.notes = [note];
|
||||
bookNoteService.deleteNote.mockReturnValue(throwError(() => new Error('delete failed')));
|
||||
|
||||
component.deleteNote(note);
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(bookNoteService.deleteNote).toHaveBeenCalledWith(3);
|
||||
expect(component.notes).toEqual([note]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'book.notes.toast.deleteFailedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('resets create and edit state when dialogs are cancelled', () => {
|
||||
const selectedNote = createNote(4);
|
||||
component.showCreateDialog = true;
|
||||
component.newNote = {
|
||||
bookId: 42,
|
||||
title: 'Draft title',
|
||||
content: 'Draft content',
|
||||
};
|
||||
component.showEditDialog = true;
|
||||
component.selectedNote = selectedNote;
|
||||
component.editNote = {
|
||||
id: selectedNote.id,
|
||||
bookId: 42,
|
||||
title: 'Edited title',
|
||||
content: 'Edited content',
|
||||
};
|
||||
|
||||
component.cancelCreate();
|
||||
component.cancelEdit();
|
||||
|
||||
expect(component.showCreateDialog).toBe(false);
|
||||
expect(component.newNote).toEqual({
|
||||
bookId: 42,
|
||||
title: '',
|
||||
content: '',
|
||||
});
|
||||
expect(component.showEditDialog).toBe(false);
|
||||
expect(component.selectedNote).toBeNull();
|
||||
expect(component.editNote).toEqual({
|
||||
bookId: 42,
|
||||
title: '',
|
||||
content: '',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookReviewService} from './book-review-service';
|
||||
|
||||
describe('BookReviewService', () => {
|
||||
let service: BookReviewService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookReviewService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookReviewService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads reviews for a specific book', () => {
|
||||
let responseBody: unknown;
|
||||
|
||||
service.getByBookId(7).subscribe(response => {
|
||||
responseBody = response;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'GET' && req.url.endsWith('/api/v1/reviews/book/7')
|
||||
);
|
||||
request.flush([{id: 1, title: 'Great review'}]);
|
||||
|
||||
expect(responseBody).toEqual([{id: 1, title: 'Great review'}]);
|
||||
});
|
||||
|
||||
it('refreshes reviews through the refresh endpoint', () => {
|
||||
service.refreshReviews(9).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'POST' && req.url.endsWith('/api/v1/reviews/book/9/refresh')
|
||||
);
|
||||
expect(request.request.body).toEqual({});
|
||||
request.flush([{id: 3, title: 'Fresh review'}]);
|
||||
});
|
||||
|
||||
it('deletes a single review by id', () => {
|
||||
service.delete(11).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'DELETE' && req.url.endsWith('/api/v1/reviews/11')
|
||||
);
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('deletes all reviews for a book', () => {
|
||||
service.deleteAllByBookId(12).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'DELETE' && req.url.endsWith('/api/v1/reviews/book/12')
|
||||
);
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
import {SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {BookReview, BookReviewService} from './book-review-service';
|
||||
import {BookReviewsComponent} from './book-reviews.component';
|
||||
|
||||
interface ConfirmationLike {
|
||||
message?: string;
|
||||
header?: string;
|
||||
accept?: () => void;
|
||||
}
|
||||
|
||||
function createReview(id: number, overrides: Partial<BookReview> = {}): BookReview {
|
||||
return {
|
||||
id,
|
||||
metadataProvider: 'goodreads',
|
||||
reviewerName: `Reviewer ${id}`,
|
||||
title: `Review ${id}`,
|
||||
rating: 4,
|
||||
date: `2026-03-${String(id).padStart(2, '0')}T12:00:00.000Z`,
|
||||
body: `Review body ${id}`,
|
||||
country: 'US',
|
||||
spoiler: false,
|
||||
followersCount: 10,
|
||||
textReviewsCount: 20,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookReviewsComponent', () => {
|
||||
let component: BookReviewsComponent;
|
||||
let reviewService: {
|
||||
getByBookId: ReturnType<typeof vi.fn>;
|
||||
refreshReviews: ReturnType<typeof vi.fn>;
|
||||
delete: ReturnType<typeof vi.fn>;
|
||||
deleteAllByBookId: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookService: {
|
||||
findBookById: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bookMetadataManageService: {
|
||||
toggleFieldLocks: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let confirmationService: {
|
||||
confirm: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let messageService: {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {
|
||||
currentUser: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let appSettingsService: {
|
||||
appSettings: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
let lastConfirmation: ConfirmationLike | null;
|
||||
|
||||
function createComponent(): BookReviewsComponent {
|
||||
return TestBed.runInInjectionContext(() => new BookReviewsComponent());
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
lastConfirmation = null;
|
||||
reviewService = {
|
||||
getByBookId: vi.fn(),
|
||||
refreshReviews: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteAllByBookId: vi.fn(),
|
||||
};
|
||||
bookService = {
|
||||
findBookById: vi.fn(),
|
||||
};
|
||||
bookMetadataManageService = {
|
||||
toggleFieldLocks: vi.fn(),
|
||||
};
|
||||
confirmationService = {
|
||||
confirm: vi.fn((confirmation: ConfirmationLike) => {
|
||||
lastConfirmation = confirmation;
|
||||
}),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canEditMetadata: true,
|
||||
},
|
||||
})),
|
||||
};
|
||||
appSettingsService = {
|
||||
appSettings: vi.fn(() => ({
|
||||
metadataPublicReviewsSettings: {
|
||||
downloadEnabled: false,
|
||||
},
|
||||
})),
|
||||
};
|
||||
translate = vi.fn((key: string, params?: Record<string, unknown>) => (
|
||||
params ? `${key}:${JSON.stringify(params)}` : key
|
||||
));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: BookReviewService, useValue: reviewService},
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: BookMetadataManageService, useValue: bookMetadataManageService},
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
component = createComponent();
|
||||
component.bookId = 42;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads reviews on book changes, sorts them by date, and mirrors the current lock state', () => {
|
||||
const undated = createReview(1, {date: undefined});
|
||||
const oldest = createReview(2, {date: '2026-03-02T12:00:00.000Z'});
|
||||
const newest = createReview(3, {date: '2026-03-03T12:00:00.000Z'});
|
||||
reviewService.getByBookId.mockReturnValue(of([oldest, undated, newest]));
|
||||
bookService.findBookById.mockReturnValue({
|
||||
metadata: {
|
||||
reviewsLocked: true,
|
||||
},
|
||||
});
|
||||
|
||||
component.ngOnChanges({
|
||||
bookId: new SimpleChange(undefined, 42, true),
|
||||
});
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(bookService.findBookById).toHaveBeenCalledWith(42);
|
||||
expect(reviewService.getByBookId).toHaveBeenCalledWith(42);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([3, 2, 1]);
|
||||
expect(component.reviewsLocked).toBe(true);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('refreshes reviews, clears revealed spoilers, and shows a success toast', () => {
|
||||
const spoilerReview = createReview(5, {spoiler: true, date: '2026-03-05T12:00:00.000Z'});
|
||||
const plainReview = createReview(4, {date: '2026-03-04T12:00:00.000Z'});
|
||||
reviewService.refreshReviews.mockReturnValue(of([plainReview, spoilerReview]));
|
||||
component.revealedSpoilers.add(spoilerReview.id!);
|
||||
component.allSpoilersRevealed = true;
|
||||
|
||||
component.fetchNewReviews();
|
||||
|
||||
expect(reviewService.refreshReviews).toHaveBeenCalledWith(42);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([5, 4]);
|
||||
expect(component.revealedSpoilers.size).toBe(0);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
expect(component.loading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.reviews.toast.reviewsUpdatedSummary',
|
||||
detail: 'book.reviews.toast.reviewsUpdatedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when refreshing reviews fails', () => {
|
||||
const error = new Error('refresh failed');
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
reviewService.refreshReviews.mockReturnValue(throwError(() => error));
|
||||
|
||||
component.fetchNewReviews();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledWith('Failed to fetch new reviews:', error);
|
||||
expect(component.loading).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'book.reviews.toast.fetchFailedSummary',
|
||||
detail: 'book.reviews.toast.fetchFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('confirms single-review deletion, removes the review, and recomputes spoiler state', () => {
|
||||
const keepReview = createReview(1, {spoiler: false});
|
||||
const deleteReview = createReview(2, {spoiler: true});
|
||||
reviewService.delete.mockReturnValue(of(void 0));
|
||||
component.reviews = [keepReview, deleteReview];
|
||||
component.revealedSpoilers.add(deleteReview.id!);
|
||||
component.allSpoilersRevealed = true;
|
||||
|
||||
component.deleteReview(deleteReview);
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'book.reviews.confirm.deleteMessage:{"reviewer":"Reviewer 2"}',
|
||||
header: 'book.reviews.confirm.deleteHeader',
|
||||
});
|
||||
expect(reviewService.delete).toHaveBeenCalledWith(2);
|
||||
expect(component.reviews).toEqual([keepReview]);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.reviews.toast.deleteSuccessSummary',
|
||||
detail: 'book.reviews.toast.deleteSuccessDetail',
|
||||
life: 2000,
|
||||
});
|
||||
});
|
||||
|
||||
it('confirms deleting all reviews and clears state after the accept callback succeeds', () => {
|
||||
const firstReview = createReview(7, {spoiler: true});
|
||||
const secondReview = createReview(8, {spoiler: false});
|
||||
reviewService.deleteAllByBookId.mockReturnValue(of(void 0));
|
||||
component.reviews = [firstReview, secondReview];
|
||||
component.revealedSpoilers.add(firstReview.id!);
|
||||
component.allSpoilersRevealed = true;
|
||||
|
||||
component.deleteAllReviews();
|
||||
lastConfirmation?.accept?.();
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'book.reviews.confirm.deleteAllMessage:{"count":2}',
|
||||
header: 'book.reviews.confirm.deleteAllHeader',
|
||||
});
|
||||
expect(reviewService.deleteAllByBookId).toHaveBeenCalledWith(42);
|
||||
expect(component.reviews).toEqual([]);
|
||||
expect(component.revealedSpoilers.size).toBe(0);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.reviews.toast.allDeletedSummary',
|
||||
detail: 'book.reviews.toast.allDeletedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('sends lock and unlock actions through the metadata service and reports the result', () => {
|
||||
bookMetadataManageService.toggleFieldLocks.mockReturnValue(of(void 0));
|
||||
|
||||
component.reviewsLocked = false;
|
||||
component.toggleReviewsLock();
|
||||
|
||||
component.reviewsLocked = true;
|
||||
component.toggleReviewsLock();
|
||||
|
||||
expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenNthCalledWith(1, [42], {
|
||||
reviewsLocked: 'LOCK',
|
||||
});
|
||||
expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenNthCalledWith(2, [42], {
|
||||
reviewsLocked: 'UNLOCK',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(1, {
|
||||
severity: 'info',
|
||||
summary: 'book.reviews.toast.lockedSummary',
|
||||
detail: 'book.reviews.toast.lockedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(2, {
|
||||
severity: 'info',
|
||||
summary: 'book.reviews.toast.unlockedSummary',
|
||||
detail: 'book.reviews.toast.unlockedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when lock toggling fails', () => {
|
||||
const error = new Error('toggle failed');
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
bookMetadataManageService.toggleFieldLocks.mockReturnValue(throwError(() => error));
|
||||
|
||||
component.toggleReviewsLock();
|
||||
|
||||
expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenCalledWith([42], {
|
||||
reviewsLocked: 'LOCK',
|
||||
});
|
||||
expect(errorSpy).toHaveBeenCalledWith('Failed to toggle lock status:', error);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'book.reviews.toast.lockFailedSummary',
|
||||
detail: 'book.reviews.toast.lockFailedDetail',
|
||||
life: 3000,
|
||||
});
|
||||
});
|
||||
|
||||
it('tracks spoiler visibility for individual and bulk reveal flows', () => {
|
||||
const firstSpoiler = createReview(9, {spoiler: true});
|
||||
const secondSpoiler = createReview(10, {spoiler: true});
|
||||
const nonSpoiler = createReview(11, {spoiler: false});
|
||||
component.reviews = [firstSpoiler, secondSpoiler, nonSpoiler];
|
||||
|
||||
component.revealSpoiler(firstSpoiler.id!);
|
||||
expect(component.isSpoilerRevealed(firstSpoiler.id!)).toBe(true);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
|
||||
component.toggleSpoilerVisibility();
|
||||
expect(component.isSpoilerRevealed(secondSpoiler.id!)).toBe(true);
|
||||
expect(component.allSpoilersRevealed).toBe(true);
|
||||
|
||||
component.toggleSpoilerVisibility();
|
||||
expect(component.revealedSpoilers.size).toBe(0);
|
||||
expect(component.allSpoilersRevealed).toBe(false);
|
||||
});
|
||||
|
||||
it('toggles sort order and reorders dated and undated reviews accordingly', () => {
|
||||
const newest = createReview(12, {date: '2026-03-12T12:00:00.000Z'});
|
||||
const oldest = createReview(13, {date: '2026-03-01T12:00:00.000Z'});
|
||||
const undated = createReview(14, {date: undefined});
|
||||
component.reviews = [newest, undated, oldest];
|
||||
|
||||
component.toggleSortOrder();
|
||||
expect(component.sortAscending).toBe(true);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([14, 13, 12]);
|
||||
|
||||
component.toggleSortOrder();
|
||||
expect(component.sortAscending).toBe(false);
|
||||
expect(component.reviews?.map(review => review.id)).toEqual([12, 13, 14]);
|
||||
});
|
||||
|
||||
it('derives permission and app-setting state and exposes helper formatting behavior', () => {
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.hasPermission).toBe(true);
|
||||
expect(component.reviewDownloadEnabled).toBe(false);
|
||||
expect(component.getProviderSeverity('amazon')).toBe('warn');
|
||||
expect(component.getProviderSeverity('goodreads')).toBe('success');
|
||||
expect(component.formatDate('2026-03-28T12:00:00.000Z')).toBe('March 28, 2026');
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around debounced signal-to-observable
|
||||
// search state, global document click listeners, and router navigation so search dropdown behavior
|
||||
// can be tested without a browser-event harness.
|
||||
describe.skip('BookSearcherComponent', () => {
|
||||
it('needs debounce seams to verify filtered-book output, loading state, and active-index reset behavior', () => {
|
||||
// TODO(seam): Cover the debounced search signal and filteredBooks computed state once timing concerns are extracted for direct control.
|
||||
});
|
||||
|
||||
it('needs event seams to verify keyboard navigation, outside-click clearing, and routed book selection', () => {
|
||||
// TODO(seam): Cover onKeydown and onDocumentClick after isolating host listeners and router side effects behind adapters.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,367 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {beforeEach, afterEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {
|
||||
AdditionalFile,
|
||||
AdditionalFileType,
|
||||
Book,
|
||||
BookFile,
|
||||
} from '../../model/book.model';
|
||||
import {BookSenderComponent} from './book-sender.component';
|
||||
import {EmailProvider} from '../../../settings/email-v2/email-provider.model';
|
||||
import {EmailRecipient} from '../../../settings/email-v2/email-recipient.model';
|
||||
import {EmailService} from '../../../settings/email-v2/email.service';
|
||||
import {EmailV2ProviderService} from '../../../settings/email-v2/email-v2-provider/email-v2-provider.service';
|
||||
import {EmailV2RecipientService} from '../../../settings/email-v2/email-v2-recipient/email-v2-recipient.service';
|
||||
|
||||
type EmailBookRequest = Parameters<EmailService['emailBook']>[0];
|
||||
|
||||
describe('BookSenderComponent', () => {
|
||||
let emailProviders: EmailProvider[];
|
||||
let emailRecipients: EmailRecipient[];
|
||||
let emailBookError: Error | null;
|
||||
|
||||
const providerService = {
|
||||
getEmailProviders: vi.fn(() => of(emailProviders)),
|
||||
};
|
||||
const recipientService = {
|
||||
getRecipients: vi.fn(() => of(emailRecipients)),
|
||||
};
|
||||
const emailService = {
|
||||
emailBook: vi.fn((request: EmailBookRequest) => {
|
||||
void request;
|
||||
return emailBookError
|
||||
? throwError(() => emailBookError)
|
||||
: of(void 0);
|
||||
}),
|
||||
};
|
||||
const messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
const dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
const translocoService = {
|
||||
translate: vi.fn((key: string) => key),
|
||||
};
|
||||
const dialogConfig: {data: {book: Book}} = {
|
||||
data: {book: createBook()},
|
||||
};
|
||||
|
||||
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
emailProviders = [
|
||||
createProvider({
|
||||
id: 101,
|
||||
name: 'Primary SMTP',
|
||||
fromAddress: 'books@example.com',
|
||||
host: 'smtp.primary.test',
|
||||
}),
|
||||
createProvider({
|
||||
id: 102,
|
||||
name: 'Fallback SMTP',
|
||||
fromAddress: '',
|
||||
host: 'smtp.fallback.test',
|
||||
}),
|
||||
];
|
||||
emailRecipients = [
|
||||
createRecipient({
|
||||
id: 201,
|
||||
name: 'Alice Reader',
|
||||
email: 'alice@example.com',
|
||||
}),
|
||||
];
|
||||
emailBookError = null;
|
||||
|
||||
providerService.getEmailProviders.mockClear();
|
||||
recipientService.getRecipients.mockClear();
|
||||
emailService.emailBook.mockClear();
|
||||
messageService.add.mockClear();
|
||||
dialogRef.close.mockClear();
|
||||
translocoService.translate.mockClear();
|
||||
|
||||
dialogConfig.data = {book: createBook()};
|
||||
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: EmailV2ProviderService, useValue: providerService},
|
||||
{provide: EmailV2RecipientService, useValue: recipientService},
|
||||
{provide: EmailService, useValue: emailService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: DynamicDialogConfig, useValue: dialogConfig},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleErrorSpy.mockRestore();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('builds emailable files and maps provider and recipient options on init', () => {
|
||||
const component = instantiateComponent(createBook({
|
||||
primaryFile: createBookFile({
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
bookType: 'EPUB',
|
||||
fileSizeKb: 512,
|
||||
}),
|
||||
alternativeFormats: [
|
||||
createAdditionalFile({
|
||||
id: 22,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 4096,
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
}),
|
||||
createAdditionalFile({
|
||||
id: 33,
|
||||
bookId: 1,
|
||||
bookType: 'MOBI',
|
||||
fileSizeKb: 2048,
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
}),
|
||||
],
|
||||
supplementaryFiles: [
|
||||
createAdditionalFile({
|
||||
id: 44,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 128,
|
||||
additionalFileType: AdditionalFileType.SUPPLEMENTARY,
|
||||
}),
|
||||
],
|
||||
}));
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(providerService.getEmailProviders).toHaveBeenCalledOnce();
|
||||
expect(recipientService.getRecipients).toHaveBeenCalledOnce();
|
||||
expect(component.emailProviders).toEqual([
|
||||
{
|
||||
label: 'Primary SMTP | books@example.com',
|
||||
value: emailProviders[0],
|
||||
},
|
||||
{
|
||||
label: 'Fallback SMTP | smtp.fallback.test',
|
||||
value: emailProviders[1],
|
||||
},
|
||||
]);
|
||||
expect(component.emailRecipients).toEqual([
|
||||
{
|
||||
label: 'Alice Reader | alice@example.com',
|
||||
value: emailRecipients[0],
|
||||
},
|
||||
]);
|
||||
expect(component.selectedFileId).toBe(11);
|
||||
expect(component.emailableFiles).toHaveLength(3);
|
||||
expect(component.emailableFiles.map(file => file.id)).toEqual([11, 22, 33]);
|
||||
expect(component.emailableFiles).toMatchObject([
|
||||
{id: 11, bookType: 'EPUB', fileSizeKb: 512, isPrimary: true},
|
||||
{id: 22, bookType: 'PDF', fileSizeKb: 4096, isPrimary: false},
|
||||
{id: 33, bookType: 'MOBI', fileSizeKb: 2048, isPrimary: false},
|
||||
]);
|
||||
});
|
||||
|
||||
it('formats file sizes across empty, kilobyte, and megabyte values', () => {
|
||||
const component = instantiateComponent();
|
||||
|
||||
expect(component.formatFileSize()).toBe('-');
|
||||
expect(component.formatFileSize(512)).toBe('512 KB');
|
||||
expect(component.formatFileSize(1536)).toBe('1.50 MB');
|
||||
});
|
||||
|
||||
it('shows the large-file warning only for selected files above the threshold', () => {
|
||||
const component = instantiateComponent(createBook({
|
||||
primaryFile: createBookFile({
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
fileSizeKb: 512,
|
||||
}),
|
||||
alternativeFormats: [
|
||||
createAdditionalFile({
|
||||
id: 22,
|
||||
bookId: 1,
|
||||
fileSizeKb: 30 * 1024,
|
||||
}),
|
||||
],
|
||||
}));
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.showLargeFileWarning).toBe(false);
|
||||
|
||||
component.selectedFileId = 22;
|
||||
expect(component.showLargeFileWarning).toBe(true);
|
||||
|
||||
component.selectedFileId = undefined;
|
||||
expect(component.showLargeFileWarning).toBe(false);
|
||||
});
|
||||
|
||||
it('shows validation errors and does not send when provider, recipient, or book are missing', () => {
|
||||
const component = instantiateComponent(createBook({id: 0}));
|
||||
|
||||
component.sendBook();
|
||||
|
||||
expect(emailService.emailBook).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledTimes(3);
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(1, {
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.providerMissingSummary',
|
||||
detail: 'book.sender.toast.providerMissingDetail',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(2, {
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.recipientMissingSummary',
|
||||
detail: 'book.sender.toast.recipientMissingDetail',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenNthCalledWith(3, {
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.bookNotSelectedSummary',
|
||||
detail: 'book.sender.toast.bookNotSelectedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the selected file and closes the dialog after a successful response', () => {
|
||||
const component = instantiateComponent();
|
||||
component.ngOnInit();
|
||||
component.selectedProvider = component.emailProviders[0];
|
||||
component.selectedRecipient = component.emailRecipients[0];
|
||||
component.selectedFileId = 22;
|
||||
|
||||
component.sendBook();
|
||||
|
||||
expect(emailService.emailBook).toHaveBeenCalledWith({
|
||||
bookId: 1,
|
||||
providerId: 101,
|
||||
recipientId: 201,
|
||||
bookFileId: 22,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.sender.toast.emailScheduledSummary',
|
||||
detail: 'book.sender.toast.emailScheduledDetail',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when sending fails', () => {
|
||||
emailBookError = new Error('SMTP rejected request');
|
||||
|
||||
const component = instantiateComponent();
|
||||
component.ngOnInit();
|
||||
component.selectedProvider = component.emailProviders[0];
|
||||
component.selectedRecipient = component.emailRecipients[0];
|
||||
|
||||
component.sendBook();
|
||||
|
||||
expect(emailService.emailBook).toHaveBeenCalledWith({
|
||||
bookId: 1,
|
||||
providerId: 101,
|
||||
recipientId: 201,
|
||||
bookFileId: 11,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'book.sender.toast.sendingFailedSummary',
|
||||
detail: 'book.sender.toast.sendingFailedDetail',
|
||||
});
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
expect(consoleErrorSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
function instantiateComponent(book: Book = createBook()): BookSenderComponent {
|
||||
dialogConfig.data = {book};
|
||||
return TestBed.runInInjectionContext(() => new BookSenderComponent());
|
||||
}
|
||||
});
|
||||
|
||||
function createBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 1,
|
||||
libraryId: 7,
|
||||
libraryName: 'Main Library',
|
||||
primaryFile: createBookFile({
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
bookType: 'EPUB',
|
||||
fileSizeKb: 512,
|
||||
}),
|
||||
alternativeFormats: [
|
||||
createAdditionalFile({
|
||||
id: 22,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 2048,
|
||||
}),
|
||||
],
|
||||
supplementaryFiles: [
|
||||
createAdditionalFile({
|
||||
id: 44,
|
||||
bookId: 1,
|
||||
bookType: 'PDF',
|
||||
fileSizeKb: 128,
|
||||
additionalFileType: AdditionalFileType.SUPPLEMENTARY,
|
||||
}),
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBookFile(overrides: Partial<BookFile> = {}): BookFile {
|
||||
return {
|
||||
id: 11,
|
||||
bookId: 1,
|
||||
fileName: 'book.epub',
|
||||
bookType: 'EPUB',
|
||||
fileSizeKb: 512,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createAdditionalFile(overrides: Partial<AdditionalFile> = {}): AdditionalFile {
|
||||
return {
|
||||
...createBookFile(),
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createProvider(overrides: Partial<EmailProvider> = {}): EmailProvider {
|
||||
return {
|
||||
isEditing: false,
|
||||
id: 101,
|
||||
userId: 1,
|
||||
name: 'Primary SMTP',
|
||||
host: 'smtp.example.test',
|
||||
port: 587,
|
||||
username: 'mailer',
|
||||
password: 'secret',
|
||||
fromAddress: 'books@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: true,
|
||||
shared: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createRecipient(overrides: Partial<EmailRecipient> = {}): EmailRecipient {
|
||||
return {
|
||||
id: 201,
|
||||
email: 'alice@example.com',
|
||||
name: 'Alice Reader',
|
||||
defaultRecipient: true,
|
||||
isEditing: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around file-reader input, paced async
|
||||
// import loops, metadata lookup retries, and library-service state so ISBN parsing and import
|
||||
// progress can be asserted without browser file APIs and timing-heavy runtime behavior.
|
||||
describe.skip('BulkIsbnImportDialogComponent', () => {
|
||||
it('needs parser seams to verify pasted-text parsing, file parsing, duplicate removal, and already-existing ISBN filtering', () => {
|
||||
// TODO(seam): Cover parseContent and related normalization helpers once file-reader inputs and existing-library lookup state are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs async-loop seams to verify import progress, cancellation, retry timing, and summary transitions', () => {
|
||||
// TODO(seam): Cover startImport and progress bookkeeping after metadata lookup, create-book requests, and delay scheduling are extracted into a stable harness.
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around dialog config/bootstrap state,
|
||||
// paginator state, confirmation flows, and multi-step duplicate merge orchestration so the
|
||||
// component can be tested without building a full dialog-plus-confirmation harness.
|
||||
describe.skip('DuplicateMergerComponent', () => {
|
||||
it('needs scanning seams to verify preset toggles, duplicate detection request shaping, and display-group initialization', () => {
|
||||
// TODO(seam): Cover applyPreset and scan once the dialog config and duplicate scan subscription flow are isolated behind test doubles.
|
||||
});
|
||||
|
||||
it('needs merge seams to verify target selection, dismissal, pagination, and attach-file success and failure handling', () => {
|
||||
// TODO(seam): Cover the merge workflow after extracting confirmation, loader, and dialog-close side effects from the component runtime.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around route-param signals, Angular Query
|
||||
// detail loading, selection state, and the large series dashboard template so the series page
|
||||
// control flow can be asserted without mounting the full browser and query runtime.
|
||||
describe.skip('SeriesPageComponent', () => {
|
||||
it('needs route and query seams to verify filtered series books, cover-book resolution, and description loading', () => {
|
||||
// TODO(seam): Cover the computed series view model once route params and injectQuery data can be driven through a deterministic harness.
|
||||
});
|
||||
|
||||
it('needs interaction seams to verify selection, menu actions, metadata flows, and overflow handling', () => {
|
||||
// TODO(seam): Cover selection state, action menus, and description expansion after overlay, loading-service, and DOM measurement concerns are isolated behind test adapters.
|
||||
});
|
||||
});
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {LoadingService} from '../../../../core/services/loading.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||
import {ShelfAssignerComponent} from './shelf-assigner.component';
|
||||
|
||||
interface CurrentUserLike {
|
||||
id: number;
|
||||
userSettings: {
|
||||
sidebarShelfSorting: {
|
||||
field: string;
|
||||
order: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
describe('ShelfAssignerComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createShelf(overrides: Partial<Shelf> = {}): Shelf {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
userId: 7,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 101,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
shelves: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createCurrentUser(
|
||||
sorting: {field: string; order: string} = {field: 'name', order: 'asc'},
|
||||
id: number = 7,
|
||||
): CurrentUserLike {
|
||||
return {
|
||||
id,
|
||||
userSettings: {
|
||||
sidebarShelfSorting: sorting,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(options: {
|
||||
book?: Book;
|
||||
bookIds?: Set<number>;
|
||||
isMultiBooks?: boolean;
|
||||
shelves?: Shelf[];
|
||||
currentUser?: CurrentUserLike | null;
|
||||
updateResult?: Observable<Book[]>;
|
||||
} = {}) {
|
||||
const shelves = signal(options.shelves ?? []);
|
||||
const currentUser = signal<CurrentUserLike | null>(options.currentUser ?? createCurrentUser());
|
||||
const updateBookShelves = vi.fn(() => options.updateResult ?? of([] as Book[]));
|
||||
const dialogRef = {close: vi.fn()};
|
||||
const messageService = {add: vi.fn()};
|
||||
const bookDialogHelper = {openShelfCreatorDialog: vi.fn()};
|
||||
const loader = document.createElement('div');
|
||||
const loadingService = {
|
||||
show: vi.fn(() => loader),
|
||||
hide: vi.fn(),
|
||||
};
|
||||
const translate = vi.fn(<T = string>(key: string, params?: Record<string, unknown>) => {
|
||||
if (typeof params?.['count'] === 'number') {
|
||||
return `translated:${key}:${String(params['count'])}` as T;
|
||||
}
|
||||
|
||||
return `translated:${key}` as T;
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: ShelfService,
|
||||
useValue: {shelves},
|
||||
},
|
||||
{
|
||||
provide: DynamicDialogConfig,
|
||||
useValue: {
|
||||
data: {
|
||||
book: options.book ?? createBook(),
|
||||
bookIds: options.bookIds ?? new Set<number>(),
|
||||
isMultiBooks: options.isMultiBooks ?? false,
|
||||
},
|
||||
},
|
||||
},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: BookService, useValue: {updateBookShelves}},
|
||||
{provide: BookDialogHelperService, useValue: bookDialogHelper},
|
||||
{provide: LoadingService, useValue: loadingService},
|
||||
{provide: UserService, useValue: {currentUser}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new ShelfAssignerComponent());
|
||||
TestBed.flushEffects();
|
||||
|
||||
return {
|
||||
component,
|
||||
shelves,
|
||||
currentUser,
|
||||
updateBookShelves,
|
||||
dialogRef,
|
||||
messageService,
|
||||
bookDialogHelper,
|
||||
loadingService,
|
||||
loader,
|
||||
translate,
|
||||
};
|
||||
}
|
||||
|
||||
it('initializes selected shelves from the injected book once shelf data is available', () => {
|
||||
const unread = createShelf({id: 1, name: 'Unread'});
|
||||
const favorites = createShelf({id: 2, name: 'Favorites'});
|
||||
const foreignShelf = createShelf({id: 3, name: 'Other User Shelf', userId: 8});
|
||||
const book = createBook({
|
||||
shelves: [
|
||||
createShelf({id: 2, name: 'Favorites'}),
|
||||
],
|
||||
});
|
||||
|
||||
const {component} = createHarness({
|
||||
book,
|
||||
shelves: [unread, favorites, foreignShelf],
|
||||
});
|
||||
|
||||
expect(component.selectedShelves).toEqual([favorites]);
|
||||
expect(component.isShelfSelected(favorites)).toBe(true);
|
||||
expect(component.isShelfSelected(unread)).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to name ascending sorting when sidebar preferences are invalid', () => {
|
||||
const {component} = createHarness({
|
||||
currentUser: createCurrentUser({field: 'createdAt', order: 'SIDEWAYS'}),
|
||||
shelves: [
|
||||
createShelf({id: 2, name: 'Zulu'}),
|
||||
createShelf({id: 1, name: 'Alpha'}),
|
||||
createShelf({id: 3, name: 'Hidden', userId: 42}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(component.shelves().map(shelf => shelf.name)).toEqual(['Alpha', 'Zulu']);
|
||||
});
|
||||
|
||||
it('sorts shelves by id descending when the stored sidebar preferences are valid', () => {
|
||||
const {component} = createHarness({
|
||||
currentUser: createCurrentUser({field: 'id', order: 'desc'}),
|
||||
shelves: [
|
||||
createShelf({id: 1, name: 'One'}),
|
||||
createShelf({id: 3, name: 'Three'}),
|
||||
createShelf({id: 2, name: 'Two'}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(component.shelves().map(shelf => shelf.id)).toEqual([3, 2, 1]);
|
||||
});
|
||||
|
||||
it('filters shelves by a trimmed case-insensitive query', () => {
|
||||
const {component} = createHarness();
|
||||
const shelves = [
|
||||
createShelf({id: 1, name: 'Science Fiction'}),
|
||||
createShelf({id: 2, name: 'History'}),
|
||||
createShelf({id: 3, name: 'Sci-Fi Favorites'}),
|
||||
];
|
||||
|
||||
component.searchQuery = ' sci ';
|
||||
|
||||
expect(component.filterShelves(shelves).map(shelf => shelf.name)).toEqual([
|
||||
'Science Fiction',
|
||||
'Sci-Fi Favorites',
|
||||
]);
|
||||
});
|
||||
|
||||
it('maps custom svg and PrimeNG shelf icons to icon-display selections', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
expect(component.getShelfIcon(createShelf({
|
||||
iconType: 'CUSTOM_SVG',
|
||||
icon: 'custom-icons/moon.svg',
|
||||
}))).toEqual({
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
});
|
||||
expect(component.getShelfIcon(createShelf({
|
||||
iconType: 'PRIME_NG',
|
||||
icon: 'bookmark',
|
||||
}))).toEqual({
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-bookmark',
|
||||
});
|
||||
});
|
||||
|
||||
it('shapes assign and unassign payloads for a single-book update and closes with success', () => {
|
||||
const existing = createShelf({id: 1, name: 'Existing'});
|
||||
const added = createShelf({id: 2, name: 'Added'});
|
||||
const removed = createShelf({id: 3, name: 'Removed'});
|
||||
const {component, updateBookShelves, loadingService, loader, messageService, dialogRef, translate} = createHarness({
|
||||
book: createBook({
|
||||
id: 11,
|
||||
shelves: [existing, removed],
|
||||
}),
|
||||
});
|
||||
|
||||
component.selectedShelves = [existing, added];
|
||||
|
||||
component.updateBooksShelves();
|
||||
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfAssigner.loading.updatingShelves', {count: 1});
|
||||
expect(loadingService.show).toHaveBeenCalledWith('translated:book.shelfAssigner.loading.updatingShelves:1');
|
||||
expect(updateBookShelves).toHaveBeenCalledWith(
|
||||
new Set([11]),
|
||||
new Set([1, 2]),
|
||||
new Set([3]),
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith(loader);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'translated:common.success',
|
||||
detail: 'translated:book.shelfAssigner.toast.updateSuccessDetail',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({assigned: true});
|
||||
});
|
||||
|
||||
it('uses the injected multi-book ids, skips unassigns, and closes with failure on update errors', () => {
|
||||
const selected = createShelf({id: 5, name: 'Selected'});
|
||||
const targetBookIds = new Set([41, 42]);
|
||||
const {component, updateBookShelves, loadingService, loader, messageService, dialogRef, translate} = createHarness({
|
||||
book: createBook({
|
||||
id: 11,
|
||||
shelves: [createShelf({id: 9, name: 'Ignored Existing'})],
|
||||
}),
|
||||
bookIds: targetBookIds,
|
||||
isMultiBooks: true,
|
||||
updateResult: throwError(() => new Error('update failed')),
|
||||
});
|
||||
|
||||
component.selectedShelves = [selected];
|
||||
|
||||
component.updateBooksShelves();
|
||||
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfAssigner.loading.updatingShelves', {count: 2});
|
||||
expect(updateBookShelves).toHaveBeenCalledWith(
|
||||
targetBookIds,
|
||||
new Set([5]),
|
||||
new Set(),
|
||||
);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith(loader);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:common.error',
|
||||
detail: 'translated:book.shelfAssigner.toast.updateFailedDetail',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({assigned: false});
|
||||
});
|
||||
});
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {ShelfCreatorComponent} from './shelf-creator.component';
|
||||
|
||||
describe('ShelfCreatorComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createHarness(options: {
|
||||
createResult?: Observable<Shelf>;
|
||||
iconPickerResult?: IconSelection | null;
|
||||
currentUser?: {permissions: {admin: boolean}} | null;
|
||||
} = {}) {
|
||||
const createShelf = vi.fn(() => options.createResult ?? of({
|
||||
name: 'Created Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
}));
|
||||
const dialogRef = {close: vi.fn()};
|
||||
const messageService = {add: vi.fn()};
|
||||
const iconPickerService = {
|
||||
open: vi.fn(() => of(options.iconPickerResult ?? null)),
|
||||
};
|
||||
const getCurrentUser = vi.fn(() => options.currentUser ?? {permissions: {admin: false}});
|
||||
const translate = vi.fn(<T = string>(key: string, params?: Record<string, unknown>) => {
|
||||
if (params?.['name']) {
|
||||
return `translated:${key}:${String(params['name'])}` as T;
|
||||
}
|
||||
|
||||
return `translated:${key}` as T;
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: ShelfService, useValue: {createShelf}},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: IconPickerService, useValue: iconPickerService},
|
||||
{provide: UserService, useValue: {getCurrentUser}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new ShelfCreatorComponent());
|
||||
|
||||
return {
|
||||
component,
|
||||
createShelf,
|
||||
dialogRef,
|
||||
messageService,
|
||||
iconPickerService,
|
||||
translate,
|
||||
};
|
||||
}
|
||||
|
||||
it('picks an icon through the injected icon picker and ignores empty selections', () => {
|
||||
const pickedIcon: IconSelection = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-star',
|
||||
};
|
||||
const {component, iconPickerService} = createHarness({
|
||||
iconPickerResult: pickedIcon,
|
||||
});
|
||||
|
||||
component.openIconPicker();
|
||||
|
||||
expect(iconPickerService.open).toHaveBeenCalledOnce();
|
||||
expect(component.selectedIcon).toEqual(pickedIcon);
|
||||
|
||||
iconPickerService.open.mockReturnValueOnce(of(null));
|
||||
component.openIconPicker();
|
||||
|
||||
expect(component.selectedIcon).toEqual(pickedIcon);
|
||||
});
|
||||
|
||||
it('clears the selected icon directly', () => {
|
||||
const {component} = createHarness();
|
||||
component.selectedIcon = {
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
};
|
||||
|
||||
component.clearSelectedIcon();
|
||||
|
||||
expect(component.selectedIcon).toBeNull();
|
||||
});
|
||||
|
||||
it('closes the dialog without a payload when cancelled', () => {
|
||||
const {component, dialogRef} = createHarness();
|
||||
|
||||
component.cancel();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
expect(dialogRef.close).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it('creates a shelf with the selected icon, shows a success toast, and closes with true', () => {
|
||||
const {component, createShelf, messageService, dialogRef, translate} = createHarness({
|
||||
currentUser: {permissions: {admin: true}},
|
||||
});
|
||||
|
||||
component.shelfName = 'Weekend Reads';
|
||||
component.isPublic = true;
|
||||
component.selectedIcon = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-bookmark',
|
||||
};
|
||||
|
||||
component.createShelf();
|
||||
|
||||
expect(createShelf).toHaveBeenCalledWith({
|
||||
name: 'Weekend Reads',
|
||||
icon: 'pi pi-bookmark',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
});
|
||||
expect(translate).toHaveBeenCalledWith('common.success');
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfCreator.toast.createSuccessDetail', {
|
||||
name: 'Weekend Reads',
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'translated:common.success',
|
||||
detail: 'translated:book.shelfCreator.toast.createSuccessDetail:Weekend Reads',
|
||||
});
|
||||
expect(dialogRef.close).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('creates a shelf with null icon fields when no icon is selected', () => {
|
||||
const {component, createShelf} = createHarness();
|
||||
|
||||
component.shelfName = 'Plain Shelf';
|
||||
component.isPublic = false;
|
||||
component.selectedIcon = null;
|
||||
|
||||
component.createShelf();
|
||||
|
||||
expect(createShelf).toHaveBeenCalledWith({
|
||||
name: 'Plain Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when create fails', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const {component, createShelf, messageService, dialogRef, translate} = createHarness({
|
||||
createResult: throwError(() => new Error('create failed')),
|
||||
});
|
||||
|
||||
component.shelfName = 'Broken Shelf';
|
||||
component.selectedIcon = {
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
};
|
||||
component.isPublic = true;
|
||||
|
||||
component.createShelf();
|
||||
|
||||
expect(createShelf).toHaveBeenCalledWith({
|
||||
name: 'Broken Shelf',
|
||||
icon: 'custom-icons/moon.svg',
|
||||
iconType: 'CUSTOM_SVG',
|
||||
publicShelf: true,
|
||||
});
|
||||
expect(translate).toHaveBeenCalledWith('common.error');
|
||||
expect(translate).toHaveBeenCalledWith('book.shelfCreator.toast.createFailedDetail');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:common.error',
|
||||
detail: 'translated:book.shelfCreator.toast.createFailedDetail',
|
||||
});
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
expect(errorSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Observable, of, throwError} from 'rxjs';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {ShelfEditDialogComponent} from './shelf-edit-dialog.component';
|
||||
|
||||
describe('ShelfEditDialogComponent', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createShelf(overrides: Partial<Shelf> = {}): Shelf {
|
||||
return {
|
||||
id: 7,
|
||||
name: 'Favorites',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(options: {
|
||||
shelfId?: number;
|
||||
shelvesData?: Shelf[];
|
||||
updateResult?: Observable<Shelf>;
|
||||
iconPickerResult?: IconSelection | null;
|
||||
currentUser?: {permissions: {admin: boolean}} | null;
|
||||
} = {}) {
|
||||
const shelves = signal<Shelf[]>(options.shelvesData ?? []);
|
||||
const updateShelf = vi.fn(() => options.updateResult ?? of(createShelf()));
|
||||
const dialogRef = {close: vi.fn()};
|
||||
const messageService = {add: vi.fn()};
|
||||
const iconPickerService = {
|
||||
open: vi.fn(() => of(options.iconPickerResult ?? null)),
|
||||
};
|
||||
const getCurrentUser = vi.fn(() => options.currentUser ?? {permissions: {admin: false}});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: ShelfService, useValue: {shelves, updateShelf}},
|
||||
{provide: DynamicDialogConfig, useValue: {data: {shelfId: options.shelfId ?? 7}}},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: IconPickerService, useValue: iconPickerService},
|
||||
{provide: UserService, useValue: {getCurrentUser}},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new ShelfEditDialogComponent());
|
||||
component.ngOnInit();
|
||||
TestBed.flushEffects();
|
||||
|
||||
return {
|
||||
component,
|
||||
shelves,
|
||||
updateShelf,
|
||||
dialogRef,
|
||||
messageService,
|
||||
iconPickerService,
|
||||
};
|
||||
}
|
||||
|
||||
it('hydrates the dialog from a matching PrimeNG shelf', () => {
|
||||
const shelf = createShelf({
|
||||
id: 42,
|
||||
name: 'Queue',
|
||||
icon: 'bookmark',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
});
|
||||
|
||||
const {component} = createHarness({
|
||||
shelfId: 42,
|
||||
shelvesData: [shelf],
|
||||
});
|
||||
|
||||
expect(component.shelf).toEqual(shelf);
|
||||
expect(component.shelfName).toBe('Queue');
|
||||
expect(component.isPublic).toBe(true);
|
||||
expect(component.selectedIcon).toEqual({
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-bookmark',
|
||||
});
|
||||
});
|
||||
|
||||
it('hydrates custom SVG icons and only initializes once after the shelf becomes available', () => {
|
||||
const {component, shelves} = createHarness({
|
||||
shelfId: 11,
|
||||
shelvesData: [createShelf({id: 99, name: 'Other Shelf'})],
|
||||
});
|
||||
|
||||
expect(component.shelf).toBeUndefined();
|
||||
expect(component.shelfName).toBe('');
|
||||
expect(component.selectedIcon).toBeNull();
|
||||
|
||||
shelves.set([
|
||||
createShelf({
|
||||
id: 11,
|
||||
name: 'Readable',
|
||||
icon: 'custom-icons/moon.svg',
|
||||
iconType: 'CUSTOM_SVG',
|
||||
}),
|
||||
]);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.shelfName).toBe('Readable');
|
||||
expect(component.selectedIcon).toEqual({
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
});
|
||||
|
||||
shelves.set([
|
||||
createShelf({
|
||||
id: 11,
|
||||
name: 'Should Not Replace',
|
||||
icon: 'bookmark',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
}),
|
||||
]);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.shelfName).toBe('Readable');
|
||||
expect(component.isPublic).toBe(false);
|
||||
expect(component.selectedIcon).toEqual({
|
||||
type: 'CUSTOM_SVG',
|
||||
value: 'custom-icons/moon.svg',
|
||||
});
|
||||
});
|
||||
|
||||
it('picks and clears icons through the dialog-local icon selection methods', () => {
|
||||
const pickedIcon: IconSelection = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-star',
|
||||
};
|
||||
const {component, iconPickerService} = createHarness({
|
||||
shelvesData: [createShelf()],
|
||||
iconPickerResult: pickedIcon,
|
||||
});
|
||||
|
||||
component.openIconPicker();
|
||||
expect(iconPickerService.open).toHaveBeenCalledOnce();
|
||||
expect(component.selectedIcon).toEqual(pickedIcon);
|
||||
|
||||
component.clearSelectedIcon();
|
||||
expect(component.selectedIcon).toBeNull();
|
||||
});
|
||||
|
||||
it('saves the edited shelf, shows a success toast, and closes the dialog', () => {
|
||||
const {component, updateShelf, messageService, dialogRef} = createHarness({
|
||||
shelfId: 7,
|
||||
shelvesData: [createShelf({id: 7})],
|
||||
});
|
||||
|
||||
component.shelfName = 'Renamed Shelf';
|
||||
component.isPublic = true;
|
||||
component.selectedIcon = {
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-heart',
|
||||
};
|
||||
|
||||
component.save();
|
||||
|
||||
expect(updateShelf).toHaveBeenCalledWith({
|
||||
name: 'Renamed Shelf',
|
||||
icon: 'pi pi-heart',
|
||||
iconType: 'PRIME_NG',
|
||||
publicShelf: true,
|
||||
}, 7);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
}));
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('shows an error toast and keeps the dialog open when save fails', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const {component, updateShelf, messageService, dialogRef} = createHarness({
|
||||
shelfId: 7,
|
||||
shelvesData: [createShelf({id: 7})],
|
||||
updateResult: throwError(() => new Error('save failed')),
|
||||
});
|
||||
|
||||
component.shelfName = 'Broken Shelf';
|
||||
component.selectedIcon = null;
|
||||
component.isPublic = false;
|
||||
component.save();
|
||||
|
||||
expect(updateShelf).toHaveBeenCalledWith({
|
||||
name: 'Broken Shelf',
|
||||
icon: null,
|
||||
iconType: null,
|
||||
publicShelf: false,
|
||||
}, 7);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
}));
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
expect(errorSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('closes the dialog without saving when cancelled', () => {
|
||||
const {component, dialogRef} = createHarness({
|
||||
shelvesData: [createShelf()],
|
||||
});
|
||||
|
||||
component.closeDialog();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {ReadStatusHelper} from './read-status.helper';
|
||||
|
||||
describe('ReadStatusHelper', () => {
|
||||
const helper = new ReadStatusHelper();
|
||||
|
||||
it('maps statuses to icons and classes', () => {
|
||||
expect(helper.getReadStatusIcon(undefined)).toBe('pi pi-book');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.READ)).toBe('pi pi-check');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.READING)).toBe('pi pi-play');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.RE_READING)).toBe('pi pi-refresh');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.PARTIALLY_READ)).toBe('pi pi-clock');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.PAUSED)).toBe('pi pi-pause');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.ABANDONED)).toBe('pi pi-times');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.WONT_READ)).toBe('pi pi-ban');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.UNREAD)).toBe('pi pi-book');
|
||||
expect(helper.getReadStatusIcon(ReadStatus.UNSET)).toBe('pi pi-book');
|
||||
|
||||
expect(helper.getReadStatusClass(undefined)).toBe('status-unset');
|
||||
expect(helper.getReadStatusClass(ReadStatus.READ)).toBe('status-read');
|
||||
expect(helper.getReadStatusClass(ReadStatus.READING)).toBe('status-reading');
|
||||
expect(helper.getReadStatusClass(ReadStatus.RE_READING)).toBe('status-re-reading');
|
||||
expect(helper.getReadStatusClass(ReadStatus.PARTIALLY_READ)).toBe('status-partially-read');
|
||||
expect(helper.getReadStatusClass(ReadStatus.PAUSED)).toBe('status-paused');
|
||||
expect(helper.getReadStatusClass(ReadStatus.ABANDONED)).toBe('status-abandoned');
|
||||
expect(helper.getReadStatusClass(ReadStatus.WONT_READ)).toBe('status-wont-read');
|
||||
expect(helper.getReadStatusClass(ReadStatus.UNREAD)).toBe('status-unset');
|
||||
expect(helper.getReadStatusClass(ReadStatus.UNSET)).toBe('status-unset');
|
||||
});
|
||||
|
||||
it('maps statuses to tooltips', () => {
|
||||
expect(helper.getReadStatusTooltip(undefined)).toBe('Unset');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.READ)).toBe('Read');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.READING)).toBe('Currently Reading');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.RE_READING)).toBe('Re-reading');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.PARTIALLY_READ)).toBe('Partially Read');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.PAUSED)).toBe('Paused');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.ABANDONED)).toBe('Abandoned');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.WONT_READ)).toBe("Won't Read");
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.UNREAD)).toBe('Unread');
|
||||
expect(helper.getReadStatusTooltip(ReadStatus.UNSET)).toBe('Unset');
|
||||
});
|
||||
|
||||
it('always shows the status icon', () => {
|
||||
expect(helper.shouldShowStatusIcon(undefined)).toBe(true);
|
||||
expect(helper.shouldShowStatusIcon(ReadStatus.READ)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {
|
||||
AdditionalFileType,
|
||||
Book,
|
||||
BookMetadata,
|
||||
BookStatusUpdateResponse,
|
||||
BulkMetadataUpdateRequest,
|
||||
computeSeriesReadStatus,
|
||||
CreatePhysicalBookRequest,
|
||||
ReadStatus
|
||||
} from './book.model';
|
||||
|
||||
describe('book.model', () => {
|
||||
it('exposes stable additional file and read-status enums', () => {
|
||||
expect(AdditionalFileType).toEqual({
|
||||
ALTERNATIVE_FORMAT: 'ALTERNATIVE_FORMAT',
|
||||
SUPPLEMENTARY: 'SUPPLEMENTARY'
|
||||
});
|
||||
expect(ReadStatus.UNREAD).toBe('UNREAD');
|
||||
expect(ReadStatus.RE_READING).toBe('RE_READING');
|
||||
});
|
||||
|
||||
it('computes aggregate series status from book states', () => {
|
||||
expect(computeSeriesReadStatus([])).toBe(ReadStatus.UNREAD);
|
||||
expect(computeSeriesReadStatus([{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READ} as Book])).toBe(ReadStatus.READ);
|
||||
expect(computeSeriesReadStatus([
|
||||
{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READ} as Book,
|
||||
{id: 2, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.UNREAD} as Book
|
||||
])).toBe(ReadStatus.PARTIALLY_READ);
|
||||
expect(computeSeriesReadStatus([
|
||||
{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READING} as Book,
|
||||
{id: 2, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.UNREAD} as Book
|
||||
])).toBe(ReadStatus.READING);
|
||||
expect(computeSeriesReadStatus([
|
||||
{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.WONT_READ} as Book
|
||||
])).toBe(ReadStatus.WONT_READ);
|
||||
});
|
||||
|
||||
it('keeps core payload and metadata contracts typed', () => {
|
||||
const metadata: BookMetadata = {
|
||||
bookId: 4,
|
||||
title: 'A Wizard of Earthsea',
|
||||
authors: ['Ursula K. Le Guin'],
|
||||
pageCount: 205
|
||||
};
|
||||
const createRequest: CreatePhysicalBookRequest = {
|
||||
libraryId: 2,
|
||||
title: 'The Tombs of Atuan',
|
||||
authors: ['Ursula K. Le Guin']
|
||||
};
|
||||
const bulkUpdate: BulkMetadataUpdateRequest = {
|
||||
bookIds: [1, 2],
|
||||
genres: ['Fantasy'],
|
||||
mergeCategories: true
|
||||
};
|
||||
const statusUpdate: BookStatusUpdateResponse = {
|
||||
bookId: 1,
|
||||
readStatus: ReadStatus.READ,
|
||||
readStatusModifiedTime: '2026-03-26T10:00:00Z'
|
||||
};
|
||||
|
||||
expect(metadata.authors).toEqual(['Ursula K. Le Guin']);
|
||||
expect(createRequest.libraryId).toBe(2);
|
||||
expect(bulkUpdate.mergeCategories).toBe(true);
|
||||
expect(statusUpdate.readStatus).toBe(ReadStatus.READ);
|
||||
expectTypeOf(metadata.pageCount).toEqualTypeOf<number | null | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {Library, LibraryPath, MetadataSource, OrganizationMode} from './library.model';
|
||||
|
||||
describe('library.model', () => {
|
||||
it('supports a library with paths and optional metadata settings', () => {
|
||||
const library: Library = {
|
||||
id: 1,
|
||||
name: 'Main Library',
|
||||
watch: true,
|
||||
paths: [{id: 10, path: '/books'}],
|
||||
metadataSource: 'PREFER_EMBEDDED',
|
||||
organizationMode: 'AUTO_DETECT'
|
||||
};
|
||||
|
||||
expect(library.paths[0].path).toBe('/books');
|
||||
expect(library.metadataSource).toBe('PREFER_EMBEDDED');
|
||||
expectTypeOf(library.paths).toMatchTypeOf<LibraryPath[]>();
|
||||
});
|
||||
|
||||
it('keeps metadata source and organization mode unions constrained', () => {
|
||||
expectTypeOf<MetadataSource>().toEqualTypeOf<
|
||||
'EMBEDDED' | 'SIDECAR' | 'PREFER_SIDECAR' | 'PREFER_EMBEDDED' | 'NONE'
|
||||
>();
|
||||
expectTypeOf<OrganizationMode>().toEqualTypeOf<
|
||||
'BOOK_PER_FILE' | 'BOOK_PER_FOLDER' | 'AUTO_DETECT'
|
||||
>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {Shelf} from './shelf.model';
|
||||
import {SortDirection} from './sort.model';
|
||||
|
||||
describe('shelf.model', () => {
|
||||
it('supports optional presentation and ownership fields', () => {
|
||||
const shelf: Shelf = {
|
||||
id: 3,
|
||||
name: 'Favorites',
|
||||
icon: 'pi pi-heart',
|
||||
publicShelf: true,
|
||||
userId: 9,
|
||||
bookCount: 24,
|
||||
sort: {
|
||||
label: 'Title',
|
||||
field: 'title',
|
||||
direction: SortDirection.ASCENDING
|
||||
}
|
||||
};
|
||||
|
||||
expect(shelf.name).toBe('Favorites');
|
||||
expect(shelf.sort?.direction).toBe(SortDirection.ASCENDING);
|
||||
});
|
||||
|
||||
it('allows nullable icon values', () => {
|
||||
expectTypeOf<Shelf['icon']>().toEqualTypeOf<string | null | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {SortDirection, SortOption} from './sort.model';
|
||||
|
||||
describe('sort.model', () => {
|
||||
it('exposes the supported sort directions', () => {
|
||||
expect(SortDirection).toEqual({
|
||||
ASCENDING: 'ASCENDING',
|
||||
DESCENDING: 'DESCENDING'
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps sort options structurally typed', () => {
|
||||
const sortOption: SortOption = {
|
||||
label: 'Title',
|
||||
field: 'title',
|
||||
direction: SortDirection.ASCENDING
|
||||
};
|
||||
|
||||
expect(sortOption.field).toBe('title');
|
||||
expectTypeOf(sortOption.direction).toEqualTypeOf<SortDirection>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,360 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AdditionalFile, Book, BookMetadata, DetachBookFileResponse} from '../model/book.model';
|
||||
import {AdditionalFileType} from '../model/book.model';
|
||||
import {BOOKS_QUERY_KEY, bookDetailQueryKey} from './book-query-keys';
|
||||
import {BookFileService} from './book-file.service';
|
||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||
|
||||
type BuildBookOverrides = Omit<Partial<Book>, 'metadata'> & {
|
||||
metadata?: Partial<BookMetadata>;
|
||||
};
|
||||
|
||||
function buildAdditionalFile(id: number, overrides: Partial<AdditionalFile> = {}): AdditionalFile {
|
||||
const bookId = overrides.bookId ?? 1;
|
||||
|
||||
return {
|
||||
id,
|
||||
bookId,
|
||||
fileName: `file-${id}.epub`,
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildBook(id: number, overrides: BuildBookOverrides = {}): Book {
|
||||
const {metadata, ...bookOverrides} = overrides;
|
||||
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
...metadata,
|
||||
},
|
||||
...bookOverrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookFileService', () => {
|
||||
let service: BookFileService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let queryClient: QueryClient;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let fileDownloadService: {downloadFile: ReturnType<typeof vi.fn>};
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue();
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
fileDownloadService = {
|
||||
downloadFile: vi.fn(),
|
||||
};
|
||||
translate = vi.fn((key: string, params?: Record<string, unknown>) => (
|
||||
params ? `${key}:${JSON.stringify(params)}` : key
|
||||
));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookFileService,
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: FileDownloadService, useValue: fileDownloadService},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookFileService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('requests blob content with the optional bookType query param', async () => {
|
||||
const responseBlob = new Blob(['book-content']);
|
||||
const requestPromise = firstValueFrom(service.getFileContent(7, 'EPUB'));
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.urlWithParams.endsWith('/api/v1/books/7/content?bookType=EPUB'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
expect(request.request.urlWithParams).toBe('http://localhost:6060/api/v1/books/7/content?bookType=EPUB');
|
||||
expect(request.request.responseType).toBe('blob');
|
||||
|
||||
request.flush(responseBlob);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual(responseBlob);
|
||||
});
|
||||
|
||||
it('delegates direct, aggregate, and additional file downloads with derived filenames', () => {
|
||||
const book = buildBook(5, {
|
||||
primaryFile: buildAdditionalFile(51, {bookId: 5, fileName: 'main.epub'}),
|
||||
metadata: {title: 'Title: Volume 1'},
|
||||
alternativeFormats: [
|
||||
buildAdditionalFile(52, {bookId: 5, fileName: 'alt.epub'}),
|
||||
],
|
||||
supplementaryFiles: [
|
||||
buildAdditionalFile(53, {
|
||||
bookId: 5,
|
||||
fileName: 'notes.pdf',
|
||||
additionalFileType: AdditionalFileType.SUPPLEMENTARY,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
service.downloadFile(book);
|
||||
service.downloadAllFiles(book);
|
||||
service.downloadAdditionalFile(book, 53);
|
||||
|
||||
expect(fileDownloadService.downloadFile).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'http://localhost:6060/api/v1/books/5/download',
|
||||
'main.epub',
|
||||
);
|
||||
expect(fileDownloadService.downloadFile).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'http://localhost:6060/api/v1/books/5/download-all',
|
||||
'Title__Volume_1.zip',
|
||||
);
|
||||
expect(fileDownloadService.downloadFile).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
'http://localhost:6060/api/v1/books/5/files/53/download',
|
||||
'notes.pdf',
|
||||
);
|
||||
});
|
||||
|
||||
it('deletes an additional file, patches the cached lists, and shows a success toast', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [
|
||||
buildBook(7, {
|
||||
alternativeFormats: [buildAdditionalFile(70, {bookId: 7, fileName: 'alt.epub'})],
|
||||
supplementaryFiles: [
|
||||
buildAdditionalFile(71, {
|
||||
bookId: 7,
|
||||
fileName: 'notes.pdf',
|
||||
additionalFileType: AdditionalFileType.SUPPLEMENTARY,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
|
||||
service.deleteAdditionalFile(7, 71).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/7/files/71'));
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
buildBook(7, {
|
||||
alternativeFormats: [buildAdditionalFile(70, {bookId: 7, fileName: 'alt.epub'})],
|
||||
supplementaryFiles: [],
|
||||
}),
|
||||
]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.bookService.toast.fileDeletedSummary',
|
||||
detail: 'book.bookService.toast.additionalFileDeletedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('promotes the next alternative format when deleting the primary book file', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [
|
||||
buildBook(9, {
|
||||
primaryFile: buildAdditionalFile(90, {bookId: 9, fileName: 'main.epub'}),
|
||||
alternativeFormats: [
|
||||
buildAdditionalFile(91, {bookId: 9, fileName: 'alt-one.pdf', bookType: 'PDF'}),
|
||||
buildAdditionalFile(92, {bookId: 9, fileName: 'alt-two.fb2', bookType: 'FB2'}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
|
||||
service.deleteBookFile(9, 90, true).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/9/files/90'));
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
buildBook(9, {
|
||||
primaryFile: buildAdditionalFile(91, {bookId: 9, fileName: 'alt-one.pdf', bookType: 'PDF'}),
|
||||
alternativeFormats: [
|
||||
buildAdditionalFile(92, {bookId: 9, fileName: 'alt-two.fb2', bookType: 'FB2'}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.bookService.toast.fileDeletedSummary',
|
||||
detail: 'book.bookService.toast.bookFileDeletedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('surfaces delete failures through an error toast and preserves cached files', () => {
|
||||
const cachedBook = buildBook(11, {
|
||||
supplementaryFiles: [
|
||||
buildAdditionalFile(111, {
|
||||
bookId: 11,
|
||||
fileName: 'appendix.pdf',
|
||||
additionalFileType: AdditionalFileType.SUPPLEMENTARY,
|
||||
}),
|
||||
],
|
||||
});
|
||||
let thrown: unknown;
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [cachedBook]);
|
||||
|
||||
service.deleteAdditionalFile(11, 111).subscribe({
|
||||
error: error => {
|
||||
thrown = error;
|
||||
},
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/11/files/111'));
|
||||
request.flush({message: 'cannot delete'}, {status: 500, statusText: 'Server Error'});
|
||||
|
||||
expect(thrown).toBeTruthy();
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([cachedBook]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'book.bookService.toast.fileDeleteFailedSummary',
|
||||
detail: 'cannot delete',
|
||||
});
|
||||
});
|
||||
|
||||
it('uploads alternative-format files with inferred bookType and patches cached formats', () => {
|
||||
const upload = new File(['epub'], 'edition.epub', {type: 'application/epub+zip'});
|
||||
const uploadedFile = buildAdditionalFile(121, {
|
||||
bookId: 12,
|
||||
fileName: 'edition.epub',
|
||||
bookType: 'EPUB',
|
||||
additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT,
|
||||
});
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [buildBook(12)]);
|
||||
|
||||
service.uploadAdditionalFile(12, upload, AdditionalFileType.ALTERNATIVE_FORMAT).subscribe(result => {
|
||||
expect(result).toEqual(uploadedFile);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/12/files'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
|
||||
const formData = request.request.body as FormData;
|
||||
expect(formData.get('file')).toBe(upload);
|
||||
expect(formData.get('isBook')).toBe('true');
|
||||
expect(formData.get('bookType')).toBe('EPUB');
|
||||
|
||||
request.flush(uploadedFile);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
buildBook(12, {
|
||||
alternativeFormats: [uploadedFile],
|
||||
}),
|
||||
]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.bookService.toast.fileUploadedSummary',
|
||||
detail: 'book.bookService.toast.fileUploadedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('detaches a book file with copyMetadata and patches both returned books in cache', () => {
|
||||
const sourceBook = buildBook(20, {
|
||||
alternativeFormats: [buildAdditionalFile(201, {bookId: 20, fileName: 'source.epub'})],
|
||||
});
|
||||
const placeholderNewBook = buildBook(21, {
|
||||
metadata: {title: 'Placeholder'},
|
||||
});
|
||||
const response: DetachBookFileResponse = {
|
||||
sourceBook: buildBook(20, {alternativeFormats: []}),
|
||||
newBook: buildBook(21, {
|
||||
primaryFile: buildAdditionalFile(201, {bookId: 21, fileName: 'source.epub'}),
|
||||
metadata: {title: 'Detached Copy'},
|
||||
}),
|
||||
};
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [sourceBook, placeholderNewBook]);
|
||||
|
||||
service.detachBookFile(20, 201, true).subscribe(result => {
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/20/files/201/detach'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({copyMetadata: true});
|
||||
request.flush(response);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([response.sourceBook, response.newBook]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'metadata.viewer.toast.detachFileSuccessSummary',
|
||||
detail: 'metadata.viewer.toast.detachFileSuccessDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('attaches source book files, updates the target cache entry, and evicts removed books', () => {
|
||||
const targetBook = buildBook(30, {
|
||||
primaryFile: buildAdditionalFile(301, {bookId: 30, fileName: 'target.epub'}),
|
||||
});
|
||||
const sourceBook = buildBook(31, {
|
||||
primaryFile: buildAdditionalFile(311, {bookId: 31, fileName: 'source-one.epub'}),
|
||||
});
|
||||
const secondSourceBook = buildBook(32, {
|
||||
primaryFile: buildAdditionalFile(321, {bookId: 32, fileName: 'source-two.epub'}),
|
||||
});
|
||||
const updatedTargetBook = buildBook(30, {
|
||||
primaryFile: buildAdditionalFile(301, {bookId: 30, fileName: 'target.epub'}),
|
||||
alternativeFormats: [
|
||||
buildAdditionalFile(311, {bookId: 30, fileName: 'source-one.epub'}),
|
||||
buildAdditionalFile(321, {bookId: 30, fileName: 'source-two.epub'}),
|
||||
],
|
||||
});
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [targetBook, sourceBook, secondSourceBook]);
|
||||
queryClient.setQueryData(bookDetailQueryKey(31, false), sourceBook);
|
||||
queryClient.setQueryData(bookDetailQueryKey(32, false), secondSourceBook);
|
||||
|
||||
service.attachBookFiles(30, [31, 32], false).subscribe(result => {
|
||||
expect(result).toEqual({
|
||||
updatedBook: updatedTargetBook,
|
||||
deletedSourceBookIds: [31, 32],
|
||||
});
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/30/attach-file'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({
|
||||
sourceBookIds: [31, 32],
|
||||
moveFiles: false,
|
||||
});
|
||||
request.flush({
|
||||
updatedBook: updatedTargetBook,
|
||||
deletedSourceBookIds: [31, 32],
|
||||
});
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([updatedTargetBook]);
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(31, false))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(32, false))).toBeUndefined();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'book.bookService.toast.filesAttachedSummary',
|
||||
detail: 'book.bookService.toast.filesAttachedDetail:{"count":2}',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around confirmation-dialog callbacks,
|
||||
// loader orchestration, and message-service side effects so menu-action branching can be asserted
|
||||
// without reproducing the full imperative overlay runtime.
|
||||
describe.skip('BookMenuService', () => {
|
||||
it('needs dialog seams to verify delete, merge, send, rescan, and metadata-refresh action branching', () => {
|
||||
// TODO(seam): Cover menu item creation and destructive-action callbacks once confirm dialog payloads can be asserted directly.
|
||||
});
|
||||
|
||||
it('needs loader and toast seams to verify success, failure, and bulk-operation messaging paths', () => {
|
||||
// TODO(seam): Cover async action handlers after loader wrappers and message dispatch are extracted behind deterministic collaborators.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
import {Book, BookMetadata, MetadataUpdateWrapper} from '../model/book.model';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {BookMetadataManageService} from './book-metadata-manage.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
function makeBook(id: number, metadata: Partial<BookMetadata> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
titleLocked: false,
|
||||
authorsLocked: false,
|
||||
...metadata,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookMetadataManageService', () => {
|
||||
let service: BookMetadataManageService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let queryClient: QueryClient;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue();
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookMetadataManageService,
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: {translate: (key: string) => key}},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookMetadataManageService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('updates metadata with merge params and patches the cached metadata', () => {
|
||||
const original = makeBook(7, {title: 'Old Title'});
|
||||
const wrapper: MetadataUpdateWrapper = {
|
||||
metadata: {bookId: 7, title: 'Updated Title'},
|
||||
clearFlags: {},
|
||||
};
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [original]);
|
||||
|
||||
service.updateBookMetadata(7, wrapper, true, 'REPLACE_WHEN_PROVIDED').subscribe(metadata => {
|
||||
expect(metadata.title).toBe('Updated Title');
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/7/metadata'));
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.params.get('mergeCategories')).toBe('true');
|
||||
expect(request.request.params.get('replaceMode')).toBe('REPLACE_WHEN_PROVIDED');
|
||||
expect(request.request.body).toEqual(wrapper);
|
||||
request.flush({bookId: 7, title: 'Updated Title'});
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)?.[0].metadata?.title).toBe('Updated Title');
|
||||
});
|
||||
|
||||
it('toggles cached metadata lock fields for successful bulk lock updates', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [
|
||||
makeBook(1, {titleLocked: false, authorsLocked: false}),
|
||||
]);
|
||||
|
||||
service.toggleFieldLocks([1], {title: 'LOCK', authorsLocked: 'LOCK'}).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/metadata/toggle-field-locks'));
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual({
|
||||
bookIds: [1],
|
||||
fieldActions: {title: 'LOCK', authorsLocked: 'LOCK'},
|
||||
});
|
||||
request.flush(null);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)?.[0].metadata).toMatchObject({
|
||||
titleLocked: true,
|
||||
authorsLocked: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when toggleFieldLocks fails', () => {
|
||||
let thrown: unknown;
|
||||
|
||||
service.toggleFieldLocks(new Set([2]), {title: 'UNLOCK'}).subscribe({
|
||||
error: error => {
|
||||
thrown = error;
|
||||
},
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/metadata/toggle-field-locks'));
|
||||
request.flush({message: 'nope'}, {status: 500, statusText: 'Server Error'});
|
||||
|
||||
expect(thrown).toBeTruthy();
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 'book.bookService.toast.fieldLockFailedSummary',
|
||||
}));
|
||||
});
|
||||
|
||||
it('reports whether a book has both audiobook and ebook files', () => {
|
||||
const dualFormatBook = makeBook(3, {
|
||||
audiobookCoverUpdatedOn: '2026-03-01',
|
||||
});
|
||||
dualFormatBook.primaryFile = {id: 10, bookId: 3, bookType: 'EPUB'};
|
||||
dualFormatBook.alternativeFormats = [{id: 11, bookId: 3, bookType: 'AUDIOBOOK'}];
|
||||
|
||||
const audiobookOnlyBook = makeBook(4);
|
||||
audiobookOnlyBook.primaryFile = {id: 12, bookId: 4, bookType: 'AUDIOBOOK'};
|
||||
|
||||
expect(service.supportsDualCovers(dualFormatBook)).toBe(true);
|
||||
expect(service.supportsDualCovers(audiobookOnlyBook)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns stable upload URLs for ebook and audiobook cover endpoints', () => {
|
||||
expect(service.getUploadCoverUrl(9)).toBe('http://localhost:6060/api/v1/books/9/metadata/cover/upload');
|
||||
expect(service.getUploadAudiobookCoverUrl(9)).toBe('http://localhost:6060/api/v1/books/9/metadata/audiobook-cover/upload');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {BookMetadataService} from './book-metadata.service';
|
||||
import {SseClient} from 'ngx-sse-client';
|
||||
|
||||
describe('BookMetadataService', () => {
|
||||
let service: BookMetadataService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: {getInternalAccessToken: ReturnType<typeof vi.fn>};
|
||||
let sseClient: {stream: ReturnType<typeof vi.fn>};
|
||||
const fetchRequest = {
|
||||
bookId: 7,
|
||||
providers: ['google'],
|
||||
title: 'Dune',
|
||||
author: 'Frank Herbert',
|
||||
isbn: '9780441172719',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
authService = {
|
||||
getInternalAccessToken: vi.fn(() => 'token-123'),
|
||||
};
|
||||
sseClient = {
|
||||
stream: vi.fn(() => of({type: 'message', data: JSON.stringify({title: 'Dune'})})),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookMetadataService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: SseClient, useValue: sseClient},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookMetadataService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('throws when fetching metadata without an auth token', () => {
|
||||
authService.getInternalAccessToken.mockReturnValueOnce(null);
|
||||
|
||||
expect(() => service.fetchBookMetadata(7, fetchRequest)).toThrowError(
|
||||
'No authentication token available'
|
||||
);
|
||||
});
|
||||
|
||||
it('streams metadata over SSE with auth headers and maps message payloads', () => {
|
||||
let result: unknown;
|
||||
|
||||
service.fetchBookMetadata(7, fetchRequest).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const [url, clientConfig, requestOptions, method] = sseClient.stream.mock.calls[0] ?? [];
|
||||
expect(url).toMatch(/\/api\/v1\/books\/7\/metadata\/prospective$/);
|
||||
expect(clientConfig).toEqual({
|
||||
keepAlive: false,
|
||||
reconnectionDelay: 1000,
|
||||
responseType: 'event'
|
||||
});
|
||||
expect(requestOptions.body).toEqual(fetchRequest);
|
||||
expect(requestOptions.withCredentials).toBe(true);
|
||||
expect(requestOptions.headers.get('Authorization')).toBe('Bearer token-123');
|
||||
expect(requestOptions.headers.get('Content-Type')).toBe('application/json');
|
||||
expect(method).toBe('POST');
|
||||
expect(result).toEqual({title: 'Dune'});
|
||||
});
|
||||
|
||||
it('turns SSE error events into thrown errors', () => {
|
||||
sseClient.stream.mockReturnValueOnce(of({type: 'error', message: 'bad stream'}));
|
||||
|
||||
let error: unknown;
|
||||
service.fetchBookMetadata(7, fetchRequest).subscribe({
|
||||
error: err => {
|
||||
error = err;
|
||||
}
|
||||
});
|
||||
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
expect((error as Error).message).toBe('bad stream');
|
||||
});
|
||||
|
||||
it('requests provider detail and ISBN lookup through HTTP endpoints', () => {
|
||||
service.fetchMetadataDetail('google', 'abc123').subscribe();
|
||||
service.lookupByIsbn('9780441172719').subscribe();
|
||||
|
||||
const detailRequest = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/books/metadata/detail/google/abc123')
|
||||
);
|
||||
expect(detailRequest.request.method).toBe('GET');
|
||||
detailRequest.flush({});
|
||||
|
||||
const lookupRequest = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/books/metadata/isbn-lookup')
|
||||
);
|
||||
expect(lookupRequest.request.method).toBe('POST');
|
||||
expect(lookupRequest.request.body).toEqual({isbn: '9780441172719'});
|
||||
lookupRequest.flush({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookNavigationService} from './book-navigation.service';
|
||||
|
||||
describe('BookNavigationService', () => {
|
||||
it('tracks navigation context and derived positions', () => {
|
||||
const service = new BookNavigationService();
|
||||
|
||||
expect(service.navigationState()).toBeNull();
|
||||
expect(service.canNavigatePrevious()).toBe(false);
|
||||
expect(service.canNavigateNext()).toBe(false);
|
||||
expect(service.previousBookId()).toBeNull();
|
||||
expect(service.nextBookId()).toBeNull();
|
||||
expect(service.currentPosition()).toBeNull();
|
||||
|
||||
service.setAvailableBookIds([1, 2, 3]);
|
||||
expect(service.availableBookIds()).toEqual([1, 2, 3]);
|
||||
|
||||
service.setNavigationContext([1, 2, 3], 2);
|
||||
|
||||
expect(service.navigationState()).toEqual({bookIds: [1, 2, 3], currentIndex: 1});
|
||||
expect(service.canNavigatePrevious()).toBe(true);
|
||||
expect(service.canNavigateNext()).toBe(true);
|
||||
expect(service.previousBookId()).toBe(1);
|
||||
expect(service.nextBookId()).toBe(3);
|
||||
expect(service.currentPosition()).toEqual({current: 2, total: 3});
|
||||
|
||||
service.updateCurrentBook(3);
|
||||
|
||||
expect(service.navigationState()).toEqual({bookIds: [1, 2, 3], currentIndex: 2});
|
||||
expect(service.canNavigatePrevious()).toBe(true);
|
||||
expect(service.canNavigateNext()).toBe(false);
|
||||
expect(service.previousBookId()).toBe(2);
|
||||
expect(service.nextBookId()).toBeNull();
|
||||
expect(service.currentPosition()).toEqual({current: 3, total: 3});
|
||||
});
|
||||
|
||||
it('clears invalid navigation context and ignores unknown book ids', () => {
|
||||
const service = new BookNavigationService();
|
||||
|
||||
service.setNavigationContext([1, 2, 3], 99);
|
||||
expect(service.navigationState()).toBeNull();
|
||||
|
||||
service.updateCurrentBook(2);
|
||||
expect(service.navigationState()).toBeNull();
|
||||
|
||||
service.setNavigationContext([1, 2, 3], 1);
|
||||
service.updateCurrentBook(99);
|
||||
|
||||
expect(service.navigationState()).toEqual({bookIds: [1, 2, 3], currentIndex: 0});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
|
||||
describe('BookPatchService', () => {
|
||||
let service: BookPatchService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let queryClient: QueryClient;
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
vi.spyOn(queryClient, 'setQueryData');
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookPatchService,
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookPatchService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('posts PDF progress with file progress when a book file id is provided', () => {
|
||||
service.savePdfProgress(11, 23, 74, 88).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({
|
||||
bookId: 11,
|
||||
pdfProgress: {
|
||||
page: 23,
|
||||
percentage: 74,
|
||||
},
|
||||
fileProgress: {
|
||||
bookFileId: 88,
|
||||
positionData: '23',
|
||||
progressPercent: 74,
|
||||
},
|
||||
});
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('deduplicates identical EPUB progress updates before posting', () => {
|
||||
service.saveEpubProgress(7, 'epubcfi(/6/2)', 'chapter-1.xhtml', 15, 31);
|
||||
service.saveEpubProgress(7, 'epubcfi(/6/2)', 'chapter-1.xhtml', 15, 31);
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress'));
|
||||
expect(request.request.body).toEqual({
|
||||
bookId: 7,
|
||||
epubProgress: {
|
||||
cfi: 'epubcfi(/6/2)',
|
||||
href: 'chapter-1.xhtml',
|
||||
percentage: 15,
|
||||
},
|
||||
fileProgress: {
|
||||
bookFileId: 31,
|
||||
positionData: 'epubcfi(/6/2)',
|
||||
positionHref: 'chapter-1.xhtml',
|
||||
progressPercent: 15,
|
||||
},
|
||||
});
|
||||
request.flush(null);
|
||||
|
||||
httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books/progress'));
|
||||
});
|
||||
|
||||
it('patches cached progress fields when resetting kobo progress', () => {
|
||||
service.resetProgress([1, 2], ResetProgressTypes.KOBO).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/reset-progress'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.params.get('type')).toBe(ResetProgressTypes.KOBO);
|
||||
expect(request.request.body).toEqual([1, 2]);
|
||||
request.flush([
|
||||
{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: '2026-03-01T00:00:00Z', dateFinished: null},
|
||||
{bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: '2026-03-02T00:00:00Z', dateFinished: '2026-03-03'},
|
||||
]);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('updates cached date finished after the backend accepts the change', () => {
|
||||
service.updateDateFinished(5, '2026-03-10').subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({
|
||||
bookId: 5,
|
||||
dateFinished: '2026-03-10',
|
||||
});
|
||||
request.flush(null);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books', 'detail', 5]});
|
||||
});
|
||||
|
||||
it('updates the read status for multiple books and patches cached fields', () => {
|
||||
service.updateBookReadStatus([1, 2], ReadStatus.READ).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/status'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({
|
||||
bookIds: [1, 2],
|
||||
status: ReadStatus.READ,
|
||||
});
|
||||
request.flush([
|
||||
{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: '2026-03-04T00:00:00Z', dateFinished: '2026-03-04'},
|
||||
{bookId: 2, readStatus: ReadStatus.READ, readStatusModifiedTime: '2026-03-05T00:00:00Z', dateFinished: '2026-03-05'},
|
||||
]);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('updates the cached last read timestamp without calling the backend', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-03-26T12:00:00Z'));
|
||||
|
||||
service.updateLastReadTime(3);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
httpTestingController.expectNone(req => req.url.includes('/api/v1/books'));
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,15 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {Book} from '../model/book.model';
|
||||
import {Book, BookMetadata} from '../model/book.model';
|
||||
import {
|
||||
addBookToCache,
|
||||
invalidateBookDetailQueries,
|
||||
invalidateBookQueries,
|
||||
invalidateBooksQuery,
|
||||
patchBookFieldsInCache,
|
||||
patchBookInCacheWith,
|
||||
patchBookMetadataInCache,
|
||||
patchBooksInCache,
|
||||
removeBookQueries,
|
||||
removeBooksFromCache
|
||||
@@ -55,6 +61,20 @@ describe('book-query-cache', () => {
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
|
||||
});
|
||||
|
||||
it('invalidates the full books query and book detail queries', () => {
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
invalidateBooksQuery(queryClient);
|
||||
invalidateBookDetailQueries(queryClient, [1, 1, 2]);
|
||||
invalidateBookQueries(queryClient, [3, 3]);
|
||||
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)});
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)});
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it('patches list entries and invalidates matching detail queries', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
@@ -72,6 +92,72 @@ describe('book-query-cache', () => {
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('patches metadata, selected fields, and updater callbacks in the list cache', () => {
|
||||
const firstBook = makeBook(1, {
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'Original Title',
|
||||
authors: ['Old Author']
|
||||
}
|
||||
});
|
||||
const secondBook = makeBook(2, {
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Second'
|
||||
},
|
||||
libraryName: 'Library A'
|
||||
});
|
||||
const thirdBook = makeBook(3, {
|
||||
metadata: {
|
||||
bookId: 3,
|
||||
title: 'Third'
|
||||
}
|
||||
});
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook, thirdBook]);
|
||||
|
||||
const updatedMetadata: BookMetadata = {
|
||||
bookId: 1,
|
||||
title: 'Updated Title'
|
||||
};
|
||||
|
||||
patchBookMetadataInCache(queryClient, 1, updatedMetadata);
|
||||
patchBookFieldsInCache(queryClient, [
|
||||
{bookId: 2, fields: {libraryName: 'Updated Library'}},
|
||||
{bookId: 3, fields: {personalRating: 4}}
|
||||
]);
|
||||
patchBookInCacheWith(queryClient, 1, book => ({
|
||||
...book,
|
||||
metadata: {
|
||||
...(book.metadata ?? {bookId: book.id}),
|
||||
authors: ['New Author']
|
||||
}
|
||||
}));
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
{
|
||||
...firstBook,
|
||||
metadata: {
|
||||
...firstBook.metadata,
|
||||
title: 'Updated Title',
|
||||
authors: ['New Author']
|
||||
}
|
||||
},
|
||||
{
|
||||
...secondBook,
|
||||
libraryName: 'Updated Library'
|
||||
},
|
||||
{
|
||||
...thirdBook,
|
||||
personalRating: 4
|
||||
}
|
||||
]);
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)});
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)});
|
||||
});
|
||||
|
||||
it('removes detail and recommendation queries for deleted books', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
@@ -103,4 +189,14 @@ describe('book-query-cache', () => {
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores an empty remove request', () => {
|
||||
const setQueryDataSpy = vi.spyOn(queryClient, 'setQueryData');
|
||||
const removeQueriesSpy = vi.spyOn(queryClient, 'removeQueries');
|
||||
|
||||
removeBooksFromCache(queryClient, []);
|
||||
|
||||
expect(setQueryDataSpy).not.toHaveBeenCalled();
|
||||
expect(removeQueriesSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {
|
||||
BOOKS_QUERY_KEY,
|
||||
bookDetailQueryKey,
|
||||
bookDetailQueryPrefix,
|
||||
bookRecommendationsQueryKey,
|
||||
bookRecommendationsQueryPrefix,
|
||||
} from './book-query-keys';
|
||||
import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys';
|
||||
|
||||
describe('book query keys', () => {
|
||||
it('builds stable keys for book queries and recommendations', () => {
|
||||
expect(BOOKS_QUERY_KEY).toEqual(['books']);
|
||||
expect(bookDetailQueryKey(12, true)).toEqual(['books', 'detail', 12, true]);
|
||||
expect(bookDetailQueryPrefix(12)).toEqual(['books', 'detail', 12]);
|
||||
expect(bookRecommendationsQueryKey(12, 25)).toEqual(['books', 'recommendations', 12, 25]);
|
||||
expect(bookRecommendationsQueryPrefix(12)).toEqual(['books', 'recommendations', 12]);
|
||||
});
|
||||
|
||||
it('builds stable keys for library queries', () => {
|
||||
expect(LIBRARIES_QUERY_KEY).toEqual(['libraries']);
|
||||
expect(libraryFormatCountsQueryKey(7)).toEqual(['libraries', 'format-counts', 7]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {Book} from '../model/book.model';
|
||||
import {BOOKS_QUERY_KEY, bookDetailQueryKey, bookRecommendationsQueryKey} from './book-query-keys';
|
||||
import {BookSocketService} from './book-socket.service';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
coverUpdatedOn: '2026-03-01T00:00:00Z',
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookSocketService', () => {
|
||||
let service: BookSocketService;
|
||||
let queryClient: QueryClient;
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookSocketService,
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookSocketService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('adds newly created books into the list cache', () => {
|
||||
const existing = makeBook(1);
|
||||
const created = makeBook(2);
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [existing]);
|
||||
|
||||
service.handleNewlyCreatedBook(created);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([existing, created]);
|
||||
});
|
||||
|
||||
it('invalidates the books query and removes detail queries for removed ids', () => {
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
const kept = makeBook(2);
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [makeBook(1), kept]);
|
||||
queryClient.setQueryData(bookDetailQueryKey(1, false), makeBook(1));
|
||||
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [kept]);
|
||||
|
||||
service.handleRemovedBookIds([1]);
|
||||
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
|
||||
});
|
||||
|
||||
it('patches updated books directly into the list cache', () => {
|
||||
const original = makeBook(7, {libraryName: 'Original'});
|
||||
const updated = makeBook(7, {libraryName: 'Updated'});
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [original]);
|
||||
|
||||
service.handleBookUpdate(updated);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([updated]);
|
||||
});
|
||||
|
||||
it('patches multiple cover timestamps and invalidates their detail queries', () => {
|
||||
const first = makeBook(3);
|
||||
const second = makeBook(4, {
|
||||
metadata: {
|
||||
bookId: 4,
|
||||
title: 'Book 4',
|
||||
},
|
||||
});
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [first, second]);
|
||||
|
||||
service.handleMultipleBookCoverPatches([{id: 3, coverUpdatedOn: '2026-03-26T12:34:00Z'}]);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
{
|
||||
...first,
|
||||
metadata: {
|
||||
...first.metadata,
|
||||
coverUpdatedOn: '2026-03-26T12:34:00Z',
|
||||
},
|
||||
},
|
||||
second,
|
||||
]);
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({queryKey: ['books', 'detail', 3]});
|
||||
});
|
||||
|
||||
it('ignores empty cover patch lists', () => {
|
||||
const setQueryDataSpy = vi.spyOn(queryClient, 'setQueryData');
|
||||
|
||||
service.handleMultipleBookCoverPatches([]);
|
||||
|
||||
expect(setQueryDataSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,263 @@
|
||||
import {HttpTestingController} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
|
||||
import type {Book, BookMetadata} from '../model/book.model';
|
||||
import type {Shelf} from '../model/shelf.model';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {BookSocketService} from './book-socket.service';
|
||||
import {BookService} from './book.service';
|
||||
|
||||
type BuildBookOverrides = Omit<Partial<Book>, 'metadata' | 'shelves'> & {
|
||||
metadata?: Partial<BookMetadata>;
|
||||
shelves?: Shelf[];
|
||||
};
|
||||
|
||||
function buildShelf(id: number, overrides: Partial<Shelf> = {}): Shelf {
|
||||
return {
|
||||
id,
|
||||
name: `Shelf ${id}`,
|
||||
userId: 7,
|
||||
bookCount: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildBook(id: number, overrides: BuildBookOverrides = {}): Book {
|
||||
const {metadata, ...bookOverrides} = overrides;
|
||||
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Main Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
...metadata,
|
||||
},
|
||||
...bookOverrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function flushBooksQuery(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
flushSignalAndQueryEffects();
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
}
|
||||
|
||||
describe('BookService', () => {
|
||||
let service: BookService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
|
||||
function setup(initialToken: string | null = 'token-123'): void {
|
||||
authService = createAuthServiceStub(initialToken);
|
||||
queryClientHarness = createQueryClientHarness();
|
||||
queryClientHarness.queryClient.setDefaultOptions({
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...queryClientHarness.providers,
|
||||
BookService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: Router, useValue: {navigate: vi.fn()}},
|
||||
{
|
||||
provide: BookSocketService,
|
||||
useValue: {
|
||||
handleNewlyCreatedBook: vi.fn(),
|
||||
handleRemovedBookIds: vi.fn(),
|
||||
handleBookUpdate: vi.fn(),
|
||||
handleMultipleBookUpdates: vi.fn(),
|
||||
handleBookMetadataUpdate: vi.fn(),
|
||||
handleMultipleBookCoverPatches: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookPatchService,
|
||||
useValue: {
|
||||
updateLastReadTime: vi.fn(),
|
||||
savePdfProgress: vi.fn(),
|
||||
saveCbxProgress: vi.fn(),
|
||||
updateDateFinished: vi.fn(),
|
||||
resetProgress: vi.fn(),
|
||||
updateBookReadStatus: vi.fn(),
|
||||
resetPersonalRating: vi.fn(),
|
||||
updatePersonalRating: vi.fn(),
|
||||
updateBookShelves: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate: vi.fn((key: string) => key),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
flushSignalAndQueryEffects();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController?.verify();
|
||||
queryClientHarness?.queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('eagerly fetches books and hydrates query-backed state, loading state, and unique metadata', async () => {
|
||||
setup();
|
||||
|
||||
const response = [
|
||||
buildBook(1, {
|
||||
metadata: {
|
||||
authors: ['Le Guin', 'Le Guin'],
|
||||
categories: ['Fantasy'],
|
||||
moods: ['Calm'],
|
||||
tags: ['Classic', 'Classic'],
|
||||
publisher: 'Ace',
|
||||
seriesName: 'Earthsea',
|
||||
},
|
||||
}),
|
||||
buildBook(2, {
|
||||
metadata: {
|
||||
authors: ['Pratchett'],
|
||||
categories: ['Fantasy', 'Humor'],
|
||||
moods: ['Calm', 'Funny'],
|
||||
tags: ['Classic', 'Satire'],
|
||||
publisher: 'Corgi',
|
||||
seriesName: 'Discworld',
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
expect(service.books()).toEqual([]);
|
||||
expect(service.isBooksLoading()).toBe(true);
|
||||
expect(service.booksError()).toBeNull();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(response);
|
||||
await flushBooksQuery();
|
||||
|
||||
expect(service.books()).toEqual(response);
|
||||
expect(service.findBookById(2)).toEqual(response[1]);
|
||||
expect(service.findBookById(999)).toBeUndefined();
|
||||
expect(service.getBooksByIds([2, 999, 1])).toEqual(response);
|
||||
expect(service.uniqueMetadata()).toEqual({
|
||||
authors: ['Le Guin', 'Pratchett'],
|
||||
categories: ['Fantasy', 'Humor'],
|
||||
moods: ['Calm', 'Funny'],
|
||||
tags: ['Classic', 'Satire'],
|
||||
publishers: ['Ace', 'Corgi'],
|
||||
series: ['Earthsea', 'Discworld'],
|
||||
});
|
||||
expect(service.isBooksLoading()).toBe(false);
|
||||
expect(service.booksError()).toBeNull();
|
||||
});
|
||||
|
||||
it('gates loading on the auth token and starts the eager fetch once a token is available', async () => {
|
||||
setup(null);
|
||||
|
||||
expect(service.books()).toEqual([]);
|
||||
expect(service.isBooksLoading()).toBe(false);
|
||||
expect(service.booksError()).toBeNull();
|
||||
httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books'));
|
||||
|
||||
authService.token.set('token-123');
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books'));
|
||||
expect(service.isBooksLoading()).toBe(true);
|
||||
request.flush([buildBook(7)]);
|
||||
await flushBooksQuery();
|
||||
|
||||
expect(service.books()).toEqual([buildBook(7)]);
|
||||
expect(service.isBooksLoading()).toBe(false);
|
||||
expect(service.booksError()).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces query errors through booksError and clears the loading flag', async () => {
|
||||
setup();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books'));
|
||||
request.flush({message: 'boom'}, {status: 500, statusText: 'Server Error'});
|
||||
await flushBooksQuery();
|
||||
|
||||
expect(service.books()).toEqual([]);
|
||||
expect(service.isBooksLoading()).toBe(false);
|
||||
expect(service.booksError()).toBe('Failed to load books');
|
||||
});
|
||||
|
||||
it('removes a shelf from the cached books query without disturbing other shelf assignments', async () => {
|
||||
setup();
|
||||
|
||||
const targetShelf = buildShelf(10, {name: 'Favorites'});
|
||||
const untouchedShelf = buildShelf(11, {name: 'Archive'});
|
||||
const initialBooks = [
|
||||
buildBook(1, {shelves: [targetShelf, untouchedShelf]}),
|
||||
buildBook(2, {shelves: [targetShelf]}),
|
||||
];
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')).flush(initialBooks);
|
||||
await flushBooksQuery();
|
||||
|
||||
service.removeBooksFromShelf(10);
|
||||
await flushBooksQuery();
|
||||
|
||||
expect(queryClientHarness.queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
buildBook(1, {shelves: [untouchedShelf]}),
|
||||
buildBook(2, {shelves: []}),
|
||||
]);
|
||||
expect(service.books()).toEqual([
|
||||
buildBook(1, {shelves: [untouchedShelf]}),
|
||||
buildBook(2, {shelves: []}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('removes the books query cache when the auth token is cleared', async () => {
|
||||
setup();
|
||||
|
||||
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries');
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')).flush([
|
||||
buildBook(1),
|
||||
buildBook(2),
|
||||
]);
|
||||
await flushBooksQuery();
|
||||
|
||||
expect(queryClientHarness.queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
buildBook(1),
|
||||
buildBook(2),
|
||||
]);
|
||||
|
||||
authService.token.set(null);
|
||||
await flushBooksQuery();
|
||||
|
||||
expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY});
|
||||
expect(queryClientHarness.queryClient.getQueryData(BOOKS_QUERY_KEY)).toBeUndefined();
|
||||
expect(service.isBooksLoading()).toBe(false);
|
||||
expect(service.booksError()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
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, vi} from 'vitest';
|
||||
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {CbxPageInfo, CbxReaderService} from './cbx-reader.service';
|
||||
|
||||
describe('CbxReaderService', () => {
|
||||
let service: CbxReaderService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: Pick<AuthService, 'getInternalAccessToken'>;
|
||||
|
||||
beforeEach(() => {
|
||||
authService = {
|
||||
getInternalAccessToken: vi.fn(() => 'token-123'),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
CbxReaderService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(CbxReaderService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('requests available pages and appends the auth token', () => {
|
||||
const response = [1, 2, 3];
|
||||
|
||||
let result: number[] | undefined;
|
||||
service.getAvailablePages(7).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.urlWithParams.endsWith('/api/v1/cbx/7/pages?token=token-123'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(response);
|
||||
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
|
||||
it('includes book type alongside the auth token when requesting page info', () => {
|
||||
const response: CbxPageInfo[] = [{pageNumber: 1, displayName: 'Cover'}];
|
||||
|
||||
let result: CbxPageInfo[] | undefined;
|
||||
service.getPageInfo(9, 'CBX').subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.urlWithParams.endsWith('/api/v1/cbx/9/page-info?bookType=CBX&token=token-123'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(response);
|
||||
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
|
||||
it('returns page image urls with both book type and token when provided', () => {
|
||||
const url = service.getPageImageUrl(12, 4, 'CBX');
|
||||
|
||||
expect(url).toBe('http://localhost:6060/api/v1/media/book/12/cbx/pages/4?bookType=CBX&token=token-123');
|
||||
});
|
||||
|
||||
it('returns unmodified urls when no auth token is available', () => {
|
||||
vi.mocked(authService.getInternalAccessToken).mockReturnValue(null);
|
||||
|
||||
const url = service.getPageImageUrl(12, 4);
|
||||
|
||||
expect(url).toBe('http://localhost:6060/api/v1/media/book/12/cbx/pages/4');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {libraryFormatCountsQueryKey, LIBRARIES_QUERY_KEY} from './library-query-keys';
|
||||
|
||||
describe('library-query-keys', () => {
|
||||
it('uses a stable key for the libraries collection', () => {
|
||||
expect(LIBRARIES_QUERY_KEY).toEqual(['libraries']);
|
||||
});
|
||||
|
||||
it('derives per-library format count keys', () => {
|
||||
expect(libraryFormatCountsQueryKey(42)).toEqual(['libraries', 'format-counts', 42]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs a seam around nested Prime confirmation payloads,
|
||||
// router/navigation side effects, clipboard writes, and multiple dialog/task services so menu-item
|
||||
// command wiring can be asserted without turning the spec into a brittle integration harness.
|
||||
describe.skip('LibraryShelfMenuService', () => {
|
||||
it('needs a menu-command seam to verify library, shelf, and magic-shelf action wiring deterministically', () => {
|
||||
// TODO(seam): Cover confirmation payloads, delete/refresh commands, and dialog launches after introducing a thin menu-action adapter.
|
||||
});
|
||||
|
||||
it('needs a browser-side seam to verify clipboard and navigation behavior without relying on global runtime objects', () => {
|
||||
// TODO(seam): Cover magic-shelf export and post-delete navigation once clipboard/router effects are injectable.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import {HttpTestingController} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
|
||||
import type {Library} from '../model/library.model';
|
||||
import {BookService} from './book.service';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys';
|
||||
import {LibraryService} from './library.service';
|
||||
|
||||
function buildLibrary(overrides: Partial<Library> = {}): Library {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'Zeta Library',
|
||||
watch: true,
|
||||
paths: [{path: '/books'}],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('LibraryService', () => {
|
||||
let service: LibraryService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
let bookService: {
|
||||
books: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
authService = createAuthServiceStub();
|
||||
queryClientHarness = createQueryClientHarness();
|
||||
bookService = {
|
||||
books: vi.fn(() => []),
|
||||
};
|
||||
|
||||
vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
|
||||
vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...queryClientHarness.providers,
|
||||
LibraryService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: BookService, useValue: bookService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(LibraryService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
flushSignalAndQueryEffects();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClientHarness.queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('refreshes and patches library metadata endpoints while invalidating the library cache', () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
|
||||
|
||||
service.refreshLibrary(9).subscribe();
|
||||
const refreshRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/9/refresh'));
|
||||
expect(refreshRequest.request.method).toBe('PUT');
|
||||
refreshRequest.flush(null);
|
||||
|
||||
service.updateLibraryFileNamingPattern(9, '{Authors}/{Title}').subscribe();
|
||||
const patternRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/9/file-naming-pattern'));
|
||||
expect(patternRequest.request.method).toBe('PATCH');
|
||||
expect(patternRequest.request.body).toEqual({fileNamingPattern: '{Authors}/{Title}'});
|
||||
patternRequest.flush(buildLibrary({id: 9, fileNamingPattern: '{Authors}/{Title}'}));
|
||||
|
||||
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||
});
|
||||
|
||||
it('invalidates library and book caches after update and delete flows', () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
|
||||
|
||||
service.updateLibrary(buildLibrary({name: 'Updated'}), 4).subscribe();
|
||||
const updateRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/4'));
|
||||
expect(updateRequest.request.method).toBe('PUT');
|
||||
updateRequest.flush(buildLibrary({id: 4, name: 'Updated'}));
|
||||
|
||||
service.deleteLibrary(4).subscribe();
|
||||
const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/4'));
|
||||
expect(deleteRequest.request.method).toBe('DELETE');
|
||||
deleteRequest.flush(null);
|
||||
|
||||
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||
expect(queryClientHarness.queryClient.removeQueries).toHaveBeenCalledWith({queryKey: libraryFormatCountsQueryKey(4), exact: true});
|
||||
});
|
||||
|
||||
it('hydrates format counts through ensureQueryData and tracks large-library loading state', async () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
|
||||
|
||||
const resultPromise = new Promise<Record<string, number>>((resolve, reject) => {
|
||||
service.getBookCountsByFormat(8).subscribe({next: resolve, error: reject});
|
||||
});
|
||||
await Promise.resolve();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/8/format-counts'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({EPUB: 7, PDF: 2});
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({EPUB: 7, PDF: 2});
|
||||
|
||||
service.setLargeLibraryLoading(true, 2500);
|
||||
expect(service.largeLibraryLoading()).toEqual({isLoading: true, expectedCount: 2500});
|
||||
|
||||
bookService.books.mockReturnValue([
|
||||
{libraryId: 8, shelves: []},
|
||||
{libraryId: 8, shelves: []},
|
||||
{libraryId: 9, shelves: []},
|
||||
]);
|
||||
expect(service.getBookCountValue(8)).toBe(2);
|
||||
});
|
||||
|
||||
it('removes library queries when the auth token becomes null', () => {
|
||||
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
|
||||
authService.token.set(null);
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
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 {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../../shared/model/metadata-batch-progress.model';
|
||||
import {
|
||||
FetchedMetadataProposalStatus,
|
||||
MetadataFetchTask,
|
||||
MetadataTaskService,
|
||||
} from './metadata-task';
|
||||
|
||||
describe('MetadataTaskService', () => {
|
||||
let service: MetadataTaskService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
MetadataTaskService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(MetadataTaskService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('maps the wrapped task response when fetching a task with proposals', () => {
|
||||
const task: MetadataFetchTask = {
|
||||
id: 'task-1',
|
||||
status: 'IN_PROGRESS',
|
||||
completed: 2,
|
||||
totalBooks: 5,
|
||||
startedAt: '2026-03-26T00:00:00Z',
|
||||
completedAt: null,
|
||||
initiatedBy: 'alice',
|
||||
errorMessage: null,
|
||||
proposals: [
|
||||
{
|
||||
proposalId: 42,
|
||||
taskId: 'task-1',
|
||||
bookId: 9,
|
||||
fetchedAt: '2026-03-26T00:00:01Z',
|
||||
reviewedAt: null,
|
||||
reviewerUserId: null,
|
||||
status: FetchedMetadataProposalStatus.FETCHED,
|
||||
metadataJson: {title: 'Dune'} as MetadataFetchTask['proposals'][number]['metadataJson'],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let result: MetadataFetchTask | undefined;
|
||||
service.getTaskWithProposals('task-1').subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/metadata/tasks/task-1'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({task});
|
||||
|
||||
expect(result).toEqual(task);
|
||||
});
|
||||
|
||||
it('deletes tasks by id', () => {
|
||||
let completed = false;
|
||||
service.deleteTask('task-2').subscribe(() => {
|
||||
completed = true;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/metadata/tasks/task-2'));
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
|
||||
it('posts status updates with the requested query param', () => {
|
||||
let completed = false;
|
||||
service.updateProposalStatus('task-3', 17, 'ACCEPTED').subscribe(() => {
|
||||
completed = true;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/metadata/tasks/task-3/proposals/17/status')
|
||||
&& req.params.get('status') === 'ACCEPTED'
|
||||
);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toBeNull();
|
||||
request.flush(null);
|
||||
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
|
||||
it('fetches active tasks directly from the active endpoint', () => {
|
||||
const tasks: MetadataBatchProgressNotification[] = [
|
||||
{
|
||||
taskId: 'task-4',
|
||||
completed: 3,
|
||||
total: 8,
|
||||
message: 'still running',
|
||||
status: MetadataBatchStatus.IN_PROGRESS,
|
||||
review: false,
|
||||
},
|
||||
];
|
||||
|
||||
let result: MetadataBatchProgressNotification[] | undefined;
|
||||
service.getActiveTasks().subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/metadata/tasks/active'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(tasks);
|
||||
|
||||
expect(result).toEqual(tasks);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import {HttpTestingController} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
|
||||
import type {Book} from '../model/book.model';
|
||||
import type {Shelf} from '../model/shelf.model';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {BookService} from './book.service';
|
||||
import {ShelfService} from './shelf.service';
|
||||
|
||||
function buildShelf(overrides: Partial<Shelf> = {}): Shelf {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'Favorites',
|
||||
userId: 7,
|
||||
bookCount: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Main Library',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('ShelfService', () => {
|
||||
let service: ShelfService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
let bookService: {
|
||||
books: ReturnType<typeof vi.fn>;
|
||||
removeBooksFromShelf: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {
|
||||
getCurrentUser: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
authService = createAuthServiceStub();
|
||||
queryClientHarness = createQueryClientHarness();
|
||||
bookService = {
|
||||
books: vi.fn(() => []),
|
||||
removeBooksFromShelf: vi.fn(),
|
||||
};
|
||||
userService = {
|
||||
getCurrentUser: vi.fn(() => null),
|
||||
};
|
||||
|
||||
vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
|
||||
vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...queryClientHarness.providers,
|
||||
ShelfService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: UserService, useValue: userService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(ShelfService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
flushSignalAndQueryEffects();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClientHarness.queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function flushShelvesQueryResult(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
}
|
||||
|
||||
it('eagerly fetches shelves and hydrates the computed shelves signal', async () => {
|
||||
const response = [
|
||||
buildShelf({id: 1, name: 'Reading', userId: 7}),
|
||||
buildShelf({id: 2, name: 'Archive', userId: 9, bookCount: 5}),
|
||||
];
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(response);
|
||||
await flushShelvesQueryResult();
|
||||
|
||||
expect(service.shelves()).toEqual(response);
|
||||
expect(service.shelvesError()).toBeNull();
|
||||
});
|
||||
|
||||
it('removes shelf queries when the auth token is cleared', () => {
|
||||
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
|
||||
|
||||
authService.token.set(null);
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves']});
|
||||
});
|
||||
|
||||
it('invalidates shelf queries for reload/create/update/delete flows and removes books on delete', () => {
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
|
||||
|
||||
service.reloadShelves();
|
||||
|
||||
service.createShelf(buildShelf({name: 'New Shelf'})).subscribe();
|
||||
const createRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves'));
|
||||
expect(createRequest.request.method).toBe('POST');
|
||||
createRequest.flush(buildShelf({id: 11, name: 'New Shelf'}));
|
||||
|
||||
service.updateShelf(buildShelf({name: 'Updated Shelf'}), 11).subscribe();
|
||||
const updateRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11'));
|
||||
expect(updateRequest.request.method).toBe('PUT');
|
||||
updateRequest.flush(buildShelf({id: 11, name: 'Updated Shelf'}));
|
||||
|
||||
service.deleteShelf(11).subscribe();
|
||||
const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11'));
|
||||
expect(deleteRequest.request.method).toBe('DELETE');
|
||||
deleteRequest.flush(null);
|
||||
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(4);
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true});
|
||||
expect(bookService.removeBooksFromShelf).toHaveBeenCalledWith(11);
|
||||
});
|
||||
|
||||
it('uses owner-aware shelf counts and falls back to persisted counts for non-owners', async () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([
|
||||
buildShelf({id: 1, userId: 7, bookCount: 99}),
|
||||
buildShelf({id: 2, userId: 10, bookCount: 6}),
|
||||
]);
|
||||
await flushShelvesQueryResult();
|
||||
|
||||
bookService.books.mockReturnValue([
|
||||
buildBook(1, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
|
||||
buildBook(2, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
|
||||
buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}),
|
||||
]);
|
||||
|
||||
userService.getCurrentUser.mockReturnValue({id: 7});
|
||||
expect(service.getBookCountValue(1)).toBe(2);
|
||||
|
||||
userService.getCurrentUser.mockReturnValue({id: 42});
|
||||
expect(service.getBookCountValue(2)).toBe(6);
|
||||
expect(service.getBookCountValue(999)).toBe(0);
|
||||
});
|
||||
|
||||
it('counts unshelved books from the current book cache snapshot', () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
|
||||
|
||||
bookService.books.mockReturnValue([
|
||||
buildBook(1, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
|
||||
buildBook(2, {shelves: []}),
|
||||
buildBook(3, {shelves: undefined}),
|
||||
]);
|
||||
|
||||
expect(service.getUnshelvedBookCountValue()).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {SortDirection, SortOption} from '../model/sort.model';
|
||||
import {Book, ReadStatus} from '../model/book.model';
|
||||
import {SortService} from './sort.service';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
fileName: `Book ${id}`,
|
||||
primaryFile: {id, bookId: id, bookType: 'EPUB'},
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
seriesName: `Series ${id}`,
|
||||
publishedDate: '2024-01-01',
|
||||
pageCount: id * 100,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('SortService', () => {
|
||||
const service = new SortService();
|
||||
|
||||
it('returns the original array when no sort is provided', () => {
|
||||
const books = [makeBook(1), makeBook(2)];
|
||||
|
||||
expect(service.applySort(books, null)).toBe(books);
|
||||
expect(service.applyMultiSort(books, [])).toBe(books);
|
||||
});
|
||||
|
||||
it('sorts by title and file name using natural ordering', () => {
|
||||
const books = [
|
||||
makeBook(2, {fileName: 'Book 10', metadata: {bookId: 2, title: 'Book 10'}}),
|
||||
makeBook(1, {fileName: 'Book 2', metadata: {bookId: 1, title: 'Book 2'}}),
|
||||
];
|
||||
const sortOption: SortOption = {label: 'Title', field: 'title', direction: SortDirection.ASCENDING};
|
||||
|
||||
expect(service.applySort(books, sortOption).map(book => book.id)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('sorts by array fields and read status rank', () => {
|
||||
const books = [
|
||||
makeBook(1, {metadata: {bookId: 1, authors: ['Jane Zed']}, readStatus: ReadStatus.READ}),
|
||||
makeBook(2, {metadata: {bookId: 2, authors: ['Adam Alpha']}, readStatus: ReadStatus.READING}),
|
||||
makeBook(3, {metadata: {bookId: 3, authors: ['Jane Zed']}, readStatus: ReadStatus.UNREAD}),
|
||||
];
|
||||
|
||||
expect(service.applyMultiSort(books, [
|
||||
{label: 'Authors', field: 'authorSurnameVorname', direction: SortDirection.ASCENDING},
|
||||
]).map(book => book.id)).toEqual([2, 1, 3]);
|
||||
|
||||
expect(service.applyMultiSort(books, [
|
||||
{label: 'Status', field: 'readStatus', direction: SortDirection.DESCENDING},
|
||||
]).map(book => book.id)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('keeps null values sorted after non-null values and warns on unknown fields', () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
const books = [
|
||||
makeBook(1, {metadata: {bookId: 1}}),
|
||||
makeBook(2, {metadata: {bookId: 2, publishedDate: '2023-01-01'}}),
|
||||
];
|
||||
|
||||
expect(service.applyMultiSort(books, [
|
||||
{label: 'Published', field: 'publishedDate', direction: SortDirection.ASCENDING},
|
||||
]).map(book => book.id)).toEqual([2, 1]);
|
||||
|
||||
expect(service.applyMultiSort(books, [
|
||||
{label: 'Unknown', field: 'doesNotExist', direction: SortDirection.ASCENDING},
|
||||
])).toEqual(books);
|
||||
expect(warnSpy).toHaveBeenCalledWith('[SortService] No extractor for field: doesNotExist');
|
||||
});
|
||||
});
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {BookdropBulkEditDialogComponent, BulkEditResult} from './bookdrop-bulk-edit-dialog.component';
|
||||
|
||||
describe('BookdropBulkEditDialogComponent', () => {
|
||||
let fixture: ComponentFixture<BookdropBulkEditDialogComponent>;
|
||||
let component: BookdropBulkEditDialogComponent;
|
||||
let dialogRef: {close: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [BookdropBulkEditDialogComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: DynamicDialogConfig, useValue: {data: {fileCount: 4}}},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(BookdropBulkEditDialogComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function blurAutoComplete(fieldName: string, value: string) {
|
||||
const input = document.createElement('input');
|
||||
input.value = value;
|
||||
|
||||
component.onAutoCompleteBlur(fieldName, {target: input} as unknown as Event);
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
it('hydrates the file count and enables fields when form controls receive values', () => {
|
||||
component.getControl('seriesName').setValue('Saga');
|
||||
component.getControl('seriesTotal').setValue(7);
|
||||
|
||||
expect(component.fileCount).toBe(4);
|
||||
expect(component.enabledFields.has('seriesName')).toBe(true);
|
||||
expect(component.enabledFields.has('seriesTotal')).toBe(true);
|
||||
expect(component.hasEnabledFields).toBe(true);
|
||||
});
|
||||
|
||||
it('adds trimmed autocomplete blur values once, clears the input, and enables the chip field', () => {
|
||||
const firstInput = blurAutoComplete('authors', ' Octavia Butler ');
|
||||
const duplicateInput = blurAutoComplete('authors', 'Octavia Butler');
|
||||
const blankInput = blurAutoComplete('authors', ' ');
|
||||
|
||||
expect(component.getControl('authors').value).toEqual(['Octavia Butler']);
|
||||
expect(component.enabledFields.has('authors')).toBe(true);
|
||||
expect(firstInput.value).toBe('');
|
||||
expect(duplicateInput.value).toBe('');
|
||||
expect(blankInput.value).toBe(' ');
|
||||
});
|
||||
|
||||
it('toggles fields on and off explicitly', () => {
|
||||
component.toggleField('publisher');
|
||||
expect(component.isFieldEnabled('publisher')).toBe(true);
|
||||
|
||||
component.toggleField('publisher');
|
||||
expect(component.isFieldEnabled('publisher')).toBe(false);
|
||||
});
|
||||
|
||||
it('applies only enabled non-null fields and preserves merge mode in the dialog result', () => {
|
||||
component.getControl('seriesName').setValue('Saga');
|
||||
component.getControl('authors').setValue(['Octavia Butler', 'N. K. Jemisin']);
|
||||
component.toggleField('publisher');
|
||||
component.mergeArrays = false;
|
||||
|
||||
component.apply();
|
||||
|
||||
const result = dialogRef.close.mock.calls[0]?.[0] as BulkEditResult;
|
||||
|
||||
expect(result.fields).toEqual({
|
||||
seriesName: 'Saga',
|
||||
authors: ['Octavia Butler', 'N. K. Jemisin'],
|
||||
publisher: '',
|
||||
});
|
||||
expect(result.enabledFields).toEqual(new Set(['seriesName', 'authors', 'publisher']));
|
||||
expect(result.mergeArrays).toBe(false);
|
||||
});
|
||||
|
||||
it('closes the dialog with null when cancelled', () => {
|
||||
component.cancel();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledWith(null);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around dialog payload bootstrapping,
|
||||
// autocomplete/search streams, and metadata copy/reset helpers so picker decisions can be
|
||||
// asserted without the full bookdrop dialog and PrimeNG form runtime.
|
||||
describe.skip('BookdropFileMetadataPickerComponent', () => {
|
||||
it('needs dialog and form seams to verify metadata bootstrap, reset, and apply behavior', () => {
|
||||
// TODO(seam): Cover initialization and confirmation branches once DynamicDialog config and reactive-form setup are isolated behind test doubles.
|
||||
});
|
||||
|
||||
it('needs search seams to verify candidate loading, selection changes, and duplicate-handling paths', () => {
|
||||
// TODO(seam): Cover autocomplete and metadata transfer flows after search streams and select widgets are extracted from the live component runtime.
|
||||
});
|
||||
});
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
import {DestroyRef, signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {FormGroup} from '@angular/forms';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {of} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {BookdropFileReviewComponent, BookdropFileUI} from './bookdrop-file-review.component';
|
||||
import {BookdropFile, BookdropFileStatus, BookdropService} from '../../service/bookdrop.service';
|
||||
import {Library} from '../../../book/model/library.model';
|
||||
import {LibraryService} from '../../../book/service/library.service';
|
||||
|
||||
describe('BookdropFileReviewComponent', () => {
|
||||
const add = vi.fn();
|
||||
const confirm = vi.fn();
|
||||
const getPendingFiles = vi.fn();
|
||||
const discardFiles = vi.fn();
|
||||
const finalizeImport = vi.fn();
|
||||
const rescan = vi.fn();
|
||||
const openBookdropFinalizeResultDialog = vi.fn();
|
||||
const openDialog = vi.fn();
|
||||
const openDirectoryPickerDialog = vi.fn();
|
||||
const setPageTitle = vi.fn();
|
||||
const translate = vi.fn((key: string, params?: Record<string, unknown>) => {
|
||||
if (!params) {
|
||||
return key;
|
||||
}
|
||||
|
||||
return `${key}:${Object.entries(params).map(([paramKey, value]) => `${paramKey}=${value}`).join(',')}`;
|
||||
});
|
||||
|
||||
const libraries = signal<Library[]>([]);
|
||||
const appSettings = signal<unknown>(null);
|
||||
|
||||
function makeLibrary(id: number, name: string, pathIds: number[]): Library {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
watch: false,
|
||||
paths: pathIds.map((pathId, index) => ({id: pathId, path: `${name}-${index + 1}`})),
|
||||
};
|
||||
}
|
||||
|
||||
function makeFile(id: number): BookdropFile {
|
||||
return {
|
||||
id,
|
||||
fileName: `file-${id}.epub`,
|
||||
filePath: `/incoming/file-${id}.epub`,
|
||||
fileSize: 1024,
|
||||
originalMetadata: {bookId: id, title: `Book ${id}`},
|
||||
createdAt: '2026-03-26T00:00:00Z',
|
||||
updatedAt: '2026-03-26T00:00:00Z',
|
||||
status: BookdropFileStatus.ACCEPTED,
|
||||
showDetails: false,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFileUi(
|
||||
id: number,
|
||||
overrides: Partial<BookdropFileUI> = {}
|
||||
): BookdropFileUI {
|
||||
return {
|
||||
file: makeFile(id),
|
||||
metadataForm: new FormGroup({}),
|
||||
copiedFields: {},
|
||||
savedFields: {},
|
||||
selected: false,
|
||||
showDetails: false,
|
||||
selectedLibraryId: null,
|
||||
selectedPathId: null,
|
||||
availablePaths: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createComponent(): BookdropFileReviewComponent {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: BookdropService,
|
||||
useValue: {
|
||||
getPendingFiles,
|
||||
discardFiles,
|
||||
finalizeImport,
|
||||
rescan,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: LibraryService,
|
||||
useValue: {
|
||||
libraries: libraries.asReadonly(),
|
||||
},
|
||||
},
|
||||
{provide: ConfirmationService, useValue: {confirm}},
|
||||
{provide: DestroyRef, useValue: {onDestroy: vi.fn()}},
|
||||
{
|
||||
provide: DialogLauncherService,
|
||||
useValue: {
|
||||
openBookdropFinalizeResultDialog,
|
||||
openDialog,
|
||||
openDirectoryPickerDialog,
|
||||
},
|
||||
},
|
||||
{provide: AppSettingsService, useValue: {appSettings: appSettings.asReadonly()}},
|
||||
{provide: MessageService, useValue: {add}},
|
||||
{provide: UrlHelperService, useValue: {getBookdropCoverUrl: vi.fn((id: number) => `/covers/${id}`)}},
|
||||
{provide: ActivatedRoute, useValue: {queryParams: of({}), snapshot: {queryParams: {}}}},
|
||||
{provide: PageTitleService, useValue: {setPageTitle}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
return TestBed.runInInjectionContext(() => new BookdropFileReviewComponent());
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
add.mockClear();
|
||||
confirm.mockClear();
|
||||
getPendingFiles.mockReset();
|
||||
discardFiles.mockReset();
|
||||
finalizeImport.mockReset();
|
||||
rescan.mockReset();
|
||||
openBookdropFinalizeResultDialog.mockClear();
|
||||
openDialog.mockClear();
|
||||
openDirectoryPickerDialog.mockClear();
|
||||
setPageTitle.mockClear();
|
||||
translate.mockClear();
|
||||
libraries.set([]);
|
||||
appSettings.set(null);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('derives defaults, selection counts, and finalize eligibility from both selection modes', () => {
|
||||
libraries.set([
|
||||
makeLibrary(1, 'Alpha', [10]),
|
||||
makeLibrary(2, 'Beta', [20, 21]),
|
||||
]);
|
||||
|
||||
const component = createComponent();
|
||||
const first = makeFileUi(1, {selected: true, selectedLibraryId: '1', selectedPathId: '10'});
|
||||
const second = makeFileUi(2, {selected: true, selectedLibraryId: '1', selectedPathId: '10'});
|
||||
const third = makeFileUi(3, {selected: false});
|
||||
|
||||
component.fileUiCache = {1: first, 2: second, 3: third};
|
||||
component.bookdropFileUis = [first, second, third];
|
||||
|
||||
component.defaultLibraryId = '1';
|
||||
expect(component.defaultPathId).toBe('10');
|
||||
expect(component.selectedLibraryPaths).toEqual([{label: 'Alpha-1', value: '10'}]);
|
||||
expect(component.canApplyDefaults).toBe(true);
|
||||
|
||||
expect(component.hasSelectedFiles).toBe(true);
|
||||
expect(component.selectedCount).toBe(2);
|
||||
expect(component.canFinalize).toBe(true);
|
||||
|
||||
second.selectedPathId = null;
|
||||
component.fileUiCache[2].selectedPathId = null;
|
||||
expect(component.canFinalize).toBe(false);
|
||||
|
||||
second.selectedPathId = '10';
|
||||
component.fileUiCache[2].selectedPathId = '10';
|
||||
component.selectAllAcrossPages = true;
|
||||
component.totalRecords = 10;
|
||||
component.excludedFiles.add(3);
|
||||
|
||||
expect(component.hasSelectedFiles).toBe(true);
|
||||
expect(component.selectedCount).toBe(9);
|
||||
expect(component.canFinalize).toBe(true);
|
||||
|
||||
component.fileUiCache[2].selectedPathId = null;
|
||||
expect(component.canFinalize).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the current-page selection state in sync with select-all changes', () => {
|
||||
const component = createComponent();
|
||||
const first = makeFileUi(1);
|
||||
const second = makeFileUi(2);
|
||||
|
||||
component.fileUiCache = {1: first, 2: second};
|
||||
component.bookdropFileUis = [first, second];
|
||||
|
||||
component.selectAll(true);
|
||||
expect(component.selectAllAcrossPages).toBe(true);
|
||||
expect(component.excludedFiles.size).toBe(0);
|
||||
expect(component.bookdropFileUis.map(file => file.selected)).toEqual([true, true]);
|
||||
expect(Object.values(component.fileUiCache).map(file => file.selected)).toEqual([true, true]);
|
||||
|
||||
component.toggleFileSelection(1, false);
|
||||
expect(component.excludedFiles.has(1)).toBe(true);
|
||||
expect(component.fileUiCache[1].selected).toBe(false);
|
||||
expect(component.bookdropFileUis[0].selected).toBe(false);
|
||||
|
||||
component.toggleFileSelection(1, true);
|
||||
expect(component.excludedFiles.has(1)).toBe(false);
|
||||
expect(component.fileUiCache[1].selected).toBe(true);
|
||||
|
||||
component.selectAll(false);
|
||||
expect(component.selectAllAcrossPages).toBe(false);
|
||||
expect(component.excludedFiles.size).toBe(0);
|
||||
expect(component.bookdropFileUis.map(file => file.selected)).toEqual([false, false]);
|
||||
expect(Object.values(component.fileUiCache).map(file => file.selected)).toEqual([false, false]);
|
||||
});
|
||||
|
||||
it('warns instead of prompting when destructive actions have no selected files', () => {
|
||||
const component = createComponent();
|
||||
component.bookdropFileUis = [];
|
||||
component.fileUiCache = {};
|
||||
|
||||
component.confirmReset();
|
||||
component.confirmFinalize();
|
||||
component.confirmDelete();
|
||||
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
expect(add).toHaveBeenCalledTimes(3);
|
||||
expect(add).toHaveBeenNthCalledWith(1, expect.objectContaining({
|
||||
severity: 'warn',
|
||||
summary: 'bookdrop.fileReview.toast.noFilesSelectedSummary',
|
||||
detail: 'bookdrop.fileReview.toast.noFilesResetDetail',
|
||||
}));
|
||||
expect(add).toHaveBeenNthCalledWith(2, expect.objectContaining({
|
||||
severity: 'warn',
|
||||
summary: 'bookdrop.fileReview.toast.noFilesSelectedSummary',
|
||||
detail: 'bookdrop.fileReview.toast.noFilesFinalizeDetail',
|
||||
}));
|
||||
expect(add).toHaveBeenNthCalledWith(3, expect.objectContaining({
|
||||
severity: 'warn',
|
||||
summary: 'bookdrop.fileReview.toast.noFilesSelectedSummary',
|
||||
detail: 'bookdrop.fileReview.toast.noFilesDeleteDetail',
|
||||
}));
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around the live summary stream, router
|
||||
// navigation timing, and widget lifecycle teardown so bookdrop notification state can be tested
|
||||
// without mounting the live websocket-backed runtime.
|
||||
describe.skip('BookdropFilesWidgetComponent', () => {
|
||||
it('needs subscription seams to verify pending-count updates and timestamp hydration from summary notifications', () => {
|
||||
// TODO(seam): Cover ngOnInit once the live summary observable is isolated behind a deterministic subject.
|
||||
});
|
||||
|
||||
it('needs routing seams to verify review navigation and destroy-time subscription cleanup', () => {
|
||||
// TODO(seam): Cover openReviewDialog and ngOnDestroy after extracting router and subscription lifecycle concerns.
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {BookdropFinalizeResultDialogComponent} from './bookdrop-finalize-result-dialog.component';
|
||||
|
||||
describe('BookdropFinalizeResultDialogComponent', () => {
|
||||
let fixture: ComponentFixture<BookdropFinalizeResultDialogComponent>;
|
||||
let component: BookdropFinalizeResultDialogComponent;
|
||||
let dialogRef: {close: ReturnType<typeof vi.fn>};
|
||||
const result = {
|
||||
totalFiles: 4,
|
||||
successfulFiles: 3,
|
||||
failedFiles: 1,
|
||||
finishedAt: '2026-03-26T00:00:00Z',
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [BookdropFinalizeResultDialogComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: DynamicDialogConfig, useValue: {data: {result}}},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(BookdropFinalizeResultDialogComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('hydrates the finalize result from the dialog config', () => {
|
||||
expect(component.result).toEqual(result);
|
||||
});
|
||||
|
||||
it('closes the dialog when the component is destroyed', () => {
|
||||
component.ngOnDestroy();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around dialog payload bootstrapping,
|
||||
// placeholder insertion with cursor management, preview extraction streams, and translated toast
|
||||
// side effects so pattern extraction can be asserted without browser selection APIs.
|
||||
describe.skip('BookdropPatternExtractDialogComponent', () => {
|
||||
it('needs input-cursor seams to verify placeholder insertion, duplicate placeholder replacement, and common-pattern application', () => {
|
||||
// TODO(seam): Cover insertPlaceholder and applyCommonPattern after input selection state and setTimeout cursor management are isolated behind deterministic helpers.
|
||||
});
|
||||
|
||||
it('needs service seams to verify preview, extraction success, and extraction failure behavior', () => {
|
||||
// TODO(seam): Cover previewPattern and extract once bookdrop service streams, dialog closing, and toast dispatch can be asserted without the live dialog runtime.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookdropFileApiService} from './bookdrop-file-api.service';
|
||||
|
||||
describe('BookdropFileApiService', () => {
|
||||
let service: BookdropFileApiService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookdropFileApiService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookdropFileApiService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('requests the current bookdrop notification summary', () => {
|
||||
let result: unknown;
|
||||
service.getNotification().subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/bookdrop/notification')
|
||||
);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({pendingCount: 3, totalCount: 8, lastUpdatedAt: '2026-03-26T00:00:00Z'});
|
||||
|
||||
expect(result).toEqual({
|
||||
pendingCount: 3,
|
||||
totalCount: 8,
|
||||
lastUpdatedAt: '2026-03-26T00:00:00Z',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {BookdropFileApiService} from './bookdrop-file-api.service';
|
||||
import {BookdropFileNotification, BookdropFileService} from './bookdrop-file.service';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
|
||||
describe('BookdropFileService', () => {
|
||||
let getNotification: ReturnType<typeof vi.fn>;
|
||||
let currentUser: ReturnType<typeof signal<{
|
||||
permissions: {admin: boolean; canAccessBookdrop: boolean};
|
||||
} | null>>;
|
||||
let token: ReturnType<typeof signal<string | null>>;
|
||||
let service: BookdropFileService;
|
||||
|
||||
const summary: BookdropFileNotification = {
|
||||
pendingCount: 2,
|
||||
totalCount: 6,
|
||||
lastUpdatedAt: '2026-03-26T00:00:00Z',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
getNotification = vi.fn(() => of(summary));
|
||||
currentUser = signal({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canAccessBookdrop: true,
|
||||
},
|
||||
});
|
||||
token = signal('token');
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookdropFileService,
|
||||
{provide: BookdropFileApiService, useValue: {getNotification}},
|
||||
{provide: AuthService, useValue: {token}},
|
||||
{provide: UserService, useValue: {currentUser}},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('initializes from the API once for users who can access bookdrop and have a token', () => {
|
||||
service = TestBed.inject(BookdropFileService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
let latestSummary: BookdropFileNotification | undefined;
|
||||
service.summary$.subscribe(value => {
|
||||
latestSummary = value;
|
||||
});
|
||||
|
||||
expect(getNotification).toHaveBeenCalledOnce();
|
||||
expect(latestSummary).toEqual(summary);
|
||||
});
|
||||
|
||||
it('does not auto-refresh when the current user lacks access', () => {
|
||||
currentUser.set({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canAccessBookdrop: false,
|
||||
},
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookdropFileService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(getNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('publishes incoming file summaries and pending state', () => {
|
||||
service = TestBed.inject(BookdropFileService);
|
||||
|
||||
let hasPendingFiles: boolean | undefined;
|
||||
service.hasPendingFiles$.subscribe(value => {
|
||||
hasPendingFiles = value;
|
||||
});
|
||||
|
||||
service.handleIncomingFile(summary);
|
||||
expect(hasPendingFiles).toBe(true);
|
||||
|
||||
service.handleIncomingFile({...summary, pendingCount: 0});
|
||||
expect(hasPendingFiles).toBe(false);
|
||||
});
|
||||
|
||||
it('warns when manual refresh fails', () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
getNotification.mockReturnValueOnce(throwError(() => new Error('boom')));
|
||||
service = TestBed.inject(BookdropFileService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
service.refresh();
|
||||
|
||||
expect(warnSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
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 {BookdropService} from './bookdrop.service';
|
||||
|
||||
describe('BookdropService', () => {
|
||||
let service: BookdropService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookdropService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookdropService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('requests pending files with default pagination', () => {
|
||||
service.getPendingFiles().subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(
|
||||
'http://localhost:6060/api/v1/bookdrop/files?status=pending&page=0&size=50'
|
||||
);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({content: [], page: {totalElements: 0, totalPages: 0, number: 0, size: 50}});
|
||||
});
|
||||
|
||||
it('posts finalize, discard, rescan, extract, and bulk-edit requests to the expected endpoints', () => {
|
||||
const finalizePayload = {selectAll: true};
|
||||
const discardPayload = {selectAll: false, selectedIds: [1, 2]};
|
||||
const extractPayload = {pattern: '{author}', preview: true};
|
||||
const bulkEditPayload = {
|
||||
fields: {title: 'Dune'},
|
||||
enabledFields: ['title'],
|
||||
mergeArrays: false,
|
||||
};
|
||||
|
||||
service.finalizeImport(finalizePayload).subscribe();
|
||||
service.discardFiles(discardPayload).subscribe();
|
||||
service.rescan().subscribe();
|
||||
service.extractFromPattern(extractPayload).subscribe();
|
||||
service.bulkEditMetadata(bulkEditPayload).subscribe();
|
||||
|
||||
const finalizeRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/imports/finalize'));
|
||||
expect(finalizeRequest.request.body).toEqual(finalizePayload);
|
||||
finalizeRequest.flush({});
|
||||
|
||||
const discardRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/files/discard'));
|
||||
expect(discardRequest.request.body).toEqual(discardPayload);
|
||||
discardRequest.flush(null);
|
||||
|
||||
const rescanRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/rescan'));
|
||||
expect(rescanRequest.request.body).toEqual({});
|
||||
rescanRequest.flush(null);
|
||||
|
||||
const extractRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/files/extract-pattern'));
|
||||
expect(extractRequest.request.body).toEqual(extractPayload);
|
||||
extractRequest.flush({});
|
||||
|
||||
const bulkEditRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/files/bulk-edit'));
|
||||
expect(bulkEditRequest.request.body).toEqual(bulkEditPayload);
|
||||
bulkEditRequest.flush({});
|
||||
});
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around ngx-infinite-scroll, nested book-card
|
||||
// interactions, and overlay/menu state so scroller paging and open-menu coordination can be tested
|
||||
// without booting a full dashboard rendering stack.
|
||||
describe.skip('DashboardScrollerComponent', () => {
|
||||
it('needs scroller and card seams to verify force-ebook mode, infinite scrolling, and menu-toggle behavior', () => {
|
||||
// TODO(seam): Cover scroller rendering and book-card coordination once the scroll and card interactions are isolated.
|
||||
});
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around effect-driven dashboard config syncing,
|
||||
// dynamic dialog lifecycle, translated option rebuilding, and magic-shelf collections so config edits
|
||||
// can be asserted without coupling the spec to the full dashboard settings UI.
|
||||
describe.skip('DashboardSettingsComponent', () => {
|
||||
it('needs config and dialog seams to verify scroller add/remove/reorder behavior and translated option rebuilding', () => {
|
||||
// TODO(seam): Cover dashboard config mutation and save/close flows once the config service and dialog interactions are wrapped.
|
||||
});
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around computed dashboard config signals,
|
||||
// magic-shelf rule evaluation, sorting, dialog launches, and page-title side effects so scroller
|
||||
// selection logic can be tested without instantiating the full dashboard ecosystem.
|
||||
describe.skip('MainDashboardComponent', () => {
|
||||
it('needs dashboard-config and magic-shelf seams to verify scroller book selection and page setup deterministically', () => {
|
||||
// TODO(seam): Cover per-scroller book selection, randomization, and page-title behavior after the dependent services are adapterized.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {DEFAULT_DASHBOARD_CONFIG, ScrollerType} from './dashboard-config.model';
|
||||
|
||||
describe('dashboard-config.model', () => {
|
||||
it('ships with four enabled default scrollers', () => {
|
||||
expect(DEFAULT_DASHBOARD_CONFIG.scrollers).toHaveLength(4);
|
||||
expect(DEFAULT_DASHBOARD_CONFIG.scrollers.every((scroller) => scroller.enabled)).toBe(true);
|
||||
});
|
||||
|
||||
it('uses ordered defaults and a shared max-items value across all defaults', () => {
|
||||
const maxItems = DEFAULT_DASHBOARD_CONFIG.scrollers.map((scroller) => scroller.maxItems);
|
||||
|
||||
expect(DEFAULT_DASHBOARD_CONFIG.scrollers.map((scroller) => scroller.order)).toEqual([1, 2, 3, 4]);
|
||||
expect(new Set(maxItems).size).toBe(1);
|
||||
expect(maxItems[0]).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('covers the expected default scroller types', () => {
|
||||
expect(DEFAULT_DASHBOARD_CONFIG.scrollers.map((scroller) => scroller.type)).toEqual([
|
||||
ScrollerType.LAST_LISTENED,
|
||||
ScrollerType.LAST_READ,
|
||||
ScrollerType.LATEST_ADDED,
|
||||
ScrollerType.RANDOM
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {MagicShelfService, type MagicShelf} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {DEFAULT_DASHBOARD_CONFIG, type DashboardConfig, ScrollerType} from '../models/dashboard-config.model';
|
||||
import {DashboardConfigService} from './dashboard-config.service';
|
||||
|
||||
describe('DashboardConfigService', () => {
|
||||
const updateUserSetting = vi.fn();
|
||||
interface TestUser {
|
||||
id: number;
|
||||
userSettings?: {
|
||||
dashboardConfig?: DashboardConfig;
|
||||
};
|
||||
}
|
||||
const userState = signal<TestUser | null>(null);
|
||||
const shelvesState = signal<MagicShelf[]>([]);
|
||||
|
||||
const userService = {
|
||||
currentUser: userState.asReadonly(),
|
||||
getCurrentUser: vi.fn(() => userState()),
|
||||
updateUserSetting,
|
||||
};
|
||||
|
||||
const magicShelfService = {
|
||||
shelves: shelvesState.asReadonly(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
updateUserSetting.mockReset();
|
||||
userService.getCurrentUser.mockReset();
|
||||
userService.getCurrentUser.mockImplementation(() => userState());
|
||||
userState.set(null);
|
||||
shelvesState.set([]);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
DashboardConfigService,
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: MagicShelfService, useValue: magicShelfService},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('normalizes missing dashboard config to a cloned default value', () => {
|
||||
userState.set({
|
||||
id: 11,
|
||||
userSettings: {dashboardConfig: {scrollers: []}},
|
||||
});
|
||||
|
||||
const service = TestBed.inject(DashboardConfigService);
|
||||
|
||||
expect(service.config()).toEqual(DEFAULT_DASHBOARD_CONFIG);
|
||||
expect(service.config()).not.toBe(DEFAULT_DASHBOARD_CONFIG);
|
||||
});
|
||||
|
||||
it('syncs renamed magic shelf titles into the config and persists the change', async () => {
|
||||
userState.set({
|
||||
id: 12,
|
||||
userSettings: {
|
||||
dashboardConfig: {
|
||||
scrollers: [
|
||||
{
|
||||
id: '1',
|
||||
type: ScrollerType.MAGIC_SHELF,
|
||||
title: 'Old shelf title',
|
||||
enabled: true,
|
||||
order: 1,
|
||||
maxItems: 20,
|
||||
magicShelfId: 55,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const service = TestBed.inject(DashboardConfigService);
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
shelvesState.set([{id: 55, name: 'New shelf title', filterJson: '{}'} as MagicShelf]);
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
expect(service.config().scrollers[0].title).toBe('New shelf title');
|
||||
expect(updateUserSetting).toHaveBeenCalledWith(12, 'dashboardConfig', {
|
||||
scrollers: [
|
||||
{
|
||||
id: '1',
|
||||
type: ScrollerType.MAGIC_SHELF,
|
||||
title: 'New shelf title',
|
||||
enabled: true,
|
||||
order: 1,
|
||||
maxItems: 20,
|
||||
magicShelfId: 55,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('saves normalized configs and skips persistence when no user is available', () => {
|
||||
const service = TestBed.inject(DashboardConfigService);
|
||||
|
||||
service.saveConfig({
|
||||
scrollers: [
|
||||
{
|
||||
id: '9',
|
||||
type: ScrollerType.LATEST_ADDED,
|
||||
title: 'recent',
|
||||
enabled: true,
|
||||
order: 1,
|
||||
maxItems: 15,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(service.config().scrollers[0].id).toBe('9');
|
||||
expect(updateUserSetting).not.toHaveBeenCalled();
|
||||
|
||||
userState.set({
|
||||
id: 21,
|
||||
userSettings: {dashboardConfig: DEFAULT_DASHBOARD_CONFIG},
|
||||
});
|
||||
|
||||
service.resetToDefault();
|
||||
|
||||
expect(updateUserSetting).toHaveBeenCalledWith(21, 'dashboardConfig', DEFAULT_DASHBOARD_CONFIG);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): This component currently couples DynamicDialog config/ref data,
|
||||
// router navigation, live library/icon services, format-count HTTP reads, drag-drop, and
|
||||
// transloco-backed option initialization in one large standalone surface. Honest coverage
|
||||
// needs a narrower presenter seam or a purpose-built harness, not a brittle all-up mock stack.
|
||||
describe.skip('LibraryCreatorComponent', () => {
|
||||
it('needs a dialog-and-library seam to verify create vs edit initialization and duplicate-name handling', () => {
|
||||
// TODO(seam): Cover dialog mode hydration, icon normalization, and duplicate-name validation
|
||||
// once the component state can be supplied without mocking the full runtime graph.
|
||||
});
|
||||
|
||||
it('needs a stable interaction seam to verify format selection, folder updates, and submit payload assembly', () => {
|
||||
// TODO(seam): Cover allowed-format toggles, folder selection, and create/update submission
|
||||
// after these flows are exposed behind testable methods or a smaller facade.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Replace this skipped spec once the component-factory lifecycle
|
||||
// is wrapped behind a testable seam. The current service hard-codes Angular's
|
||||
// `createComponent()` ESM export plus direct `document.body` mutation, and Vitest in
|
||||
// this browser-mode setup cannot reliably intercept that export to prove attach/detach
|
||||
// behavior without changing runtime code.
|
||||
describe.skip('LibraryLoadingService', () => {
|
||||
it('needs a component-factory seam to verify dynamic creation and teardown', () => {
|
||||
// TODO(seam): Cover component creation, progress updates, and body overflow cleanup
|
||||
// after introducing a testable wrapper around createComponent/document.body behavior.
|
||||
});
|
||||
});
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {LibraryLoadingComponent} from './library-loading.component';
|
||||
|
||||
describe('LibraryLoadingComponent', () => {
|
||||
it('computes progress percentage and completion state from the latest update', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
|
||||
component.updateProgress('Dune', 2, 3);
|
||||
|
||||
expect(component.bookTitle).toBe('Dune');
|
||||
expect(component.current).toBe(2);
|
||||
expect(component.total).toBe(3);
|
||||
expect(component.percentage).toBe(67);
|
||||
expect(component.isComplete).toBe(false);
|
||||
});
|
||||
|
||||
it('marks the flow complete when current reaches the total', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
|
||||
component.updateProgress('Children of Dune', 5, 5);
|
||||
|
||||
expect(component.isComplete).toBe(true);
|
||||
expect(component.percentage).toBe(100);
|
||||
});
|
||||
|
||||
it('truncates very long titles for display', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
component.bookTitle = 'A'.repeat(60);
|
||||
|
||||
expect(component.truncatedTitle).toBe(`${'A'.repeat(50)}...`);
|
||||
});
|
||||
|
||||
it('returns zero percent when there is no total yet', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
|
||||
expect(component.percentage).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import {HttpTestingController} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
|
||||
import type {Book} from '../../book/model/book.model';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import type {GroupRule} from '../component/magic-shelf-component';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
|
||||
import {MagicShelfService, type MagicShelf} from './magic-shelf.service';
|
||||
|
||||
function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf {
|
||||
return {
|
||||
id: 1,
|
||||
name: 'Favorites',
|
||||
icon: 'pi pi-star',
|
||||
iconType: 'PRIME_NG',
|
||||
filterJson: JSON.stringify(buildGroupRule()),
|
||||
isPublic: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildGroupRule(overrides: Partial<GroupRule> = {}): GroupRule {
|
||||
return {
|
||||
name: 'Favorites',
|
||||
type: 'group',
|
||||
join: 'and',
|
||||
rules: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Main Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function flushShelvesQuery(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
flushSignalAndQueryEffects();
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
}
|
||||
|
||||
describe('MagicShelfService', () => {
|
||||
let service: MagicShelfService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
let bookService: {
|
||||
books: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let ruleEvaluatorService: {
|
||||
evaluateGroup: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
authService = createAuthServiceStub();
|
||||
queryClientHarness = createQueryClientHarness();
|
||||
queryClientHarness.queryClient.setDefaultOptions({
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
|
||||
bookService = {
|
||||
books: vi.fn(() => []),
|
||||
};
|
||||
ruleEvaluatorService = {
|
||||
evaluateGroup: vi.fn(() => false),
|
||||
};
|
||||
|
||||
vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
|
||||
vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...queryClientHarness.providers,
|
||||
MagicShelfService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: BookRuleEvaluatorService, useValue: ruleEvaluatorService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(MagicShelfService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
flushSignalAndQueryEffects();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClientHarness.queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('eagerly fetches shelves and hydrates the computed shelves signal', async () => {
|
||||
const shelves = [
|
||||
buildMagicShelf({id: 1, name: 'Reading'}),
|
||||
buildMagicShelf({id: 2, name: 'Finished', isPublic: true}),
|
||||
];
|
||||
|
||||
expect(service.shelves()).toEqual([]);
|
||||
expect(service.isShelvesLoading()).toBe(true);
|
||||
expect(service.shelvesError()).toBeNull();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(shelves);
|
||||
await flushShelvesQuery();
|
||||
|
||||
expect(service.shelves()).toEqual(shelves);
|
||||
expect(service.isShelvesLoading()).toBe(false);
|
||||
expect(service.shelvesError()).toBeNull();
|
||||
});
|
||||
|
||||
it('removes shelf queries when the auth token is cleared', async () => {
|
||||
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([
|
||||
buildMagicShelf({id: 7, name: 'Cached'}),
|
||||
]);
|
||||
await flushShelvesQuery();
|
||||
|
||||
authService.token.set(null);
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves']});
|
||||
});
|
||||
|
||||
it('invalidates shelf queries after save and serializes the group payload', () => {
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
|
||||
const group = buildGroupRule({
|
||||
rules: [
|
||||
{
|
||||
field: 'title',
|
||||
operator: 'contains',
|
||||
value: 'magic',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([]);
|
||||
|
||||
service.saveShelf({
|
||||
name: 'Magic',
|
||||
icon: 'pi pi-bolt',
|
||||
iconType: 'PRIME_NG',
|
||||
group,
|
||||
isPublic: true,
|
||||
}).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(expect.objectContaining({
|
||||
name: 'Magic',
|
||||
icon: 'pi pi-bolt',
|
||||
iconType: 'PRIME_NG',
|
||||
filterJson: JSON.stringify(group),
|
||||
isPublic: true,
|
||||
}));
|
||||
request.flush(buildMagicShelf({id: 11, name: 'Magic', filterJson: JSON.stringify(group), isPublic: true}));
|
||||
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true});
|
||||
});
|
||||
|
||||
it('invalidates shelf queries after delete', () => {
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([]);
|
||||
|
||||
service.deleteShelf(11).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves/11'));
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true});
|
||||
});
|
||||
|
||||
it('finds shelves by id from the hydrated query state', async () => {
|
||||
const readingShelf = buildMagicShelf({id: 1, name: 'Reading'});
|
||||
const archiveShelf = buildMagicShelf({id: 2, name: 'Archive'});
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([
|
||||
readingShelf,
|
||||
archiveShelf,
|
||||
]);
|
||||
await flushShelvesQuery();
|
||||
|
||||
expect(service.findShelfById(2)).toEqual(archiveShelf);
|
||||
expect(service.findShelfById(999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns zero and logs when a shelf filter contains invalid JSON', async () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([
|
||||
buildMagicShelf({id: 1, filterJson: '{invalid-json'}),
|
||||
]);
|
||||
await flushShelvesQuery();
|
||||
|
||||
expect(service.getBookCountValue(1)).toBe(0);
|
||||
expect(bookService.books).not.toHaveBeenCalled();
|
||||
expect(ruleEvaluatorService.evaluateGroup).not.toHaveBeenCalled();
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Invalid filter JSON', expect.any(SyntaxError));
|
||||
});
|
||||
|
||||
it('counts matching books against the parsed shelf rule group', async () => {
|
||||
const group = buildGroupRule({
|
||||
rules: [
|
||||
{
|
||||
field: 'title',
|
||||
operator: 'contains',
|
||||
value: 'book',
|
||||
},
|
||||
],
|
||||
});
|
||||
const books = [
|
||||
buildBook(1),
|
||||
buildBook(2),
|
||||
buildBook(3),
|
||||
];
|
||||
|
||||
bookService.books.mockReturnValue(books);
|
||||
ruleEvaluatorService.evaluateGroup.mockImplementation((book: Book, parsedGroup: GroupRule, allBooks: Book[]) =>
|
||||
parsedGroup.name === group.name && allBooks === books && book.id !== 2
|
||||
);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([
|
||||
buildMagicShelf({id: 5, filterJson: JSON.stringify(group)}),
|
||||
]);
|
||||
await flushShelvesQuery();
|
||||
|
||||
expect(service.getBookCountValue(5)).toBe(2);
|
||||
expect(ruleEvaluatorService.evaluateGroup).toHaveBeenCalledTimes(3);
|
||||
expect(ruleEvaluatorService.evaluateGroup).toHaveBeenNthCalledWith(1, books[0], group, books);
|
||||
expect(ruleEvaluatorService.evaluateGroup).toHaveBeenNthCalledWith(2, books[1], group, books);
|
||||
expect(ruleEvaluatorService.evaluateGroup).toHaveBeenNthCalledWith(3, books[2], group, books);
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This surface combines routed params, dynamic-dialog inputs, TanStack query
|
||||
// state, and metadata-host book switching, so it needs a routed integration harness.
|
||||
describe.skip('BookMetadataCenterComponent', () => {
|
||||
it('needs a routed dialog harness for tab sync, book switching, and recommendation loading', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
import {SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {ReadingSessionApiService, ReadingSessionResponse} from '../../../../../shared/service/reading-session-api.service';
|
||||
import {BookReadingSessionsComponent} from './book-reading-sessions.component';
|
||||
|
||||
describe('BookReadingSessionsComponent', () => {
|
||||
const getSessionsByBookId = vi.fn();
|
||||
const translate = vi.fn((key: string) => `translated:${key}`);
|
||||
|
||||
function createSession(overrides: Partial<ReadingSessionResponse> = {}): ReadingSessionResponse {
|
||||
return {
|
||||
id: 1,
|
||||
bookId: 7,
|
||||
bookTitle: 'Example',
|
||||
bookType: 'EPUB',
|
||||
startTime: '2026-03-26T10:00:00Z',
|
||||
endTime: '2026-03-26T10:05:30Z',
|
||||
durationSeconds: 330,
|
||||
startProgress: 10,
|
||||
endProgress: 18,
|
||||
progressDelta: 8,
|
||||
startLocation: '15',
|
||||
endLocation: '20',
|
||||
createdAt: '2026-03-26T10:05:30Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
getSessionsByBookId.mockReset();
|
||||
translate.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: ReadingSessionApiService, useValue: {getSessionsByBookId}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads reading sessions on init and exposes the translated page report template', () => {
|
||||
const session = createSession();
|
||||
getSessionsByBookId.mockReturnValue(of({
|
||||
content: [session],
|
||||
page: {totalElements: 1, totalPages: 1, number: 0, size: 100},
|
||||
}));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent());
|
||||
component.bookId = 7;
|
||||
component.ngOnInit();
|
||||
|
||||
expect(getSessionsByBookId).toHaveBeenCalledWith(7, 0, 100);
|
||||
expect(component.sessions).toEqual([session]);
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.pageReportTemplate).toBe('translated:metadata.readingSessions.pageReport');
|
||||
});
|
||||
|
||||
it('reloads when the book id changes after the first change and clears loading on errors', () => {
|
||||
getSessionsByBookId
|
||||
.mockReturnValueOnce(throwError(() => new Error('failed')))
|
||||
.mockReturnValueOnce(of({
|
||||
content: [createSession({id: 2, bookId: 9})],
|
||||
page: {totalElements: 1, totalPages: 1, number: 0, size: 100},
|
||||
}));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent());
|
||||
component.bookId = 7;
|
||||
|
||||
component.loadSessions();
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.sessions).toEqual([]);
|
||||
|
||||
component.bookId = 9;
|
||||
component.ngOnChanges({
|
||||
bookId: new SimpleChange(7, 9, false),
|
||||
});
|
||||
|
||||
expect(getSessionsByBookId).toHaveBeenNthCalledWith(2, 9, 0, 100);
|
||||
expect(component.sessions).toEqual([createSession({id: 2, bookId: 9})]);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores the initial ngOnChanges first-change event', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent());
|
||||
|
||||
component.ngOnChanges({
|
||||
bookId: new SimpleChange(undefined, 7, true),
|
||||
});
|
||||
|
||||
expect(getSessionsByBookId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('formats durations, actual durations, and date helpers consistently', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent());
|
||||
const session = createSession();
|
||||
|
||||
expect(component.formatDuration(3725)).toBe('1h 2m');
|
||||
expect(component.formatDuration(125)).toBe('2m 5s');
|
||||
expect(component.formatDuration(45)).toBe('45s');
|
||||
expect(component.calculateActualDuration(session)).toBe(330);
|
||||
expect(component.getActualDuration(session)).toBe('5m 30s');
|
||||
expect(component.getActualDuration(createSession({durationSeconds: 300}))).toBe('5m 30s');
|
||||
expect(component.formatDate(session.startTime)).toBe(new Date(session.startTime).toLocaleString());
|
||||
expect(component.formatSessionDate(session.startTime)).toBe(new Date(session.startTime).toLocaleDateString(undefined, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric'
|
||||
}));
|
||||
expect(component.formatTime(session.startTime)).toBe(new Date(session.startTime).toLocaleTimeString(undefined, {
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
}));
|
||||
});
|
||||
|
||||
it('maps book types, progress deltas, and location formatting branches', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent());
|
||||
const pageSession = createSession();
|
||||
const audioSession = createSession({bookType: 'AUDIOBOOK', startLocation: '00:01:00', endLocation: '00:02:00'});
|
||||
|
||||
expect(component.getBookTypeIcon('PDF')).toBe('pi pi-file-pdf');
|
||||
expect(component.getBookTypeIcon('CBR')).toBe('pi pi-images');
|
||||
expect(component.getBookTypeIcon('UNKNOWN')).toBe('pi pi-file');
|
||||
expect(component.formatBookType('AUDIOBOOK')).toBe('translated:metadata.readingSessions.audio');
|
||||
expect(component.formatBookType('EPUB')).toBe('EPUB');
|
||||
|
||||
expect(component.getProgressColor(3)).toBe('success');
|
||||
expect(component.getProgressColor(-1)).toBe('danger');
|
||||
expect(component.getProgressColor(0)).toBe('secondary');
|
||||
expect(component.getProgressDeltaClass(3)).toBe('progress-positive');
|
||||
expect(component.getProgressDeltaClass(-1)).toBe('progress-negative');
|
||||
expect(component.getProgressDeltaClass(0)).toBe('progress-neutral');
|
||||
expect(component.getProgressDeltaIcon(3)).toBe('pi pi-arrow-up');
|
||||
expect(component.getProgressDeltaIcon(-1)).toBe('pi pi-arrow-down');
|
||||
expect(component.getProgressDeltaIcon(0)).toBe('pi pi-minus');
|
||||
|
||||
expect(component.isPageNumber('15')).toBe(true);
|
||||
expect(component.isPageNumber('chapter-1')).toBe(false);
|
||||
expect(component.isPageNumber(undefined)).toBe(false);
|
||||
expect(component.formatLocation(pageSession)).toBe('translated:metadata.readingSessions.page 15 → 20');
|
||||
expect(component.formatLocation(audioSession)).toBe('00:01:00 → 00:02:00');
|
||||
expect(component.formatLocation(createSession({startLocation: undefined, endLocation: undefined}))).toBe('-');
|
||||
expect(component.formatLocation(createSession({startLocation: 'chapter-1', endLocation: 'chapter-2'}))).toBe('-');
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): The metadata editor requires a high-fidelity form harness for PrimeNG
|
||||
// upload, autocomplete, drag-drop author ordering, router navigation, and autosave flows.
|
||||
describe.skip('MetadataEditorComponent', () => {
|
||||
it('needs an integration harness for form population, upload, save, and navigation branches', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {CdkDragDrop} from '@angular/cdk/drag-drop';
|
||||
import {AutoCompleteSelectEvent} from 'primeng/autocomplete';
|
||||
|
||||
import {Book, BookMetadata} from '../../../../book/model/book.model';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
import {BookMetadataManageService} from '../../../../book/service/book-metadata-manage.service';
|
||||
import {AppSettings} from '../../../../../shared/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {MetadataFormBuilder} from '../../../../../shared/metadata';
|
||||
import {MetadataUtilsService} from '../../../../../shared/metadata/metadata-utils.service';
|
||||
import {MetadataPickerComponent} from './metadata-picker.component';
|
||||
|
||||
describe('MetadataPickerComponent', () => {
|
||||
const uniqueMetadata = signal({
|
||||
authors: ['Alice', 'Bob'],
|
||||
categories: ['Fantasy', 'History'],
|
||||
moods: ['Hopeful'],
|
||||
tags: ['Epic'],
|
||||
publishers: ['Orbit'],
|
||||
series: ['Saga'],
|
||||
});
|
||||
const appSettings = signal<AppSettings | null>(null);
|
||||
const updateBookMetadata = vi.fn(() => of(void 0));
|
||||
const uploadAudiobookCoverFromUrl = vi.fn(() => of(void 0));
|
||||
const supportsDualCovers = vi.fn(() => true);
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string, params?: Record<string, unknown>) => params?.['field'] ? `${key}:${params['field']}` : key);
|
||||
const getThumbnailUrl = vi.fn((bookId: number, updatedOn?: string) => `thumb:${bookId}:${updatedOn ?? 'none'}`);
|
||||
const getCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `cover:${bookId}:${updatedOn ?? 'none'}`);
|
||||
const getAudiobookCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `audio-cover:${bookId}:${updatedOn ?? 'none'}`);
|
||||
|
||||
function createMetadata(overrides: Partial<BookMetadata> = {}): BookMetadata {
|
||||
return {
|
||||
bookId: 21,
|
||||
title: 'Original Title',
|
||||
subtitle: 'Original Subtitle',
|
||||
authors: ['Alice'],
|
||||
categories: ['Fantasy'],
|
||||
description: 'Original description',
|
||||
provider: 'googleBooks',
|
||||
coverUpdatedOn: '2026-03-26',
|
||||
titleLocked: true,
|
||||
comicMetadata: {
|
||||
issueNumber: '1',
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBook(metadata: Partial<BookMetadata> = {}, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id: 21,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: createMetadata(metadata),
|
||||
primaryFile: {id: 1, bookId: 21, bookType: 'EPUB'},
|
||||
alternativeFormats: [],
|
||||
supplementaryFiles: [],
|
||||
isPhysical: false,
|
||||
...overrides,
|
||||
} as Book;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
uniqueMetadata.set({
|
||||
authors: ['Alice', 'Bob'],
|
||||
categories: ['Fantasy', 'History'],
|
||||
moods: ['Hopeful'],
|
||||
tags: ['Epic'],
|
||||
publishers: ['Orbit'],
|
||||
series: ['Saga'],
|
||||
});
|
||||
appSettings.set(null);
|
||||
updateBookMetadata.mockClear();
|
||||
uploadAudiobookCoverFromUrl.mockClear();
|
||||
supportsDualCovers.mockClear();
|
||||
messageAdd.mockClear();
|
||||
translate.mockClear();
|
||||
getThumbnailUrl.mockClear();
|
||||
getCoverUrl.mockClear();
|
||||
getAudiobookCoverUrl.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
MetadataFormBuilder,
|
||||
MetadataUtilsService,
|
||||
{provide: AppSettingsService, useValue: {appSettings}},
|
||||
{provide: BookService, useValue: {uniqueMetadata}},
|
||||
{
|
||||
provide: BookMetadataManageService,
|
||||
useValue: {updateBookMetadata, uploadAudiobookCoverFromUrl, supportsDualCovers},
|
||||
},
|
||||
{
|
||||
provide: UrlHelperService,
|
||||
useValue: {getThumbnailUrl, getCoverUrl, getAudiobookCoverUrl},
|
||||
},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('syncs provider field visibility from app settings and filters metadata suggestions', () => {
|
||||
appSettings.set({
|
||||
metadataProviderSpecificFields: {
|
||||
googleId: true,
|
||||
audibleId: true,
|
||||
amazonRating: false,
|
||||
},
|
||||
} as AppSettings);
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.metadataProviderFields.map(field => field.controlName)).toContain('googleId');
|
||||
expect(component.metadataProviderFields.map(field => field.controlName)).toContain('audibleId');
|
||||
expect(component.metadataProviderFields.map(field => field.controlName)).not.toContain('amazonRating');
|
||||
|
||||
component.filterItems({query: 'fan'}, 'categories');
|
||||
expect(component.getFiltered('categories')).toEqual(['Fantasy']);
|
||||
expect(component.getFiltered('missing')).toEqual([]);
|
||||
});
|
||||
|
||||
it('patches book metadata into the form and resets review state when a new book arrives', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.reviewMode = true;
|
||||
component.copiedFields = {title: true};
|
||||
component.savedFields = {title: true};
|
||||
component.hoveredFields = {title: true};
|
||||
component.fetchedMetadata = createMetadata({provider: 'comicvine'});
|
||||
|
||||
component.book = createBook();
|
||||
|
||||
expect(component.currentBookId).toBe(21);
|
||||
expect(component.metadataForm.get('title')?.value).toBe('Original Title');
|
||||
expect(component.metadataForm.get('authors')?.value).toEqual(['Alice']);
|
||||
expect(component.metadataForm.get('title')?.disabled).toBe(true);
|
||||
expect(component.originalMetadata.thumbnailUrl).toBe('thumb:21:2026-03-26');
|
||||
expect(component.comicSectionExpanded).toBe(true);
|
||||
expect(component.copiedFields).toEqual({});
|
||||
expect(component.savedFields).toEqual({});
|
||||
expect(component.hoveredFields).toEqual({});
|
||||
});
|
||||
|
||||
it('handles author and array autocomplete helpers without duplicating values', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.book = createBook();
|
||||
component.metadataForm.get('authors')?.setValue(['Alice', 'Bob']);
|
||||
|
||||
component.dropAuthor({previousIndex: 1, currentIndex: 0} as CdkDragDrop<string[]>);
|
||||
expect(component.metadataForm.get('authors')?.value).toEqual(['Bob', 'Alice']);
|
||||
|
||||
component.removeAuthor(1);
|
||||
expect(component.metadataForm.get('authors')?.value).toEqual(['Bob']);
|
||||
|
||||
component.authorInputValue = 'Cara';
|
||||
component.onAuthorInputKeyUp({key: 'Enter'} as KeyboardEvent);
|
||||
expect(component.metadataForm.get('authors')?.value).toEqual(['Bob', 'Cara']);
|
||||
expect(component.authorInputValue).toBe('');
|
||||
|
||||
component.onAutoCompleteSelect('categories', {
|
||||
value: 'Fantasy',
|
||||
originalEvent: {target: {value: 'Fantasy'}},
|
||||
} as unknown as AutoCompleteSelectEvent);
|
||||
component.onAutoCompleteKeyUp('categories', {
|
||||
key: 'Enter',
|
||||
target: {value: 'History'},
|
||||
} as unknown as KeyboardEvent);
|
||||
|
||||
expect(component.metadataForm.get('categories')?.value).toEqual(['Fantasy', 'History']);
|
||||
});
|
||||
|
||||
it('copies fetched values, respects locked fields, and resets fields back to the original metadata', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.book = createBook();
|
||||
component.fetchedMetadata = createMetadata({
|
||||
title: 'Fetched Title',
|
||||
provider: 'Audible',
|
||||
thumbnailUrl: 'https://covers.example/audiobook.jpg',
|
||||
comicMetadata: {issueNumber: '7'},
|
||||
});
|
||||
|
||||
component.copyFetchedToCurrent('title');
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'metadata.picker.toast.actionBlockedSummary',
|
||||
detail: 'metadata.picker.toast.fieldLockedDetail:title',
|
||||
});
|
||||
|
||||
component.metadataForm.get('titleLocked')?.setValue(false);
|
||||
component.metadataForm.get('title')?.enable();
|
||||
component.copyFetchedToCurrent('title');
|
||||
expect(component.metadataForm.get('title')?.value).toBe('Fetched Title');
|
||||
expect(component.isValueCopied('title')).toBe(true);
|
||||
|
||||
component.copyFetchedToCurrent('audiobookThumbnailUrl');
|
||||
expect(component.metadataForm.get('audiobookThumbnailUrl')?.value).toBe('https://covers.example/audiobook.jpg');
|
||||
expect(component.isValueCopied('audiobookThumbnailUrl')).toBe(true);
|
||||
|
||||
component.metadataForm.get('comicIssueNumberLocked')?.setValue(true);
|
||||
component.copyFetchedToCurrent('comicIssueNumber');
|
||||
expect(messageAdd).toHaveBeenLastCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'metadata.picker.toast.actionBlockedSummary',
|
||||
detail: 'metadata.picker.toast.fieldLockedDetail:Issue #',
|
||||
});
|
||||
|
||||
component.resetField('title');
|
||||
expect(component.metadataForm.get('title')?.value).toBe('Original Title');
|
||||
expect(component.isValueCopied('title')).toBe(false);
|
||||
});
|
||||
|
||||
it('saves metadata, uploads audible covers when needed, and toggles lock states', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.fetchedMetadata = createMetadata({
|
||||
provider: 'Audible',
|
||||
thumbnailUrl: 'https://covers.example/audiobook.jpg',
|
||||
});
|
||||
component.book = createBook();
|
||||
component.copiedFields = {title: true, audiobookThumbnailUrl: true};
|
||||
component.metadataForm.get('titleLocked')?.setValue(false);
|
||||
component.metadataForm.get('title')?.enable();
|
||||
component.metadataForm.get('title')?.setValue('Updated Title');
|
||||
|
||||
component.onSave();
|
||||
|
||||
expect(updateBookMetadata).toHaveBeenCalledWith(21, expect.objectContaining({
|
||||
metadata: expect.objectContaining({title: 'Updated Title'}),
|
||||
clearFlags: expect.any(Object),
|
||||
}), false, 'REPLACE_WHEN_PROVIDED');
|
||||
expect(uploadAudiobookCoverFromUrl).toHaveBeenCalledWith(21, 'https://covers.example/audiobook.jpg');
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(component.isValueSaved('title')).toBe(true);
|
||||
expect(component.isValueSaved('audiobookThumbnailUrl')).toBe(true);
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'metadata.picker.toast.successSummary',
|
||||
detail: 'metadata.picker.toast.metadataUpdated',
|
||||
});
|
||||
|
||||
component.toggleLock('thumbnailUrl');
|
||||
expect(component.metadataForm.get('coverLocked')?.value).toBe(true);
|
||||
expect(component.metadataForm.get('thumbnailUrl')?.disabled).toBe(true);
|
||||
|
||||
component.lockAll();
|
||||
component.unlockAll();
|
||||
|
||||
expect(updateBookMetadata).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it('covers hover state, back navigation, dual-cover helpers, and comic visibility helpers', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
const goBackEmit = vi.spyOn(component.goBack, 'emit');
|
||||
const book = createBook({}, {
|
||||
isPhysical: true,
|
||||
primaryFile: undefined,
|
||||
alternativeFormats: [{id: 2, bookId: 21, bookType: 'AUDIOBOOK'}],
|
||||
});
|
||||
|
||||
component.fetchedMetadata = createMetadata({
|
||||
provider: 'comicvine',
|
||||
narrator: 'Narrator',
|
||||
comicMetadata: {issueNumber: '7'},
|
||||
});
|
||||
component.book = book;
|
||||
component.copiedFields = {title: true};
|
||||
component.savedFields = {title: false};
|
||||
|
||||
component.onMouseEnter('title');
|
||||
expect(component.hoveredFields['title']).toBe(true);
|
||||
|
||||
component.onMouseLeave('title');
|
||||
expect(component.hoveredFields['title']).toBe(false);
|
||||
|
||||
component.goBackClick();
|
||||
expect(goBackEmit).toHaveBeenCalledWith(true);
|
||||
|
||||
expect(component.isAudibleProvider()).toBe(false);
|
||||
component.fetchedMetadata = createMetadata({provider: 'Audible', narrator: 'Narrator', comicMetadata: {issueNumber: '7'}});
|
||||
expect(component.isAudibleProvider()).toBe(true);
|
||||
expect(component.getFetchedAudiobookValue('narrator')).toBe('Narrator');
|
||||
expect(component.getFetchedComicValue('issueNumber')).toBe('7');
|
||||
|
||||
expect(component.hasEbookFormat(book)).toBe(true);
|
||||
expect(component.hasAudiobookFormat(book)).toBe(true);
|
||||
expect(component.supportsDualCovers(book)).toBe(true);
|
||||
expect(component.hasAnyFetchedComicData()).toBe(true);
|
||||
expect(component.hasAnyCurrentComicData()).toBe(true);
|
||||
expect(component.shouldShowComicSection()).toBe(true);
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): Search orchestration depends on reactive form state, provider fan-out requests,
|
||||
// and metadata picker integration that should be covered through a component harness.
|
||||
describe.skip('MetadataSearcherComponent', () => {
|
||||
it('needs an integration harness for provider filtering, auto-search, and detail-loading flows', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This tab surface coordinates nested review, notes, reading-session, and
|
||||
// audiobook child components, so it needs an integration harness around real tab changes.
|
||||
describe.skip('MetadataTabsComponent', () => {
|
||||
it('needs a tab harness for chapter loading and file action emission branches', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ConfirmationService, MessageService, MenuItem} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {Book, BookFile, BookMetadata, BookRecommendation, ReadStatus} from '../../../../book/model/book.model';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
import {BookFileService} from '../../../../book/service/book-file.service';
|
||||
import {AppSettings} from '../../../../../shared/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
|
||||
import {LibraryService} from '../../../../book/service/library.service';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {AuthorService} from '../../../../author-browser/service/author.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
||||
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service';
|
||||
import {MetadataViewerComponent} from './metadata-viewer.component';
|
||||
|
||||
interface CurrentUser {
|
||||
permissions?: {
|
||||
canManageLibrary?: boolean;
|
||||
canUpload?: boolean;
|
||||
canEmailBook?: boolean;
|
||||
canDeleteBook?: boolean;
|
||||
admin?: boolean;
|
||||
};
|
||||
userSettings?: {
|
||||
metadataCenterViewMode?: 'route' | 'dialog';
|
||||
};
|
||||
}
|
||||
|
||||
interface ConfirmationLike {
|
||||
message?: string;
|
||||
header?: string;
|
||||
accept?: () => void;
|
||||
}
|
||||
|
||||
describe('MetadataViewerComponent', () => {
|
||||
const currentUser = signal<CurrentUser | null>(null);
|
||||
const appSettings = signal<AppSettings | null>(null);
|
||||
const navigationState = signal(false);
|
||||
const canNavigatePrevious = signal(false);
|
||||
const canNavigateNext = signal(false);
|
||||
const currentPosition = signal<{ current: number; total: number } | null>(null);
|
||||
|
||||
const readBook = vi.fn();
|
||||
const togglePhysicalFlag = vi.fn(() => of(void 0));
|
||||
const deleteBooks = vi.fn(() => of(void 0));
|
||||
const updateDateFinished = vi.fn(() => of(void 0));
|
||||
const updateBookReadStatus = vi.fn(() => of(void 0));
|
||||
const resetProgress = vi.fn(() => of(void 0));
|
||||
const updatePersonalRating = vi.fn(() => of(void 0));
|
||||
const resetPersonalRating = vi.fn(() => of(void 0));
|
||||
const getBooksInSeries = vi.fn(() => of([] as Book[]));
|
||||
const findBookById = vi.fn();
|
||||
|
||||
const downloadFile = vi.fn();
|
||||
const downloadAdditionalFile = vi.fn();
|
||||
const downloadAllFiles = vi.fn();
|
||||
const deleteAdditionalFile = vi.fn(() => of(void 0));
|
||||
const deleteBookFile = vi.fn(() => of(void 0));
|
||||
const detachBookFile = vi.fn(() => of(void 0));
|
||||
|
||||
const openAdditionalFileUploaderDialog = vi.fn();
|
||||
const openCustomSendDialog = vi.fn();
|
||||
const openBookFileAttacherDialog = vi.fn();
|
||||
const openFileMoverDialog = vi.fn();
|
||||
const openShelfAssignerDialog = vi.fn();
|
||||
|
||||
const emailBookQuick = vi.fn(() => of(void 0));
|
||||
const refreshMetadataTask = vi.fn(() => of(void 0));
|
||||
const getAuthorByName = vi.fn(() => of({id: 41}));
|
||||
|
||||
const findLibraryById = vi.fn(() => ({allowedFormats: ['PDF', 'EPUB']}));
|
||||
const switchBook = vi.fn();
|
||||
const updateCurrentBook = vi.fn();
|
||||
const previousBookId = vi.fn();
|
||||
const nextBookId = vi.fn();
|
||||
const routerNavigate = vi.fn(() => Promise.resolve(true));
|
||||
|
||||
let lastConfirmation: ConfirmationLike | null = null;
|
||||
const confirm = vi.fn((confirmation: ConfirmationLike) => {
|
||||
lastConfirmation = confirmation;
|
||||
});
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string, params?: Record<string, unknown>) => {
|
||||
if (!params) {
|
||||
return key;
|
||||
}
|
||||
return `${key}:${Object.entries(params).map(([paramKey, value]) => `${paramKey}=${value}`).join(',')}`;
|
||||
});
|
||||
const getCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `cover:${bookId}:${updatedOn ?? 'none'}`);
|
||||
const getAudiobookCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `audio:${bookId}:${updatedOn ?? 'none'}`);
|
||||
const getThumbnailUrl = vi.fn((bookId: number, updatedOn?: string) => `thumb:${bookId}:${updatedOn ?? 'none'}`);
|
||||
|
||||
function createFile(
|
||||
id: number,
|
||||
overrides: Partial<BookFile> = {},
|
||||
): BookFile {
|
||||
return {
|
||||
id,
|
||||
bookId: 21,
|
||||
fileName: `file-${id}.epub`,
|
||||
filePath: `/books/file-${id}.epub`,
|
||||
fileSizeKb: 100,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createMetadata(overrides: Partial<BookMetadata> = {}): BookMetadata {
|
||||
return {
|
||||
bookId: 21,
|
||||
title: 'Original Title',
|
||||
authors: ['Alice'],
|
||||
coverUpdatedOn: '2026-03-26',
|
||||
audiobookCoverUpdatedOn: '2026-03-26',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createBook(
|
||||
overrides: Partial<Book> = {},
|
||||
metadataOverrides: Partial<BookMetadata> = {},
|
||||
): Book {
|
||||
return {
|
||||
id: 21,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: createMetadata(metadataOverrides),
|
||||
primaryFile: createFile(1, {bookId: 21, bookType: 'EPUB'}),
|
||||
alternativeFormats: [],
|
||||
supplementaryFiles: [],
|
||||
isPhysical: false,
|
||||
...overrides,
|
||||
} as Book;
|
||||
}
|
||||
|
||||
function createComponent(): MetadataViewerComponent {
|
||||
return TestBed.runInInjectionContext(() => new MetadataViewerComponent());
|
||||
}
|
||||
|
||||
function runMenuCommand(command: MenuItem['command'] | undefined): void {
|
||||
(command as (() => void) | undefined)?.();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
currentUser.set(null);
|
||||
appSettings.set(null);
|
||||
navigationState.set(false);
|
||||
canNavigatePrevious.set(false);
|
||||
canNavigateNext.set(false);
|
||||
currentPosition.set(null);
|
||||
|
||||
readBook.mockClear();
|
||||
togglePhysicalFlag.mockClear();
|
||||
deleteBooks.mockClear();
|
||||
updateDateFinished.mockClear();
|
||||
updateBookReadStatus.mockClear();
|
||||
resetProgress.mockClear();
|
||||
updatePersonalRating.mockClear();
|
||||
resetPersonalRating.mockClear();
|
||||
getBooksInSeries.mockClear();
|
||||
findBookById.mockClear();
|
||||
|
||||
downloadFile.mockClear();
|
||||
downloadAdditionalFile.mockClear();
|
||||
downloadAllFiles.mockClear();
|
||||
deleteAdditionalFile.mockClear();
|
||||
deleteBookFile.mockClear();
|
||||
detachBookFile.mockClear();
|
||||
|
||||
openAdditionalFileUploaderDialog.mockClear();
|
||||
openCustomSendDialog.mockClear();
|
||||
openBookFileAttacherDialog.mockClear();
|
||||
openFileMoverDialog.mockClear();
|
||||
openShelfAssignerDialog.mockClear();
|
||||
|
||||
emailBookQuick.mockClear();
|
||||
refreshMetadataTask.mockClear();
|
||||
getAuthorByName.mockClear();
|
||||
|
||||
findLibraryById.mockClear();
|
||||
switchBook.mockClear();
|
||||
updateCurrentBook.mockClear();
|
||||
previousBookId.mockClear();
|
||||
nextBookId.mockClear();
|
||||
routerNavigate.mockClear();
|
||||
|
||||
confirm.mockClear();
|
||||
messageAdd.mockClear();
|
||||
translate.mockClear();
|
||||
getCoverUrl.mockClear();
|
||||
getAudiobookCoverUrl.mockClear();
|
||||
getThumbnailUrl.mockClear();
|
||||
lastConfirmation = null;
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
{provide: LibraryService, useValue: {findLibraryById}},
|
||||
{
|
||||
provide: BookDialogHelperService,
|
||||
useValue: {
|
||||
openAdditionalFileUploaderDialog,
|
||||
openCustomSendDialog,
|
||||
openBookFileAttacherDialog,
|
||||
openFileMoverDialog,
|
||||
openShelfAssignerDialog,
|
||||
},
|
||||
},
|
||||
{provide: EmailService, useValue: {emailBookQuick}},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{
|
||||
provide: BookService,
|
||||
useValue: {
|
||||
readBook,
|
||||
togglePhysicalFlag,
|
||||
deleteBooks,
|
||||
updateDateFinished,
|
||||
updateBookReadStatus,
|
||||
resetProgress,
|
||||
updatePersonalRating,
|
||||
resetPersonalRating,
|
||||
getBooksInSeries,
|
||||
findBookById,
|
||||
},
|
||||
},
|
||||
{provide: BookFileService, useValue: {downloadFile, downloadAdditionalFile, downloadAllFiles, deleteAdditionalFile, deleteBookFile, detachBookFile}},
|
||||
{provide: TaskHelperService, useValue: {refreshMetadataTask}},
|
||||
{provide: AuthorService, useValue: {getAuthorByName}},
|
||||
{provide: UrlHelperService, useValue: {getCoverUrl, getAudiobookCoverUrl, getThumbnailUrl}},
|
||||
{provide: UserService, useValue: {currentUser}},
|
||||
{provide: AppSettingsService, useValue: {appSettings}},
|
||||
{provide: ConfirmationService, useValue: {confirm}},
|
||||
{provide: Router, useValue: {navigate: routerNavigate}},
|
||||
{
|
||||
provide: BookNavigationService,
|
||||
useValue: {
|
||||
navigationState,
|
||||
canNavigatePrevious,
|
||||
canNavigateNext,
|
||||
currentPosition,
|
||||
previousBookId,
|
||||
nextBookId,
|
||||
updateCurrentBook,
|
||||
},
|
||||
},
|
||||
{provide: BookMetadataHostService, useValue: {switchBook}},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('filters series recommendations and builds the read, download, and other menus from the current book', () => {
|
||||
const component = createComponent();
|
||||
const seriesBooks = [
|
||||
{id: 8, metadata: {seriesNumber: 2}},
|
||||
{id: 4, metadata: {seriesNumber: 1}},
|
||||
] as Book[];
|
||||
getBooksInSeries.mockReturnValueOnce(of(seriesBooks as Book[]));
|
||||
|
||||
const recommendedBooks: BookRecommendation[] = [
|
||||
{book: {id: 4} as Book, similarityScore: 0.99},
|
||||
{book: {id: 17} as Book, similarityScore: 0.87},
|
||||
];
|
||||
|
||||
component.recommendedBooks = recommendedBooks;
|
||||
const richBook = createBook(
|
||||
{
|
||||
id: 21,
|
||||
primaryFile: createFile(1, {bookId: 21, bookType: 'EPUB', fileName: 'main.epub', filePath: '/books/main.epub', fileSizeKb: 2048}),
|
||||
alternativeFormats: [
|
||||
createFile(2, {bookId: 21, bookType: 'EPUB', fileName: 'alt.epub', filePath: '/books/alt.epub', fileSizeKb: 1024}),
|
||||
createFile(3, {bookId: 21, bookType: 'PDF', fileName: 'art.pdf', filePath: '/books/art.pdf', fileSizeKb: 5120}),
|
||||
],
|
||||
supplementaryFiles: [
|
||||
createFile(4, {bookId: 21, fileName: 'appendix.txt', filePath: '/books/appendix.txt', fileSizeKb: 12}),
|
||||
],
|
||||
},
|
||||
{
|
||||
bookId: 21,
|
||||
seriesName: 'Series One',
|
||||
seriesNumber: 3,
|
||||
}
|
||||
);
|
||||
findBookById.mockReturnValue(richBook);
|
||||
|
||||
currentUser.set({
|
||||
permissions: {
|
||||
canManageLibrary: true,
|
||||
canUpload: true,
|
||||
canEmailBook: true,
|
||||
canDeleteBook: true,
|
||||
},
|
||||
userSettings: {
|
||||
metadataCenterViewMode: 'route',
|
||||
},
|
||||
});
|
||||
appSettings.set({
|
||||
diskType: 'LOCAL',
|
||||
metadataProviderSettings: {
|
||||
amazon: {domain: 'co.uk'},
|
||||
},
|
||||
} as AppSettings);
|
||||
|
||||
component.book = richBook;
|
||||
|
||||
expect(component.bookInSeries.map(book => book.id)).toEqual([4, 8]);
|
||||
expect(component.recommendedBooks.map(book => book.book.id)).toEqual([17]);
|
||||
|
||||
const readItems = component.readMenuItems();
|
||||
expect(readItems.map(item => item.separator ? 'separator' : item.label)).toEqual([
|
||||
'metadata.viewer.menuStreamingReader',
|
||||
'separator',
|
||||
'EPUB',
|
||||
'PDF',
|
||||
]);
|
||||
expect(readItems[0].command).toBeDefined();
|
||||
runMenuCommand(readItems[0].command);
|
||||
expect(readBook).toHaveBeenCalledWith(21, 'epub-streaming', undefined);
|
||||
runMenuCommand(readItems[2].items?.[0].command);
|
||||
expect(readBook).toHaveBeenLastCalledWith(21, undefined, 'EPUB');
|
||||
|
||||
const downloadItems = component.downloadMenuItems();
|
||||
expect(downloadItems.some(item => item.separator)).toBe(true);
|
||||
expect(downloadItems[0].label).toContain('EPUB ·');
|
||||
expect(downloadItems[3].label).toContain('appendix.txt');
|
||||
runMenuCommand(downloadItems[0].command);
|
||||
expect(downloadAdditionalFile).toHaveBeenCalledWith(richBook, 2);
|
||||
runMenuCommand(downloadItems[3].command);
|
||||
expect(downloadAdditionalFile).toHaveBeenCalledWith(richBook, 4);
|
||||
|
||||
const otherItems = component.otherItems();
|
||||
expect(otherItems.map(item => item.separator ? 'separator' : item.label)).toEqual([
|
||||
'metadata.viewer.menuShelf',
|
||||
'metadata.viewer.menuMarkPhysical',
|
||||
'metadata.viewer.menuUploadFile',
|
||||
'metadata.viewer.menuOrganizeFiles',
|
||||
'metadata.viewer.menuSendBook',
|
||||
'metadata.viewer.menuDeleteFileFormats',
|
||||
'metadata.viewer.menuDeleteSupplementaryFiles',
|
||||
'metadata.viewer.menuDeleteBookAllFiles',
|
||||
]);
|
||||
|
||||
runMenuCommand(otherItems[0].command);
|
||||
expect(openShelfAssignerDialog).toHaveBeenCalledWith(richBook, null);
|
||||
|
||||
runMenuCommand(otherItems[1].command);
|
||||
expect(togglePhysicalFlag).toHaveBeenCalledWith(21, true);
|
||||
|
||||
runMenuCommand(otherItems[2].command);
|
||||
expect(openAdditionalFileUploaderDialog).toHaveBeenCalledWith(richBook);
|
||||
|
||||
runMenuCommand(otherItems[3].command);
|
||||
expect(openFileMoverDialog).toHaveBeenCalledWith(new Set([21]));
|
||||
|
||||
const sendBookItem = otherItems[4];
|
||||
runMenuCommand(sendBookItem.items?.[0].command);
|
||||
expect(emailBookQuick).toHaveBeenCalledWith(21);
|
||||
runMenuCommand(sendBookItem.items?.[1].command);
|
||||
expect(openCustomSendDialog).toHaveBeenCalledWith(richBook);
|
||||
|
||||
const deleteFormatItems = otherItems[5].items ?? [];
|
||||
runMenuCommand(deleteFormatItems[0].command);
|
||||
expect(confirm).toHaveBeenCalled();
|
||||
|
||||
const deleteSupplementaryItems = otherItems[6].items ?? [];
|
||||
runMenuCommand(deleteSupplementaryItems[0].command);
|
||||
expect(confirm).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('chooses confirmation copy for file deletion branches and runs the accept callbacks', () => {
|
||||
const component = createComponent();
|
||||
const book = createBook();
|
||||
|
||||
component.deleteBookFile(book, 1, 'primary.epub', true, true);
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'metadata.viewer.confirm.deleteOnlyFormatMessage:fileName=primary.epub',
|
||||
header: 'metadata.viewer.confirm.deleteOnlyFormatHeader',
|
||||
});
|
||||
|
||||
component.deleteBookFile(book, 2, 'primary.epub', true, false);
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'metadata.viewer.confirm.deletePrimaryFormatMessage:fileName=primary.epub',
|
||||
header: 'metadata.viewer.confirm.deletePrimaryFormatHeader',
|
||||
});
|
||||
|
||||
component.deleteBookFile(book, 3, 'alt.pdf', false, false);
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'metadata.viewer.confirm.deleteAltFormatMessage:fileName=alt.pdf',
|
||||
header: 'metadata.viewer.confirm.deleteAltFormatHeader',
|
||||
});
|
||||
lastConfirmation?.accept?.();
|
||||
expect(deleteBookFile).toHaveBeenCalledWith(21, 3, false);
|
||||
expect(messageAdd).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'metadata.viewer.toast.deleteFormatSuccessSummary',
|
||||
}));
|
||||
|
||||
deleteAdditionalFile.mockReturnValueOnce(throwError(() => new Error('boom')));
|
||||
component.deleteAdditionalFile(21, 9, 'appendix.txt');
|
||||
expect(lastConfirmation).toMatchObject({
|
||||
message: 'metadata.viewer.confirm.deleteSupplementaryMessage:fileName=appendix.txt',
|
||||
header: 'metadata.viewer.confirm.deleteSupplementaryHeader',
|
||||
});
|
||||
lastConfirmation?.accept?.();
|
||||
expect(deleteAdditionalFile).toHaveBeenCalledWith(21, 9);
|
||||
expect(messageAdd).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 'metadata.viewer.toast.deleteSupplementaryErrorSummary',
|
||||
}));
|
||||
});
|
||||
|
||||
it('navigates and formats helper branches for read states, file metadata, and location helpers', () => {
|
||||
const component = createComponent();
|
||||
const viewer = component as unknown as {
|
||||
metadataCenterViewMode: 'route' | 'dialog';
|
||||
};
|
||||
|
||||
previousBookId.mockReturnValue(12);
|
||||
nextBookId.mockReturnValue(27);
|
||||
|
||||
viewer.metadataCenterViewMode = 'route';
|
||||
component.navigatePrevious();
|
||||
expect(updateCurrentBook).toHaveBeenCalledWith(12);
|
||||
expect(routerNavigate).toHaveBeenCalledWith(['/book', 12], {queryParams: {tab: 'view'}});
|
||||
|
||||
viewer.metadataCenterViewMode = 'dialog';
|
||||
component.navigateNext();
|
||||
expect(updateCurrentBook).toHaveBeenLastCalledWith(27);
|
||||
expect(switchBook).toHaveBeenCalledWith(27);
|
||||
|
||||
const audiobookBook = createBook({primaryFile: createFile(1, {bookType: 'AUDIOBOOK'})});
|
||||
component.selectedReadStatus = ReadStatus.READING;
|
||||
expect(component.isInProgressStatus()).toBe(true);
|
||||
expect(component.getReadButtonLabel(audiobookBook)).toBe('metadata.viewer.continueBtn');
|
||||
expect(component.getReadButtonIcon(audiobookBook)).toBe('pi pi-play');
|
||||
|
||||
component.selectedReadStatus = ReadStatus.UNREAD;
|
||||
expect(component.isInProgressStatus()).toBe(false);
|
||||
expect(component.getReadButtonLabel(audiobookBook)).toBe('metadata.viewer.playBtn');
|
||||
expect(component.getReadButtonLabel(createBook())).toBe('metadata.viewer.readBtn');
|
||||
expect(component.getReadButtonIcon(createBook())).toBe('pi pi-book');
|
||||
|
||||
expect(component.formatFileSize(null)).toBe('-');
|
||||
expect(component.formatFileSize({fileSizeKb: 1536})).toBe('1.50 MB');
|
||||
expect(component.truncateFileName('plain-name-without-extension', 12)).toBe('plain-nam...');
|
||||
expect(component.truncateFileName('very-long-name.epub', 12)).toBe('very....epub');
|
||||
expect(component.getDisplayFormat(createFile(9, {extension: 'pdf'}))).toBe('PDF');
|
||||
expect(component.getDisplayFormat(createFile(10, {filePath: '/books/chapter.cbx'}))).toBe('CBX');
|
||||
expect(component.getUniqueAlternativeFormats(createBook({
|
||||
primaryFile: createFile(1, {bookType: 'EPUB', extension: 'epub'}),
|
||||
alternativeFormats: [
|
||||
createFile(2, {bookType: 'EPUB', extension: 'epub'}),
|
||||
createFile(3, {bookType: 'PDF', extension: 'pdf'}),
|
||||
createFile(4, {bookType: 'PDF', extension: 'pdf'}),
|
||||
],
|
||||
}))).toEqual(['PDF']);
|
||||
expect(component.getFileIcon(null)).toBe('pi pi-file');
|
||||
expect(component.getFileIcon('pdf')).toBe('pi pi-file-pdf');
|
||||
expect(component.getFileIcon('audiobook')).toBe('pi pi-headphones');
|
||||
expect(component.getFileTypeBgColor('PDF')).toBe('var(--book-type-pdf-color, var(--p-gray-500))');
|
||||
expect(component.getStarColorScaled(null)).toBe('rgb(203, 213, 225)');
|
||||
expect(component.getStarColorScaled(5)).toBe('rgb(34, 197, 94)');
|
||||
expect(component.getRatingPercent(4.5)).toBe(90);
|
||||
expect(component.getRatingTooltip(createBook({metadata: createMetadata({amazonRating: 4.2, amazonReviewCount: 1234})}), 'amazon')).toBe('★ 4.2 | 1,234 reviews');
|
||||
expect(component.getStatusLabel(ReadStatus.READING)).toBe('metadata.viewer.readStatusReading'.toUpperCase());
|
||||
expect(component.getStatusLabel('missing')).toBe('UNSET');
|
||||
expect(component.getBookCoverUrl(createBook())).toBe('cover:21:2026-03-26');
|
||||
expect(component.getBookCoverUrl(createBook({primaryFile: createFile(1, {bookType: 'AUDIOBOOK'})}))).toBe('audio:21:2026-03-26');
|
||||
expect(component.hasAnyFiles(createBook())).toBe(true);
|
||||
expect(component.isPhysicalBook(createBook({primaryFile: undefined, alternativeFormats: []}))).toBe(true);
|
||||
expect(component.isMetadataFullyLocked(createMetadata({titleLocked: true, subtitleLocked: false}))).toBe(false);
|
||||
expect(component.isMetadataFullyLocked(createMetadata({titleLocked: true, subtitleLocked: true, allMetadataLocked: true}))).toBe(true);
|
||||
expect(component.hasComicMetadata(createBook({metadata: createMetadata({comicMetadata: {issueNumber: '7'}})}))).toBe(true);
|
||||
expect(component.hasAnyCreators({pencillers: ['A']})).toBe(true);
|
||||
expect(component.formatWebLink('https://example.com/books/very/long/path/segment/that/exceeds/limit')).toContain('example.com');
|
||||
expect(component.getChannelLabel(1)).toBe('metadata.viewer.channelMono');
|
||||
expect(component.getChannelLabel(2)).toBe('metadata.viewer.channelStereo');
|
||||
expect(component.getChannelLabel(6)).toBe('metadata.viewer.channelMultiple:count=6');
|
||||
});
|
||||
});
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {Book} from '../../../../book/model/book.model';
|
||||
import {SidecarMetadata, SidecarService, SidecarSyncStatus} from '../../../service/sidecar.service';
|
||||
import {SidecarViewerComponent} from './sidecar-viewer.component';
|
||||
|
||||
describe('SidecarViewerComponent', () => {
|
||||
const getSyncStatus = vi.fn();
|
||||
const getSidecarContent = vi.fn();
|
||||
const exportToSidecar = vi.fn();
|
||||
const importFromSidecar = vi.fn();
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string) => `translated:${key}`);
|
||||
|
||||
function createBook(id: number): Book {
|
||||
return {
|
||||
id,
|
||||
title: `Book ${id}`,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
} as Book;
|
||||
}
|
||||
|
||||
function createMetadata(): SidecarMetadata {
|
||||
return {
|
||||
version: '1',
|
||||
generatedAt: '2026-03-26T00:00:00Z',
|
||||
generatedBy: 'test',
|
||||
metadata: {title: 'Example'},
|
||||
cover: {source: 'embedded', path: '/covers/example.jpg'},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
getSyncStatus.mockReset();
|
||||
getSidecarContent.mockReset();
|
||||
exportToSidecar.mockReset();
|
||||
importFromSidecar.mockReset();
|
||||
messageAdd.mockReset();
|
||||
translate.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: SidecarService,
|
||||
useValue: {getSyncStatus, getSidecarContent, exportToSidecar, importFromSidecar},
|
||||
},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('resets its state when the selected book is cleared', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.currentBookId = 7;
|
||||
component.sidecarContent = createMetadata();
|
||||
component.syncStatus = 'IN_SYNC';
|
||||
component.loading = true;
|
||||
component.error = 'failed';
|
||||
|
||||
component.book = null;
|
||||
|
||||
expect(component.currentBookId).toBeNull();
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.syncStatus).toBe('NOT_APPLICABLE');
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.error).toBeNull();
|
||||
});
|
||||
|
||||
it('loads sync status and content when a sidecar exists for the selected book', () => {
|
||||
const metadata = createMetadata();
|
||||
getSyncStatus.mockReturnValue(of({status: 'IN_SYNC'}));
|
||||
getSidecarContent.mockReturnValue(of(metadata));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.book = createBook(7);
|
||||
|
||||
expect(getSyncStatus).toHaveBeenCalledWith(7);
|
||||
expect(getSidecarContent).toHaveBeenCalledWith(7);
|
||||
expect(component.currentBookId).toBe(7);
|
||||
expect(component.syncStatus).toBe('IN_SYNC');
|
||||
expect(component.sidecarContent).toEqual(metadata);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('skips content loading when the sidecar is missing or not applicable', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
getSyncStatus.mockReturnValue(of({status: 'MISSING'}));
|
||||
|
||||
component.book = createBook(3);
|
||||
|
||||
expect(getSidecarContent).not.toHaveBeenCalled();
|
||||
expect(component.syncStatus).toBe('MISSING');
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.loading).toBe(false);
|
||||
|
||||
getSyncStatus.mockReturnValue(of({status: 'NOT_APPLICABLE'}));
|
||||
component.book = createBook(4);
|
||||
|
||||
expect(getSidecarContent).not.toHaveBeenCalled();
|
||||
expect(component.syncStatus).toBe('NOT_APPLICABLE');
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to NOT_APPLICABLE when sync status lookup fails', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
getSyncStatus.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.book = createBook(5);
|
||||
|
||||
expect(component.syncStatus).toBe('NOT_APPLICABLE');
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.loading).toBe(false);
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('suppresses console noise for missing sidecar content but logs other load failures', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
|
||||
getSyncStatus.mockReturnValue(of({status: 'OUTDATED'}));
|
||||
getSidecarContent.mockReturnValue(throwError(() => ({status: 404})));
|
||||
component.book = createBook(6);
|
||||
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.loading).toBe(false);
|
||||
expect(consoleError).not.toHaveBeenCalled();
|
||||
|
||||
getSidecarContent.mockReturnValue(throwError(() => ({status: 500})));
|
||||
component.loadSidecarData(6);
|
||||
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('exports to sidecar, shows a success toast, and reloads the current book data', () => {
|
||||
exportToSidecar.mockReturnValue(of({message: 'ok'}));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
const reload = vi.spyOn(component, 'loadSidecarData').mockImplementation(() => undefined);
|
||||
component.currentBookId = 9;
|
||||
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(exportToSidecar).toHaveBeenCalledWith(9);
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:metadata.sidecar.toast.exportSuccessSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.exportSuccessDetail',
|
||||
});
|
||||
expect(reload).toHaveBeenCalledWith(9);
|
||||
expect(component.exporting).toBe(false);
|
||||
});
|
||||
|
||||
it('shows an error toast when export fails and ignores export without a selected book', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
exportToSidecar.mockReturnValue(throwError(() => new Error('export failed')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(exportToSidecar).not.toHaveBeenCalled();
|
||||
|
||||
component.currentBookId = 11;
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:metadata.sidecar.toast.exportFailedSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.exportFailedDetail',
|
||||
});
|
||||
expect(component.exporting).toBe(false);
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('imports from sidecar, shows success or error toasts, and reloads when needed', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
importFromSidecar.mockReturnValueOnce(of({message: 'ok'})).mockReturnValueOnce(throwError(() => new Error('import failed')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
const reload = vi.spyOn(component, 'loadSidecarData').mockImplementation(() => undefined);
|
||||
|
||||
component.currentBookId = 12;
|
||||
component.importFromSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:metadata.sidecar.toast.importSuccessSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.importSuccessDetail',
|
||||
});
|
||||
expect(reload).toHaveBeenCalledWith(12);
|
||||
expect(component.importing).toBe(false);
|
||||
|
||||
component.importFromSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenLastCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:metadata.sidecar.toast.importFailedSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.importFailedDetail',
|
||||
});
|
||||
expect(component.importing).toBe(false);
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('maps sync status severities and labels across all branches', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
const cases: [SidecarSyncStatus | 'UNKNOWN', string, string][] = [
|
||||
['IN_SYNC', 'success', 'translated:metadata.sidecar.syncStatusInSync'],
|
||||
['OUTDATED', 'warn', 'translated:metadata.sidecar.syncStatusOutdated'],
|
||||
['CONFLICT', 'danger', 'translated:metadata.sidecar.syncStatusConflict'],
|
||||
['MISSING', 'secondary', 'translated:metadata.sidecar.syncStatusMissing'],
|
||||
['NOT_APPLICABLE', 'info', 'translated:metadata.sidecar.syncStatusNA'],
|
||||
['UNKNOWN', 'info', 'translated:metadata.sidecar.syncStatusUnknown'],
|
||||
];
|
||||
|
||||
for (const [status, severity, label] of cases) {
|
||||
component.syncStatus = status as SidecarSyncStatus;
|
||||
expect(component.getSyncStatusSeverity()).toBe(severity);
|
||||
expect(component.getSyncStatusLabel()).toBe(label);
|
||||
}
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around dialog payload setup, reactive-form
|
||||
// state mutation, autocomplete widgets, and chained metadata-plus-cover uploads so bulk update
|
||||
// branching can be asserted without the full dialog and PrimeNG runtime.
|
||||
describe.skip('BulkMetadataUpdateComponent', () => {
|
||||
it('needs form seams to verify clear-field toggles, manual autocomplete entry, and payload construction', () => {
|
||||
// TODO(seam): Cover onFieldClearToggle, autocomplete handlers, and onSubmit payload mapping once the reactive-form shell is isolated behind deterministic helpers.
|
||||
});
|
||||
|
||||
it('needs upload seams to verify metadata success, partial cover-upload failure, and loading-state transitions', () => {
|
||||
// TODO(seam): Cover chained updateBooksMetadata and bulkUploadCover branches after dialog, message, and file-upload concerns are exposed through stable doubles.
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around dialog-driven book bootstrapping,
|
||||
// remote cover-search streams, file-upload handling, and toast side effects so cover selection
|
||||
// behavior can be asserted without the full overlay and browser file runtime.
|
||||
describe.skip('CoverSearchComponent', () => {
|
||||
it('needs search seams to verify lookup, result selection, and empty-state messaging', () => {
|
||||
// TODO(seam): Cover remote search branches once the metadata lookup stream and dialog payload are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs upload seams to verify local file import, cover replacement, and error reporting paths', () => {
|
||||
// TODO(seam): Cover upload and confirm flows after browser file APIs and message dispatch are extracted into testable adapters.
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user