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:
@@ -0,0 +1,94 @@
|
||||
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 {AuditLog, AuditLogService, PageableResponse} from './audit-log.service';
|
||||
|
||||
describe('AuditLogService', () => {
|
||||
let service: AuditLogService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
AuditLogService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(AuditLogService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('requests paged audit logs with the default pagination', () => {
|
||||
const response: PageableResponse<AuditLog> = {
|
||||
content: [],
|
||||
page: {
|
||||
totalElements: 0,
|
||||
totalPages: 0,
|
||||
number: 0,
|
||||
size: 25,
|
||||
},
|
||||
};
|
||||
|
||||
let result: PageableResponse<AuditLog> | undefined;
|
||||
service.getAuditLogs().subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/audit-logs'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
expect(request.request.params.get('page')).toBe('0');
|
||||
expect(request.request.params.get('size')).toBe('25');
|
||||
expect(request.request.params.has('action')).toBe(false);
|
||||
expect(request.request.params.has('username')).toBe(false);
|
||||
expect(request.request.params.has('from')).toBe(false);
|
||||
expect(request.request.params.has('to')).toBe(false);
|
||||
request.flush(response);
|
||||
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
|
||||
it('includes optional filters when they are provided', () => {
|
||||
service.getAuditLogs(2, 50, 'DELETE', 'alice', '2026-01-01', '2026-01-31').subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/audit-logs'));
|
||||
expect(request.request.params.get('page')).toBe('2');
|
||||
expect(request.request.params.get('size')).toBe('50');
|
||||
expect(request.request.params.get('action')).toBe('DELETE');
|
||||
expect(request.request.params.get('username')).toBe('alice');
|
||||
expect(request.request.params.get('from')).toBe('2026-01-01');
|
||||
expect(request.request.params.get('to')).toBe('2026-01-31');
|
||||
request.flush({
|
||||
content: [],
|
||||
page: {
|
||||
totalElements: 0,
|
||||
totalPages: 0,
|
||||
number: 2,
|
||||
size: 50,
|
||||
},
|
||||
} satisfies PageableResponse<AuditLog>);
|
||||
});
|
||||
|
||||
it('requests distinct usernames from the dedicated endpoint', () => {
|
||||
const response = ['alice', 'bob'];
|
||||
|
||||
let result: string[] | undefined;
|
||||
service.getDistinctUsernames().subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/audit-logs/usernames'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(response);
|
||||
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around route query-param restoration,
|
||||
// Prime table lazy-load events, interval-based auto-refresh, and router writes so the audit log
|
||||
// page can be exercised without a brittle integration harness for timers and navigation state.
|
||||
describe.skip('AuditLogsComponent', () => {
|
||||
it('needs route and timer seams to verify filter restoration, pagination, and auto-refresh behavior', () => {
|
||||
// TODO(seam): Cover query-param sync, table lazy loading, and interval refresh once route/timer dependencies are isolated.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): This component orchestrates async font discovery/loading, dialog-driven
|
||||
// uploads, confirmation flows, browser font registration, and toast reporting. Real coverage
|
||||
// needs a dedicated font-runtime seam around `CustomFontService` and the dialog/confirm stack.
|
||||
describe.skip('CustomFontsComponent', () => {
|
||||
it('needs a custom-font runtime seam to verify load success vs failure and browser font readiness', () => {
|
||||
// TODO(seam): Cover ensureFonts/loadAllFonts success and failure paths once browser-font
|
||||
// registration is exposed behind a stable service seam.
|
||||
});
|
||||
|
||||
it('needs a dialog-confirm seam to verify quota checks, upload additions, and delete flows', () => {
|
||||
// TODO(seam): Cover upload dialog close handling and confirmed delete behavior after the
|
||||
// dialog/confirmation interactions can be driven without full PrimeNG runtime wiring.
|
||||
});
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs browser seams around `document.fonts`, `FontFace`,
|
||||
// drag-and-drop file objects, and the DynamicDialog upload lifecycle so preview cancellation and
|
||||
// upload teardown can be asserted without depending on DOM font APIs that Vitest does not provide.
|
||||
describe.skip('FontUploadDialogComponent', () => {
|
||||
it('needs a font-preview seam to verify preview cleanup, drag-drop handling, and upload completion deterministically', () => {
|
||||
// TODO(seam): Cover preview token cancellation and dialog close behavior once font loading is wrapped in an injectable adapter.
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This component mixes permission-driven effects, clipboard access, PrimeNG
|
||||
// toast wiring, and service persistence, so it needs a mounted settings harness.
|
||||
describe.skip('HardcoverSettingsComponent', () => {
|
||||
it('needs a mounted settings harness for permission hydration, save, and clipboard flows', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
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 {HardcoverSyncSettingsService} from './hardcover-sync-settings.service';
|
||||
|
||||
describe('HardcoverSyncSettingsService', () => {
|
||||
let service: HardcoverSyncSettingsService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
HardcoverSyncSettingsService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(HardcoverSyncSettingsService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the saved hardcover sync settings', () => {
|
||||
let responseBody: unknown;
|
||||
|
||||
service.getSettings().subscribe(response => {
|
||||
responseBody = response;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'GET' && req.url.endsWith('/api/v1/hardcover-sync-settings')
|
||||
);
|
||||
request.flush({
|
||||
hardcoverApiKey: 'hardcover-key',
|
||||
hardcoverSyncEnabled: true,
|
||||
});
|
||||
|
||||
expect(responseBody).toEqual({
|
||||
hardcoverApiKey: 'hardcover-key',
|
||||
hardcoverSyncEnabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('persists updated hardcover sync settings', () => {
|
||||
const payload = {
|
||||
hardcoverApiKey: 'next-key',
|
||||
hardcoverSyncEnabled: false,
|
||||
};
|
||||
|
||||
service.updateSettings(payload).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'PUT' && req.url.endsWith('/api/v1/hardcover-sync-settings')
|
||||
);
|
||||
expect(request.request.body).toEqual(payload);
|
||||
request.flush(payload);
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): Kobo settings rely on user-permission effects, debounced slider saves,
|
||||
// confirm-dialog callbacks, clipboard access, and app-setting persistence.
|
||||
describe.skip('KoboSyncSettingsComponent', () => {
|
||||
it('needs a mounted settings harness for slider debounce, token regeneration, and save flows', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
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 {KoboService} from './kobo.service';
|
||||
|
||||
describe('KoboService', () => {
|
||||
let service: KoboService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
KoboService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(KoboService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the current kobo sync settings', () => {
|
||||
let responseBody: unknown;
|
||||
|
||||
service.getUser().subscribe(response => {
|
||||
responseBody = response;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'GET' && req.url.endsWith('/api/v1/kobo-settings')
|
||||
);
|
||||
request.flush({
|
||||
token: 'abc123',
|
||||
syncEnabled: true,
|
||||
autoAddToShelf: false,
|
||||
twoWayProgressSync: true,
|
||||
});
|
||||
|
||||
expect(responseBody).toEqual({
|
||||
token: 'abc123',
|
||||
syncEnabled: true,
|
||||
autoAddToShelf: false,
|
||||
twoWayProgressSync: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('creates or refreshes the kobo token through the token endpoint', () => {
|
||||
service.createOrUpdateToken().subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'PUT' && req.url.endsWith('/api/v1/kobo-settings/token')
|
||||
);
|
||||
expect(request.request.body).toBeNull();
|
||||
request.flush({
|
||||
token: 'new-token',
|
||||
syncEnabled: false,
|
||||
autoAddToShelf: true,
|
||||
twoWayProgressSync: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('persists updated kobo settings with a PUT request', () => {
|
||||
const payload = {
|
||||
token: 'abc123',
|
||||
syncEnabled: true,
|
||||
autoAddToShelf: true,
|
||||
twoWayProgressSync: false,
|
||||
progressMarkAsReadingThreshold: 25,
|
||||
progressMarkAsFinishedThreshold: 95,
|
||||
};
|
||||
|
||||
service.updateSettings(payload).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'PUT' && req.url.endsWith('/api/v1/kobo-settings')
|
||||
);
|
||||
expect(request.request.body).toEqual(payload);
|
||||
request.flush(payload);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around effect-driven permission hydration,
|
||||
// clipboard/browser globals, and message-service side effects so credential save, toggle, and
|
||||
// copy flows can be asserted without mounting the full KOReader settings runtime.
|
||||
describe.skip('KoreaderSettingsComponent', () => {
|
||||
it('needs permission seams to verify initial settings load and edit/save transitions', () => {
|
||||
// TODO(seam): Cover permission-gated loadKoreaderSettings and onEditSave once the current-user signal and side-effect services are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs browser seams to verify sync toggles, copy-to-clipboard success, and error reporting', () => {
|
||||
// TODO(seam): Cover toggle and copyText flows after navigator.clipboard, window.location, and toast dispatch are extracted into testable adapters.
|
||||
});
|
||||
});
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
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 {KoreaderService} from './koreader.service';
|
||||
|
||||
describe('KoreaderService', () => {
|
||||
let service: KoreaderService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
KoreaderService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(KoreaderService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('creates a KOReader user with the expected payload', () => {
|
||||
let responseBody: unknown;
|
||||
|
||||
service.createUser('reader', 'secret123').subscribe(response => {
|
||||
responseBody = response;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'PUT' && req.url.endsWith('/api/v1/koreader-users/me')
|
||||
);
|
||||
expect(request.request.body).toEqual({
|
||||
username: 'reader',
|
||||
password: 'secret123',
|
||||
});
|
||||
|
||||
request.flush({
|
||||
username: 'reader',
|
||||
password: 'secret123',
|
||||
syncEnabled: true,
|
||||
});
|
||||
|
||||
expect(responseBody).toEqual({
|
||||
username: 'reader',
|
||||
password: 'secret123',
|
||||
syncEnabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('loads the current KOReader user from the profile endpoint', () => {
|
||||
let responseBody: unknown;
|
||||
|
||||
service.getUser().subscribe(response => {
|
||||
responseBody = response;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'GET' && req.url.endsWith('/api/v1/koreader-users/me')
|
||||
);
|
||||
request.flush({
|
||||
username: 'reader',
|
||||
password: 'secret123',
|
||||
syncEnabled: false,
|
||||
syncWithGrimmoryReader: true,
|
||||
});
|
||||
|
||||
expect(responseBody).toEqual({
|
||||
username: 'reader',
|
||||
password: 'secret123',
|
||||
syncEnabled: false,
|
||||
syncWithGrimmoryReader: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('patches the sync-enabled flag using the enabled query parameter', () => {
|
||||
service.toggleSync(true).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.method === 'PATCH' && req.url.endsWith('/api/v1/koreader-users/me/sync')
|
||||
);
|
||||
expect(request.request.params.get('enabled')).toBe('true');
|
||||
expect(request.request.body).toBeNull();
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('uses the Grimmory sync-progress endpoint before falling back to the legacy Booklore route', () => {
|
||||
let completed = false;
|
||||
|
||||
service.toggleSyncProgressWithGrimmoryReader(false).subscribe(() => {
|
||||
completed = true;
|
||||
});
|
||||
|
||||
const grimmoryRequest = httpTestingController.expectOne(req =>
|
||||
req.method === 'PATCH' && req.url.endsWith('/api/v1/koreader-users/me/sync-progress-with-grimmory')
|
||||
);
|
||||
expect(grimmoryRequest.request.params.get('enabled')).toBe('false');
|
||||
grimmoryRequest.flush('missing route', {status: 404, statusText: 'Not Found'});
|
||||
|
||||
const legacyRequest = httpTestingController.expectOne(req =>
|
||||
req.method === 'PATCH' && req.url.endsWith('/api/v1/koreader-users/me/sync-progress-with-booklore')
|
||||
);
|
||||
expect(legacyRequest.request.params.get('enabled')).toBe('false');
|
||||
legacyRequest.flush(null);
|
||||
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around the nested device-settings shell and
|
||||
// child standalone panels so device preference composition can be asserted without the full
|
||||
// settings page runtime.
|
||||
describe.skip('DeviceSettingsComponent', () => {
|
||||
it('needs composition seams to verify KOReader, email, and send-to-device panel inclusion', () => {
|
||||
// TODO(seam): Cover child-panel composition after the shell template is isolated from the broader settings runtime and its lazy imports.
|
||||
});
|
||||
});
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ReactiveFormsModule} from '@angular/forms';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {
|
||||
createDynamicDialogHarness,
|
||||
createMessageServiceProvider,
|
||||
createMessageServiceSpy,
|
||||
} from '../../../../core/testing/dialog-testing';
|
||||
import {EmailV2ProviderService} from '../email-v2-provider/email-v2-provider.service';
|
||||
import {CreateEmailProviderDialogComponent} from './create-email-provider-dialog.component';
|
||||
|
||||
describe('CreateEmailProviderDialogComponent', () => {
|
||||
let createEmailProvider: ReturnType<typeof vi.fn>;
|
||||
let dialogHarness: ReturnType<typeof createDynamicDialogHarness<null>>;
|
||||
let messageService: ReturnType<typeof createMessageServiceSpy>;
|
||||
let translate: TranslocoService['translate'];
|
||||
|
||||
beforeEach(() => {
|
||||
createEmailProvider = vi.fn(() => of({
|
||||
id: 9,
|
||||
name: 'Primary SMTP',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'mailer',
|
||||
password: 'secret',
|
||||
fromAddress: 'mailer@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
}));
|
||||
dialogHarness = createDynamicDialogHarness<null>(null);
|
||||
messageService = createMessageServiceSpy();
|
||||
translate = (<T = string>(key: string, params?: Record<string, unknown>) => {
|
||||
if (!params) {
|
||||
return `translated:${key}` as T;
|
||||
}
|
||||
|
||||
return `translated:${key}:${JSON.stringify(params)}` as T;
|
||||
}) as TranslocoService['translate'];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createComponent() {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ReactiveFormsModule],
|
||||
providers: [
|
||||
...dialogHarness.providers,
|
||||
{
|
||||
provide: EmailV2ProviderService,
|
||||
useValue: {
|
||||
createEmailProvider,
|
||||
},
|
||||
},
|
||||
createMessageServiceProvider(messageService),
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new CreateEmailProviderDialogComponent());
|
||||
component.ngOnInit();
|
||||
return component;
|
||||
}
|
||||
|
||||
it('initializes the reactive form with the expected defaults and validators', () => {
|
||||
const component = createComponent();
|
||||
|
||||
expect(component.emailProviderForm.getRawValue()).toEqual({
|
||||
name: '',
|
||||
host: '',
|
||||
port: null,
|
||||
username: '',
|
||||
password: '',
|
||||
fromAddress: '',
|
||||
auth: false,
|
||||
startTls: false,
|
||||
});
|
||||
|
||||
component.emailProviderForm.patchValue({
|
||||
name: 'ab',
|
||||
host: '',
|
||||
port: 0,
|
||||
fromAddress: 'not-an-email',
|
||||
});
|
||||
|
||||
expect(component.emailProviderForm.invalid).toBe(true);
|
||||
expect(component.emailProviderForm.controls['name'].hasError('minlength')).toBe(true);
|
||||
expect(component.emailProviderForm.controls['host'].hasError('required')).toBe(true);
|
||||
expect(component.emailProviderForm.controls['port'].hasError('min')).toBe(true);
|
||||
expect(component.emailProviderForm.controls['fromAddress'].hasError('email')).toBe(true);
|
||||
});
|
||||
|
||||
it('shows a warning toast and skips the mutation when the form is invalid', () => {
|
||||
const component = createComponent();
|
||||
component.emailProviderForm.patchValue({
|
||||
name: 'ab',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
});
|
||||
|
||||
component.createEmailProvider();
|
||||
|
||||
expect(createEmailProvider).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'translated:settingsEmail.provider.create.validationError',
|
||||
detail: 'translated:settingsEmail.provider.create.validationErrorDetail',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits the form payload, shows a success toast, and closes the dialog on success', () => {
|
||||
const component = createComponent();
|
||||
component.emailProviderForm.setValue({
|
||||
name: 'Primary SMTP',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'mailer',
|
||||
password: 'secret',
|
||||
fromAddress: 'mailer@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
});
|
||||
|
||||
component.createEmailProvider();
|
||||
|
||||
expect(createEmailProvider).toHaveBeenCalledWith({
|
||||
name: 'Primary SMTP',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'mailer',
|
||||
password: 'secret',
|
||||
fromAddress: 'mailer@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:settingsEmail.provider.create.success',
|
||||
detail: 'translated:settingsEmail.provider.create.successDetail',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('shows the translated backend error detail and keeps the dialog open when creation fails with a message', () => {
|
||||
createEmailProvider.mockReturnValueOnce(throwError(() => ({
|
||||
error: {
|
||||
message: 'SMTP rejected credentials',
|
||||
},
|
||||
})));
|
||||
const component = createComponent();
|
||||
component.emailProviderForm.setValue({
|
||||
name: 'Broken SMTP',
|
||||
host: 'smtp.example.com',
|
||||
port: 465,
|
||||
username: 'mailer',
|
||||
password: 'bad-secret',
|
||||
fromAddress: 'mailer@example.com',
|
||||
auth: true,
|
||||
startTls: false,
|
||||
});
|
||||
|
||||
component.createEmailProvider();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:settingsEmail.provider.create.failed',
|
||||
detail: 'translated:settingsEmail.provider.create.failedDetail:{"message":"SMTP rejected credentials"}',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('falls back to the default failure detail when the backend does not return a message', () => {
|
||||
createEmailProvider.mockReturnValueOnce(throwError(() => new Error('network down')));
|
||||
const component = createComponent();
|
||||
component.emailProviderForm.setValue({
|
||||
name: 'Fallback SMTP',
|
||||
host: 'smtp.example.com',
|
||||
port: 2525,
|
||||
username: '',
|
||||
password: '',
|
||||
fromAddress: '',
|
||||
auth: false,
|
||||
startTls: false,
|
||||
});
|
||||
|
||||
component.createEmailProvider();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:settingsEmail.provider.create.failed',
|
||||
detail: 'translated:settingsEmail.provider.create.failedDefault',
|
||||
});
|
||||
expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('closes the dialog without a result when dismissed explicitly', () => {
|
||||
const component = createComponent();
|
||||
|
||||
component.closeDialog();
|
||||
|
||||
expect(dialogHarness.dialogRef.close).toHaveBeenCalledOnce();
|
||||
expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith();
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): Recipient creation also needs a mounted dialog harness around the reactive
|
||||
// form, duplicate validation, and recipient persistence branches.
|
||||
describe.skip('CreateEmailRecipientDialogComponent', () => {
|
||||
it('needs a dialog harness for submit validation and recipient creation branches', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {EmailProvider} from './email-provider.model';
|
||||
|
||||
describe('email-provider.model', () => {
|
||||
it('captures provider connection details and editing state', () => {
|
||||
const provider: EmailProvider = {
|
||||
isEditing: false,
|
||||
id: 1,
|
||||
userId: 9,
|
||||
name: 'SMTP',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'secret',
|
||||
fromAddress: 'books@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: true,
|
||||
shared: false
|
||||
};
|
||||
|
||||
expect(provider.port).toBe(587);
|
||||
expect(provider.defaultProvider).toBe(true);
|
||||
expectTypeOf(provider.startTls).toEqualTypeOf<boolean>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {EmailRecipient} from './email-recipient.model';
|
||||
|
||||
describe('email-recipient.model', () => {
|
||||
it('captures recipient identity and editing state', () => {
|
||||
const recipient: EmailRecipient = {
|
||||
id: 2,
|
||||
email: 'reader@example.com',
|
||||
name: 'Reader',
|
||||
defaultRecipient: true,
|
||||
isEditing: false
|
||||
};
|
||||
|
||||
expect(recipient.email).toBe('reader@example.com');
|
||||
expect(recipient.defaultRecipient).toBe(true);
|
||||
expectTypeOf(recipient.isEditing).toEqualTypeOf<boolean>();
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around current-user bootstrapping, shared
|
||||
// provider permission logic, dialog close streams, and confirm/toast side effects so provider
|
||||
// management can be asserted without the full PrimeNG table runtime.
|
||||
describe.skip('EmailV2ProviderComponent', () => {
|
||||
it('needs service seams to verify provider loading, default assignment, sharing toggles, and delete/save outcomes', () => {
|
||||
// TODO(seam): Cover loadCurrentUser, loadEmailProviders, saveProvider, deleteProvider, setDefaultProvider, and toggleShared once service streams are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs table-edit seams to verify row editing and create-provider dialog refresh behavior', () => {
|
||||
// TODO(seam): Cover toggleEdit and openCreateProviderDialog after dialog onClose streams and provider-row state are extracted from the live table runtime.
|
||||
});
|
||||
});
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
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 {API_CONFIG} from '../../../../core/config/api-config';
|
||||
import {EmailV2ProviderService} from './email-v2-provider.service';
|
||||
|
||||
describe('EmailV2ProviderService', () => {
|
||||
let service: EmailV2ProviderService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
EmailV2ProviderService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(EmailV2ProviderService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads providers', () => {
|
||||
service.getEmailProviders().subscribe(providers => {
|
||||
expect(providers).toEqual([{id: 1, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: true, shared: false, isEditing: false}]);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([{id: 1, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: true, shared: false, isEditing: false}]);
|
||||
});
|
||||
|
||||
it('creates a provider', () => {
|
||||
const provider = {id: 1, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: false, shared: false, isEditing: false};
|
||||
|
||||
service.createEmailProvider(provider).subscribe(result => {
|
||||
expect(result).toEqual(provider);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(provider);
|
||||
request.flush(provider);
|
||||
});
|
||||
|
||||
it('updates a provider', () => {
|
||||
const provider = {id: 2, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: false, shared: false, isEditing: true};
|
||||
|
||||
service.updateProvider(provider).subscribe(result => {
|
||||
expect(result).toEqual(provider);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers/2`);
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual(provider);
|
||||
request.flush(provider);
|
||||
});
|
||||
|
||||
it('deletes a provider', () => {
|
||||
service.deleteProvider(3).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers/3`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('marks a provider as default', () => {
|
||||
service.setDefaultProvider(4).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers/4/set-default`);
|
||||
expect(request.request.method).toBe('PATCH');
|
||||
expect(request.request.body).toEqual({});
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around confirm dialogs, dialog-launcher
|
||||
// close streams, and editable table row state so recipient CRUD behavior can be asserted without
|
||||
// the full PrimeNG table runtime.
|
||||
describe.skip('EmailV2RecipientComponent', () => {
|
||||
it('needs service seams to verify recipient loading, default selection, and save/delete outcomes', () => {
|
||||
// TODO(seam): Cover loadRecipientEmails, saveRecipient, deleteRecipient, and setDefaultRecipient once service streams and confirm behavior are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs table-edit seams to verify row edit toggling and create-dialog refresh behavior', () => {
|
||||
// TODO(seam): Cover toggleEditRecipient and openAddRecipientDialog after dialog onClose streams and row-edit state are extracted from the live table runtime.
|
||||
});
|
||||
});
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
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 {API_CONFIG} from '../../../../core/config/api-config';
|
||||
import {EmailV2RecipientService} from './email-v2-recipient.service';
|
||||
|
||||
describe('EmailV2RecipientService', () => {
|
||||
let service: EmailV2RecipientService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
EmailV2RecipientService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(EmailV2RecipientService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads recipients', () => {
|
||||
service.getRecipients().subscribe(recipients => {
|
||||
expect(recipients).toEqual([{id: 1, email: 'reader@test', name: 'Reader', defaultRecipient: true, isEditing: false}]);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([{id: 1, email: 'reader@test', name: 'Reader', defaultRecipient: true, isEditing: false}]);
|
||||
});
|
||||
|
||||
it('creates a recipient', () => {
|
||||
const recipient = {id: 1, email: 'reader@test', name: 'Reader', defaultRecipient: false, isEditing: false};
|
||||
|
||||
service.createRecipient(recipient).subscribe(result => {
|
||||
expect(result).toEqual(recipient);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(recipient);
|
||||
request.flush(recipient);
|
||||
});
|
||||
|
||||
it('updates a recipient', () => {
|
||||
const recipient = {id: 2, email: 'reader@test', name: 'Reader', defaultRecipient: false, isEditing: true};
|
||||
|
||||
service.updateRecipient(recipient).subscribe(result => {
|
||||
expect(result).toEqual(recipient);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients/2`);
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual(recipient);
|
||||
request.flush(recipient);
|
||||
});
|
||||
|
||||
it('deletes a recipient', () => {
|
||||
service.deleteRecipient(3).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients/3`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('marks a recipient as default', () => {
|
||||
service.setDefaultRecipient(4).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients/4/set-default`);
|
||||
expect(request.request.method).toBe('PATCH');
|
||||
expect(request.request.body).toEqual({});
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): The email settings screen coordinates nested provider and recipient dialogs,
|
||||
// permissions, and persisted settings, which needs a mounted settings harness.
|
||||
describe.skip('EmailV2Component', () => {
|
||||
it('needs a mounted settings harness for provider, recipient, and toggle flows', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
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 {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {EmailService} from './email.service';
|
||||
|
||||
describe('EmailService', () => {
|
||||
let service: EmailService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
EmailService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(EmailService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('emails a book with the detailed payload', () => {
|
||||
const payload = {bookId: 1, providerId: 2, recipientId: 3, bookFileId: 4};
|
||||
|
||||
service.emailBook(payload).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/book`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(payload);
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('emails a book quickly', () => {
|
||||
service.emailBookQuick(99).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/book/99`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({});
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import {ComponentFixture, 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 {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
||||
import {LibraryService} from '../../book/service/library.service';
|
||||
import {FileNamingPatternComponent} from './file-naming-pattern.component';
|
||||
|
||||
describe('FileNamingPatternComponent', () => {
|
||||
let fixture: ComponentFixture<FileNamingPatternComponent>;
|
||||
let component: FileNamingPatternComponent;
|
||||
let saveSettings: ReturnType<typeof vi.fn>;
|
||||
let updateLibraryFileNamingPattern: ReturnType<typeof vi.fn>;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
saveSettings = vi.fn(() => of(void 0));
|
||||
updateLibraryFileNamingPattern = vi.fn(() => of(void 0));
|
||||
messageService = {add: vi.fn()};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [FileNamingPatternComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: AppSettingsService, useValue: {appSettings: () => ({uploadPattern: '{authors}/{title}'}), saveSettings}},
|
||||
{
|
||||
provide: LibraryService,
|
||||
useValue: {
|
||||
libraries: () => [
|
||||
{id: 1, name: 'Main', fileNamingPattern: '{series}/{title}'},
|
||||
{id: 2, name: 'Side', fileNamingPattern: ''},
|
||||
],
|
||||
updateLibraryFileNamingPattern,
|
||||
},
|
||||
},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(FileNamingPatternComponent);
|
||||
component = fixture.componentInstance;
|
||||
component.ngOnInit();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('hydrates the default pattern and generates previews with extensions', () => {
|
||||
expect(component.defaultPattern).toBe('{authors}/{title}');
|
||||
expect(component.generateDefaultPreview()).toBe('/Patrick Rothfuss/The Name of the Wind.pdf');
|
||||
});
|
||||
|
||||
it('validates patterns and exposes invalid-character errors', () => {
|
||||
component.onDefaultPatternChange('bad%^pattern');
|
||||
|
||||
expect(component.validatePattern('bad%^pattern')).toBe(false);
|
||||
expect(component.defaultErrorMessage).toBeTruthy();
|
||||
});
|
||||
|
||||
it('persists the default upload pattern when validation passes', () => {
|
||||
component.defaultPattern = '{title}/{series}';
|
||||
|
||||
component.savePatterns();
|
||||
|
||||
expect(saveSettings).toHaveBeenCalledWith([
|
||||
{key: 'UPLOAD_FILE_PATTERN', newValue: '{title}/{series}'},
|
||||
]);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('saves library overrides and reports partial failures', () => {
|
||||
updateLibraryFileNamingPattern
|
||||
.mockReturnValueOnce(of(void 0))
|
||||
.mockReturnValueOnce(throwError(() => new Error('boom')));
|
||||
|
||||
component.saveLibraryPatterns();
|
||||
|
||||
expect(updateLibraryFileNamingPattern).toHaveBeenCalledTimes(2);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around Prime split-button/tiered-menu browser
|
||||
// hooks such as `window.matchMedia`, plus effect-driven settings hydration and metadata-regeneration
|
||||
// subscriptions, so preference saves can be asserted without depending on Prime runtime internals.
|
||||
describe.skip('GlobalPreferencesComponent', () => {
|
||||
it('needs a menu and settings seam to verify toggle persistence, file-size validation, and cover-regeneration actions', () => {
|
||||
// TODO(seam): Cover saveSetting and regenerateCovers once the split-button/menu interactions are isolated behind a smaller adapter.
|
||||
});
|
||||
});
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import {ComponentFixture, 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 {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {MetadataMatchWeightsService} from '../../../../shared/service/metadata-match-weights.service';
|
||||
import {AppSettingKey} from '../../../../shared/model/app-settings.model';
|
||||
import {MetadataMatchWeightsComponent} from './metadata-match-weights-component';
|
||||
|
||||
describe('MetadataMatchWeightsComponent', () => {
|
||||
let fixture: ComponentFixture<MetadataMatchWeightsComponent>;
|
||||
let component: MetadataMatchWeightsComponent;
|
||||
let saveSettings: ReturnType<typeof vi.fn>;
|
||||
let recalculateAll: ReturnType<typeof vi.fn>;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
saveSettings = vi.fn(() => of(void 0));
|
||||
recalculateAll = vi.fn(() => of(void 0));
|
||||
messageService = {add: vi.fn()};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [MetadataMatchWeightsComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{
|
||||
provide: AppSettingsService,
|
||||
useValue: {
|
||||
appSettings: () => ({
|
||||
metadataMatchWeights: {
|
||||
title: 10,
|
||||
subtitle: 5,
|
||||
description: 3,
|
||||
publisher: 2,
|
||||
publishedDate: 1,
|
||||
authors: 9,
|
||||
categories: 4,
|
||||
seriesName: 6,
|
||||
seriesNumber: 2,
|
||||
seriesTotal: 1,
|
||||
isbn13: 8,
|
||||
isbn10: 7,
|
||||
pageCount: 2,
|
||||
language: 1,
|
||||
amazonRating: 2,
|
||||
amazonReviewCount: 2,
|
||||
goodreadsRating: 2,
|
||||
goodreadsReviewCount: 2,
|
||||
hardcoverRating: 2,
|
||||
hardcoverReviewCount: 2,
|
||||
doubanRating: 2,
|
||||
doubanReviewCount: 2,
|
||||
ranobedbRating: 2,
|
||||
audibleRating: 2,
|
||||
audibleReviewCount: 2,
|
||||
coverImage: 3,
|
||||
},
|
||||
}),
|
||||
saveSettings,
|
||||
},
|
||||
},
|
||||
{provide: MetadataMatchWeightsService, useValue: {recalculateAll}},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(MetadataMatchWeightsComponent);
|
||||
component = fixture.componentInstance;
|
||||
component.ngOnInit();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('hydrates the reactive form from saved match weights', () => {
|
||||
expect(component.form.get('title')?.value).toBe(10);
|
||||
expect(component.form.get('authors')?.value).toBe(9);
|
||||
expect(component.orderedKeys[0]).toBe('title');
|
||||
});
|
||||
|
||||
it('persists valid form values through app settings', () => {
|
||||
component.save();
|
||||
|
||||
expect(saveSettings).toHaveBeenCalledWith([
|
||||
{
|
||||
key: AppSettingKey.METADATA_MATCH_WEIGHTS,
|
||||
newValue: component.form.value,
|
||||
},
|
||||
]);
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
expect(component.isSaving).toBe(false);
|
||||
});
|
||||
|
||||
it('does not save invalid forms', () => {
|
||||
component.form.get('title')?.setValue(-1);
|
||||
|
||||
component.save();
|
||||
|
||||
expect(saveSettings).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it('reports recalculate failures and resets the loading flag', () => {
|
||||
recalculateAll.mockReturnValueOnce(throwError(() => new Error('boom')));
|
||||
|
||||
component.recalculate();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
expect(component.isRecalculating).toBe(false);
|
||||
});
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs a seam around effect-driven settings hydration and
|
||||
// the large provider payload editor so save behavior can be asserted without coupling the spec to a
|
||||
// brittle form snapshot across every provider toggle and token field.
|
||||
describe.skip('MetadataProviderSettingsComponent', () => {
|
||||
it('needs a provider-settings form seam to verify payload assembly and toggle/token interactions deterministically', () => {
|
||||
// TODO(seam): Cover applySettings, token gating, and save payload composition once the provider editor state is extracted behind a smaller adapter.
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around app-settings signal hydration,
|
||||
// library-sync service interactions, and the nested preference shell so save/reset behavior can
|
||||
// be asserted without mounting the full settings runtime.
|
||||
describe.skip('LibraryMetadataSettingsComponent', () => {
|
||||
it('needs settings seams to verify sidecar preference synchronization and reset behavior', () => {
|
||||
// TODO(seam): Cover the effect-driven settings bootstrap once app settings and sync updates are exposed through deterministic test doubles.
|
||||
});
|
||||
|
||||
it('needs child-shell seams to verify save-state propagation across nested metadata preference panels', () => {
|
||||
// TODO(seam): Cover panel composition and persistence actions after the settings shell is isolated from the live query-backed view model.
|
||||
});
|
||||
});
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {AppSettingKey, type AppSettings, type MetadataPersistenceSettings} from '../../../../shared/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {SettingsHelperService} from '../../../../shared/service/settings-helper.service';
|
||||
import {MetadataPersistenceSettingsComponent} from './metadata-persistence-settings-component';
|
||||
|
||||
describe('MetadataPersistenceSettingsComponent', () => {
|
||||
let fixture: ComponentFixture<MetadataPersistenceSettingsComponent>;
|
||||
let component: MetadataPersistenceSettingsComponent;
|
||||
let appSettingsService: {appSettings: ReturnType<typeof vi.fn>};
|
||||
let settingsHelper: {saveSetting: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
appSettingsService = {
|
||||
appSettings: vi.fn(() => buildSettings()),
|
||||
};
|
||||
settingsHelper = {
|
||||
saveSetting: vi.fn(),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [MetadataPersistenceSettingsComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: SettingsHelperService, useValue: settingsHelper},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(MetadataPersistenceSettingsComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('hydrates persistence settings and network-storage state from app settings', () => {
|
||||
expect(component.isNetworkStorage).toBe(true);
|
||||
expect(component.metadataPersistence.moveFilesToLibraryPattern).toBe(true);
|
||||
expect(component.metadataPersistence.convertCbrCb7ToCbz).toBe(true);
|
||||
expect(component.metadataPersistence.saveToOriginalFile.epub).toEqual({
|
||||
enabled: true,
|
||||
maxFileSizeInMb: 123,
|
||||
});
|
||||
expect(component.metadataPersistence.saveToOriginalFile.pdf).toEqual({
|
||||
enabled: false,
|
||||
maxFileSizeInMb: 250,
|
||||
});
|
||||
expect(component.metadataPersistence.sidecarSettings).toEqual({
|
||||
enabled: true,
|
||||
writeOnUpdate: true,
|
||||
writeOnScan: false,
|
||||
includeCoverFile: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('toggles persistence flags and saves the updated settings', () => {
|
||||
component.onPersistenceToggle('convertCbrCb7ToCbz');
|
||||
|
||||
expect(component.metadataPersistence.convertCbrCb7ToCbz).toBe(false);
|
||||
expect(settingsHelper.saveSetting).toHaveBeenCalledWith(
|
||||
AppSettingKey.METADATA_PERSISTENCE_SETTINGS,
|
||||
component.metadataPersistence
|
||||
);
|
||||
});
|
||||
|
||||
it('toggles save-to-original-file settings and persists the current metadata settings', () => {
|
||||
component.onSaveToOriginalFileToggle('pdf');
|
||||
|
||||
expect(component.metadataPersistence.saveToOriginalFile.pdf.enabled).toBe(true);
|
||||
expect(settingsHelper.saveSetting).toHaveBeenCalledWith(
|
||||
AppSettingKey.METADATA_PERSISTENCE_SETTINGS,
|
||||
component.metadataPersistence
|
||||
);
|
||||
});
|
||||
|
||||
it('toggles sidecar settings and saves the updated state', () => {
|
||||
component.onSidecarToggle('includeCoverFile');
|
||||
|
||||
expect(component.metadataPersistence.sidecarSettings?.includeCoverFile).toBe(true);
|
||||
expect(settingsHelper.saveSetting).toHaveBeenCalledWith(
|
||||
AppSettingKey.METADATA_PERSISTENCE_SETTINGS,
|
||||
component.metadataPersistence
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
function buildSettings(): AppSettings {
|
||||
const metadataPersistenceSettings: MetadataPersistenceSettings = {
|
||||
moveFilesToLibraryPattern: true,
|
||||
convertCbrCb7ToCbz: true,
|
||||
saveToOriginalFile: {
|
||||
epub: {enabled: true, maxFileSizeInMb: 123},
|
||||
pdf: {enabled: false, maxFileSizeInMb: 250},
|
||||
cbx: {enabled: true, maxFileSizeInMb: 64},
|
||||
audiobook: {enabled: false, maxFileSizeInMb: 1000},
|
||||
},
|
||||
sidecarSettings: {
|
||||
enabled: true,
|
||||
writeOnUpdate: true,
|
||||
writeOnScan: false,
|
||||
includeCoverFile: false,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
diskType: 'NETWORK',
|
||||
metadataPersistenceSettings,
|
||||
} as AppSettings;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around settings hydration and the composed
|
||||
// metadata preference subpanels so the container shell can be asserted without mounting the full
|
||||
// nested settings runtime.
|
||||
describe.skip('MetadataSettingsComponent', () => {
|
||||
it('needs settings seams to verify metadata option bootstrap and bookdrop-download toggling', () => {
|
||||
// TODO(seam): Cover loadSettings, initializeSettings, and onMetadataDownloadOnBookdropToggle once app settings and save helpers are exposed through deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs child-panel seams to verify metadata option submissions across nested preferences', () => {
|
||||
// TODO(seam): Cover onMetadataSubmit after the container shell is isolated from the provider, match-weight, persistence, and review child runtimes.
|
||||
});
|
||||
});
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {AppSettingKey, type AppSettings} from '../../../../shared/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {SettingsHelperService} from '../../../../shared/service/settings-helper.service';
|
||||
import {PublicReviewsSettingsComponent} from './public-reviews-settings-component';
|
||||
|
||||
describe('PublicReviewsSettingsComponent', () => {
|
||||
let fixture: ComponentFixture<PublicReviewsSettingsComponent>;
|
||||
let component: PublicReviewsSettingsComponent;
|
||||
let appSettingsService: {appSettings: ReturnType<typeof vi.fn>};
|
||||
let settingsHelper: {saveSetting: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
appSettingsService = {
|
||||
appSettings: vi.fn(() => ({
|
||||
metadataPublicReviewsSettings: {
|
||||
downloadEnabled: false,
|
||||
autoDownloadEnabled: true,
|
||||
providers: [{provider: 'Amazon', enabled: true, maxReviews: 7}],
|
||||
},
|
||||
} as AppSettings)),
|
||||
};
|
||||
settingsHelper = {
|
||||
saveSetting: vi.fn(),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PublicReviewsSettingsComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: SettingsHelperService, useValue: settingsHelper},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(PublicReviewsSettingsComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('hydrates saved review settings and ensures all required providers exist', () => {
|
||||
expect(component.publicReviewSettings.downloadEnabled).toBe(false);
|
||||
expect(component.publicReviewSettings.autoDownloadEnabled).toBe(true);
|
||||
expect(component.publicReviewSettings.providers).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({provider: 'Amazon', enabled: true, maxReviews: 7}),
|
||||
expect.objectContaining({provider: 'GoodReads', enabled: false, maxReviews: 10}),
|
||||
expect.objectContaining({provider: 'Douban', enabled: false, maxReviews: 10}),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('persists top-level review toggles', () => {
|
||||
component.onPublicReviewsToggle(true);
|
||||
component.onAutoDownloadToggle(false);
|
||||
|
||||
expect(settingsHelper.saveSetting).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS,
|
||||
component.publicReviewSettings
|
||||
);
|
||||
expect(settingsHelper.saveSetting).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS,
|
||||
component.publicReviewSettings
|
||||
);
|
||||
});
|
||||
|
||||
it('updates provider settings and persists them', () => {
|
||||
component.onProviderToggle('Amazon', false);
|
||||
component.onMaxReviewsChange('Amazon', 12);
|
||||
|
||||
const amazon = component.publicReviewSettings.providers.find(provider => provider.provider === 'Amazon');
|
||||
expect(amazon).toEqual(expect.objectContaining({enabled: false, maxReviews: 12}));
|
||||
expect(settingsHelper.saveSetting).toHaveBeenCalledWith(
|
||||
AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS,
|
||||
component.publicReviewSettings
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): OPDS settings coordinate clipboard access, confirmation dialogs, PrimeNG
|
||||
// tables, and remote user CRUD, so they should be exercised with a mounted settings harness.
|
||||
describe.skip('OpdsSettings', () => {
|
||||
it('needs a mounted settings harness for user CRUD and OPDS or Komga toggle branches', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {OpdsService} from './opds.service';
|
||||
|
||||
describe('OpdsService', () => {
|
||||
let service: OpdsService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
OpdsService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(OpdsService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads OPDS users', () => {
|
||||
service.getUser().subscribe(users => {
|
||||
expect(users).toEqual([{id: 1, userId: 10, username: 'reader'}]);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([{id: 1, userId: 10, username: 'reader'}]);
|
||||
});
|
||||
|
||||
it('creates an OPDS user', () => {
|
||||
const payload = {username: 'reader', password: 'secret', sortOrder: 'TITLE_ASC' as const};
|
||||
|
||||
service.createUser(payload).subscribe(user => {
|
||||
expect(user).toEqual({id: 1, userId: 10, username: 'reader', sortOrder: 'TITLE_ASC'});
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(payload);
|
||||
request.flush({id: 1, userId: 10, username: 'reader', sortOrder: 'TITLE_ASC'});
|
||||
});
|
||||
|
||||
it('updates an OPDS user sort order', () => {
|
||||
service.updateUser(5, 'AUTHOR_DESC').subscribe(user => {
|
||||
expect(user).toEqual({id: 5, userId: 10, username: 'reader', sortOrder: 'AUTHOR_DESC'});
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users/5`);
|
||||
expect(request.request.method).toBe('PATCH');
|
||||
expect(request.request.body).toEqual({sortOrder: 'AUTHOR_DESC'});
|
||||
request.flush({id: 5, userId: 10, username: 'reader', sortOrder: 'AUTHOR_DESC'});
|
||||
});
|
||||
|
||||
it('deletes an OPDS credential', () => {
|
||||
service.deleteCredential(7).subscribe(response => {
|
||||
expect(response).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users/7`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {ReaderPreferencesService} from '../reader-preferences.service';
|
||||
import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrollMode, UserSettings} from '../../user-management/user.service';
|
||||
import {CbxReaderPreferencesComponent} from './cbx-reader-preferences-component';
|
||||
|
||||
function createUserSettings(): UserSettings {
|
||||
return {
|
||||
perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
|
||||
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
|
||||
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.AUTO},
|
||||
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: true,
|
||||
} as UserSettings;
|
||||
}
|
||||
|
||||
describe('CbxReaderPreferencesComponent', () => {
|
||||
let fixture: ComponentFixture<CbxReaderPreferencesComponent>;
|
||||
let updatePreference: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
updatePreference = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [CbxReaderPreferencesComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: ReaderPreferencesService, useValue: {updatePreference}},
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(CbxReaderPreferencesComponent);
|
||||
fixture.componentInstance.userSettings = createUserSettings();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('returns configured defaults from the supplied user settings', () => {
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
expect(component.selectedCbxSpread).toBe(CbxPageSpread.EVEN);
|
||||
expect(component.selectedCbxViewMode).toBe(CbxPageViewMode.SINGLE_PAGE);
|
||||
expect(component.selectedCbxFitMode).toBe(CbxFitMode.AUTO);
|
||||
expect(component.selectedCbxScrollMode).toBe(CbxScrollMode.PAGINATED);
|
||||
expect(component.selectedCbxBackgroundColor).toBe(CbxBackgroundColor.GRAY);
|
||||
});
|
||||
|
||||
it('persists each CBX reader preference through the shared preferences service', () => {
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component.selectedCbxSpread = CbxPageSpread.ODD;
|
||||
component.selectedCbxViewMode = CbxPageViewMode.TWO_PAGE;
|
||||
component.selectedCbxFitMode = CbxFitMode.FIT_WIDTH;
|
||||
component.selectedCbxScrollMode = CbxScrollMode.INFINITE;
|
||||
component.selectedCbxBackgroundColor = CbxBackgroundColor.BLACK;
|
||||
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(1, ['cbxReaderSetting', 'pageSpread'], CbxPageSpread.ODD);
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(2, ['cbxReaderSetting', 'pageViewMode'], CbxPageViewMode.TWO_PAGE);
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(3, ['cbxReaderSetting', 'fitMode'], CbxFitMode.FIT_WIDTH);
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(4, ['cbxReaderSetting', 'scrollMode'], CbxScrollMode.INFINITE);
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(5, ['cbxReaderSetting', 'backgroundColor'], CbxBackgroundColor.BLACK);
|
||||
});
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): EPUB reader preferences need a mounted settings harness around form controls,
|
||||
// custom-font selection, and persisted user-setting mutations.
|
||||
describe.skip('EpubReaderPreferencesComponent', () => {
|
||||
it('needs a mounted settings harness for theme, flow, and font preference branches', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {ReaderPreferencesService} from '../reader-preferences.service';
|
||||
import {UserSettings} from '../../user-management/user.service';
|
||||
import {PdfReaderPreferencesComponent} from './pdf-reader-preferences-component';
|
||||
|
||||
function createUserSettings(): UserSettings {
|
||||
return {
|
||||
perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: 'page-fit', showSidebar: true},
|
||||
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
|
||||
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
|
||||
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: true,
|
||||
} as UserSettings;
|
||||
}
|
||||
|
||||
describe('PdfReaderPreferencesComponent', () => {
|
||||
let fixture: ComponentFixture<PdfReaderPreferencesComponent>;
|
||||
let updatePreference: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
updatePreference = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [PdfReaderPreferencesComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: ReaderPreferencesService, useValue: {updatePreference}},
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(PdfReaderPreferencesComponent);
|
||||
fixture.componentInstance.userSettings = createUserSettings();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('reads the current spread and zoom from user settings', () => {
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
expect(component.selectedSpread).toBe('off');
|
||||
expect(component.selectedZoom).toBe('page-fit');
|
||||
});
|
||||
|
||||
it('persists PDF reader preference changes through the shared preferences service', () => {
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component.selectedSpread = 'even';
|
||||
component.selectedZoom = 'page-width';
|
||||
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(1, ['pdfReaderSetting', 'pageSpread'], 'even');
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(2, ['pdfReaderSetting', 'pageZoom'], 'page-width');
|
||||
});
|
||||
});
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {UserService} from '../user-management/user.service';
|
||||
import {ReaderPreferences} from './reader-preferences.component';
|
||||
|
||||
describe('ReaderPreferences', () => {
|
||||
beforeEach(() => {
|
||||
const currentUser = signal({
|
||||
userSettings: {
|
||||
theme: 'sepia',
|
||||
},
|
||||
permissions: {
|
||||
admin: false,
|
||||
canManageFonts: true,
|
||||
},
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: UserService, useValue: {currentUser}},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('hydrates user settings and font management permission from the current user signal', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new ReaderPreferences());
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.userSettings).toEqual({theme: 'sepia'});
|
||||
expect(component.hasFontManagementPermission).toBe(true);
|
||||
});
|
||||
});
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ReaderPreferencesService} from './reader-preferences.service';
|
||||
import {User, UserService, UserSettings} from '../user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
describe('ReaderPreferencesService', () => {
|
||||
function createUserSettings(): UserSettings {
|
||||
return {
|
||||
perBookSetting: {pdf: 'pdf', epub: 'epub', cbx: 'cbx'},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
|
||||
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
|
||||
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
|
||||
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: true,
|
||||
} as UserSettings;
|
||||
}
|
||||
|
||||
it('updates a nested preference and notifies the backend', () => {
|
||||
const userSettings = createUserSettings();
|
||||
const currentUser = signal<User | null>({
|
||||
id: 7,
|
||||
userSettings,
|
||||
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: true,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false,
|
||||
} as unknown as User['permissions'],
|
||||
username: 'reader',
|
||||
name: 'Reader',
|
||||
email: 'reader@example.test',
|
||||
assignedLibraries: [],
|
||||
} as unknown as User);
|
||||
const updateUserSetting = vi.fn();
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn(key => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ReaderPreferencesService,
|
||||
{provide: UserService, useValue: {currentUser, updateUserSetting}},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(ReaderPreferencesService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
service.updatePreference(['ebookReaderSetting', 'fontSize'], 22);
|
||||
|
||||
expect(updateUserSetting).toHaveBeenCalledWith(7, 'ebookReaderSetting', expect.objectContaining({fontSize: 22}));
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'settingsReader.toast.preferencesUpdated',
|
||||
detail: 'settingsReader.toast.preferencesUpdatedDetail',
|
||||
life: 2000
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores updates until the current user is available', () => {
|
||||
const currentUser = signal(null);
|
||||
const updateUserSetting = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ReaderPreferencesService,
|
||||
{provide: UserService, useValue: {currentUser, updateUserSetting}},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: TranslocoService, useValue: {translate: vi.fn()}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(ReaderPreferencesService);
|
||||
|
||||
expect(() => service.updatePreference(['ebookReaderSetting', 'fontSize'], 22)).not.toThrow();
|
||||
expect(updateUserSetting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates missing nested branches before persisting a preference', () => {
|
||||
const userSettings = createUserSettings();
|
||||
const currentUser = signal<User | null>({
|
||||
id: 7,
|
||||
userSettings,
|
||||
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: true,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false,
|
||||
} as unknown as User['permissions'],
|
||||
username: 'reader',
|
||||
name: 'Reader',
|
||||
email: 'reader@example.test',
|
||||
assignedLibraries: [],
|
||||
} as unknown as User);
|
||||
const updateUserSetting = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ReaderPreferencesService,
|
||||
{provide: UserService, useValue: {currentUser, updateUserSetting}},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: TranslocoService, useValue: {translate: vi.fn()}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(ReaderPreferencesService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
service.updatePreference(['ebookReaderSetting', 'advanced', 'fontSize'], 22);
|
||||
|
||||
expect(updateUserSetting).toHaveBeenCalledWith(7, 'ebookReaderSetting', expect.objectContaining({
|
||||
advanced: {fontSize: 22}
|
||||
}));
|
||||
expect(userSettings.ebookReaderSetting).toEqual(expect.objectContaining({
|
||||
advanced: {fontSize: 22}
|
||||
}));
|
||||
});
|
||||
});
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {SettingsApplicationModeComponent} from './settings-application-mode.component';
|
||||
import {ReaderPreferencesService} from '../reader-preferences.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {UserSettings} from '../../user-management/user.service';
|
||||
|
||||
describe('SettingsApplicationModeComponent', () => {
|
||||
function createUserSettings(): UserSettings {
|
||||
return {
|
||||
perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
|
||||
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
|
||||
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
|
||||
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: true,
|
||||
} as UserSettings;
|
||||
}
|
||||
|
||||
let fixture: ComponentFixture<SettingsApplicationModeComponent>;
|
||||
let updatePreference: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
updatePreference = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [SettingsApplicationModeComponent],
|
||||
providers: [
|
||||
{provide: ReaderPreferencesService, useValue: {updatePreference}},
|
||||
{provide: TranslocoService, useValue: {translate: vi.fn((key: string) => key)}},
|
||||
]
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(SettingsApplicationModeComponent);
|
||||
fixture.componentInstance.userSettings = createUserSettings();
|
||||
});
|
||||
|
||||
it('loads preferences and forwards updates for each scope', () => {
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.selectedPdfScope).toBe('Global');
|
||||
expect(component.selectedNewPdfScope).toBe('Global');
|
||||
expect(component.selectedEpubScope).toBe('Individual');
|
||||
expect(component.selectedCbxScope).toBe('Global');
|
||||
|
||||
component.selectedPdfScope = 'Individual';
|
||||
component.selectedNewPdfScope = 'Individual';
|
||||
component.selectedEpubScope = 'Global';
|
||||
component.selectedCbxScope = 'Individual';
|
||||
|
||||
component.onPdfScopeChange();
|
||||
component.onNewPdfScopeChange();
|
||||
component.onEpubScopeChange();
|
||||
component.onCbxScopeChange();
|
||||
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(1, ['perBookSetting', 'pdf'], 'Individual');
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(2, ['perBookSetting', 'newPdf'], 'Individual');
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(3, ['perBookSetting', 'epub'], 'Global');
|
||||
expect(updatePreference).toHaveBeenNthCalledWith(4, ['perBookSetting', 'cbx'], 'Individual');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around route/query-param synchronization,
|
||||
// lazy tab composition, and nested settings child activation so tab selection can be asserted
|
||||
// without mounting the full router-backed settings shell.
|
||||
describe.skip('SettingsComponent', () => {
|
||||
it('needs router seams to verify initial tab resolution and query-param updates', () => {
|
||||
// TODO(seam): Cover activeTab bootstrapping and route synchronization once ActivatedRoute and Router state are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs shell seams to verify tab-switch navigation across the composed settings surface', () => {
|
||||
// TODO(seam): Cover tab click behavior after the routed settings shell is extracted from PrimeNG tab and router outlet runtime concerns.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
import {firstValueFrom, of, throwError} from 'rxjs';
|
||||
|
||||
import {TaskHelperService} from './task-helper.service';
|
||||
import {TaskService, TaskType} from './task.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
describe('TaskHelperService', () => {
|
||||
it('schedules metadata refresh tasks', async () => {
|
||||
const startTask = vi.fn(() => of({type: TaskType.REFRESH_METADATA_MANUAL, status: 'ACCEPTED'}));
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TaskHelperService,
|
||||
{provide: TaskService, useValue: {startTask}},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TaskHelperService);
|
||||
|
||||
await expect(firstValueFrom(service.refreshMetadataTask({libraryIds: [1]} as never))).resolves.toEqual({success: true});
|
||||
expect(startTask).toHaveBeenCalledWith({
|
||||
taskType: TaskType.REFRESH_METADATA_MANUAL,
|
||||
triggeredByCron: false,
|
||||
options: {libraryIds: [1]}
|
||||
});
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'settingsTasks.toast.metadataScheduled',
|
||||
detail: 'settingsTasks.toast.metadataScheduledDetail'
|
||||
});
|
||||
});
|
||||
|
||||
it('maps task conflicts to the already running error toast', async () => {
|
||||
const startTask = vi.fn(() => throwError(() => ({status: 409})));
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TaskHelperService,
|
||||
{provide: TaskService, useValue: {startTask}},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TaskHelperService);
|
||||
|
||||
await expect(firstValueFrom(service.refreshMetadataTask({libraryIds: [1]} as never))).resolves.toEqual({success: false});
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'settingsTasks.toast.alreadyRunning',
|
||||
life: 5000,
|
||||
detail: 'settingsTasks.toast.metadataAlreadyRunningDetail'
|
||||
});
|
||||
});
|
||||
|
||||
it('maps non-conflict failures to the generic error toast', async () => {
|
||||
const startTask = vi.fn(() => throwError(() => ({status: 500})));
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TaskHelperService,
|
||||
{provide: TaskService, useValue: {startTask}},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(TaskHelperService);
|
||||
|
||||
await expect(firstValueFrom(service.refreshMetadataTask({libraryIds: [1]} as never))).resolves.toEqual({success: false});
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'settingsTasks.toast.metadataFailed',
|
||||
life: 5000,
|
||||
detail: 'settingsTasks.toast.metadataFailedDetail'
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,373 @@
|
||||
import {NO_ERRORS_SCHEMA} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Observable, Subject, of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {
|
||||
MetadataReplaceMode,
|
||||
TaskHistory,
|
||||
TaskInfo,
|
||||
TaskProgressPayload,
|
||||
TaskService,
|
||||
TaskStatus,
|
||||
TaskType,
|
||||
} from './task.service';
|
||||
import {TaskManagementComponent} from './task-management.component';
|
||||
|
||||
describe('TaskManagementComponent', () => {
|
||||
let component: TaskManagementComponent;
|
||||
let taskService: {
|
||||
getAvailableTasks: ReturnType<typeof vi.fn>;
|
||||
getLatestTasksForEachType: ReturnType<typeof vi.fn>;
|
||||
taskProgress$: Observable<TaskProgressPayload | null>;
|
||||
startTask: ReturnType<typeof vi.fn>;
|
||||
cancelTask: ReturnType<typeof vi.fn>;
|
||||
updateCronConfig: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let taskProgressSubject: Subject<TaskProgressPayload | null>;
|
||||
let messageService: {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translate: ReturnType<typeof vi.fn>;
|
||||
|
||||
const clearPdfTask: TaskInfo = {
|
||||
taskType: TaskType.CLEAR_PDF_CACHE,
|
||||
name: 'Clear PDF cache',
|
||||
description: 'Clear the cached PDF files.',
|
||||
parallel: false,
|
||||
async: false,
|
||||
cronSupported: true,
|
||||
cronConfig: {
|
||||
id: 7,
|
||||
taskType: TaskType.CLEAR_PDF_CACHE,
|
||||
cronExpression: '0 0 * * * *',
|
||||
enabled: true,
|
||||
options: null,
|
||||
createdAt: '2026-03-27T03:00:00Z',
|
||||
updatedAt: '2026-03-27T03:00:00Z',
|
||||
},
|
||||
metadata: ' cache cleanup ',
|
||||
};
|
||||
|
||||
const refreshMetadataTask: TaskInfo = {
|
||||
taskType: TaskType.REFRESH_LIBRARY_METADATA,
|
||||
name: 'Refresh metadata',
|
||||
description: 'Refresh library metadata.',
|
||||
parallel: false,
|
||||
async: true,
|
||||
cronSupported: false,
|
||||
cronConfig: null,
|
||||
};
|
||||
|
||||
const pendingHistory: TaskHistory = {
|
||||
id: 'task-1',
|
||||
type: TaskType.CLEAR_PDF_CACHE,
|
||||
status: TaskStatus.PENDING,
|
||||
progressPercentage: 10,
|
||||
message: 'working',
|
||||
createdAt: '2026-03-27T03:00:00Z',
|
||||
updatedAt: '2026-03-27T03:01:00Z',
|
||||
completedAt: null,
|
||||
};
|
||||
|
||||
const inProgressHistory: TaskHistory = {
|
||||
...pendingHistory,
|
||||
status: TaskStatus.IN_PROGRESS,
|
||||
updatedAt: '2026-03-27T02:55:00Z',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-03-27T03:06:00Z'));
|
||||
|
||||
taskProgressSubject = new Subject<TaskProgressPayload | null>();
|
||||
translate = vi.fn((key: string, params?: Record<string, unknown>) => (params ? `${key}:${JSON.stringify(params)}` : key));
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
taskService = {
|
||||
getAvailableTasks: vi.fn(() => of([refreshMetadataTask, clearPdfTask])),
|
||||
getLatestTasksForEachType: vi.fn(() => of({
|
||||
taskHistories: [pendingHistory],
|
||||
})),
|
||||
taskProgress$: taskProgressSubject.asObservable(),
|
||||
startTask: vi.fn(() => of({
|
||||
type: TaskType.CLEAR_PDF_CACHE,
|
||||
status: TaskStatus.ACCEPTED,
|
||||
})),
|
||||
cancelTask: vi.fn(() => of({
|
||||
taskId: 'task-1',
|
||||
cancelled: true,
|
||||
message: 'cancelled',
|
||||
})),
|
||||
updateCronConfig: vi.fn(() => of({
|
||||
id: 7,
|
||||
taskType: TaskType.CLEAR_PDF_CACHE,
|
||||
cronExpression: '0 0 * * * *',
|
||||
enabled: true,
|
||||
options: null,
|
||||
createdAt: '2026-03-27T03:00:00Z',
|
||||
updatedAt: '2026-03-27T03:00:00Z',
|
||||
})),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [TaskManagementComponent],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
providers: [
|
||||
{provide: TaskService, useValue: taskService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
],
|
||||
});
|
||||
|
||||
component = TestBed.createComponent(TaskManagementComponent).componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads tasks, sorts them, and attaches latest task histories on init', () => {
|
||||
component.ngOnInit();
|
||||
|
||||
expect(taskService.getAvailableTasks).toHaveBeenCalledTimes(1);
|
||||
expect(taskService.getLatestTasksForEachType).toHaveBeenCalledTimes(1);
|
||||
expect(component.taskInfos.map(task => task.taskType)).toEqual([
|
||||
TaskType.REFRESH_LIBRARY_METADATA,
|
||||
TaskType.CLEAR_PDF_CACHE,
|
||||
]);
|
||||
expect(component.getTaskHistory(TaskType.CLEAR_PDF_CACHE)).toMatchObject({
|
||||
id: 'task-1',
|
||||
status: TaskStatus.PENDING,
|
||||
});
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('reports load failures through the message service', () => {
|
||||
taskService.getAvailableTasks = vi.fn(() => throwError(() => new Error('boom')));
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'common.error',
|
||||
detail: 'settingsTasks.toast.loadError',
|
||||
});
|
||||
});
|
||||
|
||||
it('tracks task progress updates and reloads after a completed task', () => {
|
||||
const loadTasksSpy = vi.spyOn(component, 'loadTasks');
|
||||
|
||||
component.ngOnInit();
|
||||
expect(loadTasksSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
taskProgressSubject.next({
|
||||
taskId: 'task-2',
|
||||
taskType: TaskType.CLEAR_PDF_CACHE,
|
||||
message: 'done',
|
||||
progress: 100,
|
||||
taskStatus: TaskStatus.COMPLETED,
|
||||
});
|
||||
|
||||
expect(component.getTaskHistory(TaskType.CLEAR_PDF_CACHE)).toMatchObject({
|
||||
id: 'task-2',
|
||||
status: TaskStatus.COMPLETED,
|
||||
completedAt: expect.any(String),
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
|
||||
expect(loadTasksSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('distinguishes running, stale, and cancellable tasks', () => {
|
||||
component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, inProgressHistory);
|
||||
|
||||
expect(component.isTaskRunning(TaskType.CLEAR_PDF_CACHE)).toBe(true);
|
||||
expect(component.canCancelTask(inProgressHistory)).toBe(true);
|
||||
expect(component.canExecuteTask(TaskType.CLEAR_PDF_CACHE)).toBe(true);
|
||||
expect(component.isTaskStale(inProgressHistory)).toBe(true);
|
||||
expect(component.getTaskButtonLabel(TaskType.CLEAR_PDF_CACHE)).toBe('settingsTasks.buttons.rerun');
|
||||
|
||||
component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, {
|
||||
...inProgressHistory,
|
||||
updatedAt: '2026-03-27T03:05:45Z',
|
||||
});
|
||||
|
||||
expect(component.isTaskStale(component.getTaskHistory(TaskType.CLEAR_PDF_CACHE))).toBe(false);
|
||||
expect(component.canExecuteTask(TaskType.CLEAR_PDF_CACHE)).toBe(false);
|
||||
expect(component.getTaskButtonLabel(TaskType.CLEAR_PDF_CACHE)).toBe('settingsTasks.buttons.run');
|
||||
});
|
||||
|
||||
it('blocks duplicate task execution when the task is still fresh', () => {
|
||||
component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, {
|
||||
...inProgressHistory,
|
||||
updatedAt: '2026-03-27T03:05:45Z',
|
||||
});
|
||||
|
||||
component.runTask(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
expect(taskService.startTask).not.toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'settingsTasks.toast.alreadyRunning',
|
||||
detail: 'settingsTasks.toast.alreadyRunningDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('queues async metadata refresh tasks with the selected replace mode', () => {
|
||||
component.selectedMetadataReplaceMode = MetadataReplaceMode.REPLACE_ALL;
|
||||
|
||||
component.runTask(TaskType.REFRESH_LIBRARY_METADATA);
|
||||
|
||||
expect(taskService.startTask).toHaveBeenCalledWith({
|
||||
taskType: TaskType.REFRESH_LIBRARY_METADATA,
|
||||
triggeredByCron: false,
|
||||
options: {
|
||||
metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL,
|
||||
},
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'settingsTasks.toast.taskQueued',
|
||||
detail: 'settingsTasks.toast.taskQueuedDetail:{"name":"Refresh Library Metadata"}',
|
||||
});
|
||||
});
|
||||
|
||||
it('reports sync task completion and failure outcomes', () => {
|
||||
component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, {
|
||||
...pendingHistory,
|
||||
status: TaskStatus.COMPLETED,
|
||||
completedAt: '2026-03-27T03:05:50Z',
|
||||
updatedAt: '2026-03-27T03:05:50Z',
|
||||
});
|
||||
taskService.startTask = vi.fn(() => of({
|
||||
type: TaskType.CLEAR_PDF_CACHE,
|
||||
status: TaskStatus.COMPLETED,
|
||||
}));
|
||||
component.runTask(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'settingsTasks.toast.taskCompleted',
|
||||
detail: 'settingsTasks.toast.taskCompletedDetail:{"name":"Clear Pdf Cache"}',
|
||||
});
|
||||
|
||||
messageService.add.mockClear();
|
||||
component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, {
|
||||
...pendingHistory,
|
||||
status: TaskStatus.COMPLETED,
|
||||
completedAt: '2026-03-27T03:05:55Z',
|
||||
updatedAt: '2026-03-27T03:05:55Z',
|
||||
});
|
||||
taskService.startTask = vi.fn(() => of({
|
||||
type: TaskType.CLEAR_PDF_CACHE,
|
||||
status: TaskStatus.FAILED,
|
||||
message: 'nope',
|
||||
}));
|
||||
component.runTask(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'settingsTasks.toast.taskFailed',
|
||||
detail: 'nope',
|
||||
});
|
||||
});
|
||||
|
||||
it('cancels tasks and handles both success and failure paths', () => {
|
||||
component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, pendingHistory);
|
||||
component.cancelTask(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
expect(taskService.cancelTask).toHaveBeenCalledWith('task-1');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'settingsTasks.toast.taskCancelled',
|
||||
detail: 'cancelled',
|
||||
});
|
||||
|
||||
messageService.add.mockClear();
|
||||
taskService.cancelTask = vi.fn(() => of({
|
||||
taskId: 'task-1',
|
||||
cancelled: false,
|
||||
message: 'busy',
|
||||
}));
|
||||
component.cancelTask(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'settingsTasks.toast.cancelFailed',
|
||||
detail: 'busy',
|
||||
});
|
||||
});
|
||||
|
||||
it('validates cron expressions and saves trimmed updates', () => {
|
||||
component.taskInfos = [clearPdfTask];
|
||||
|
||||
component.startEditingCron(TaskType.CLEAR_PDF_CACHE);
|
||||
expect(component.isEditingCron(TaskType.CLEAR_PDF_CACHE)).toBe(true);
|
||||
expect(component.editingCronExpression).toBe('0 0 * * * *');
|
||||
|
||||
component.editingCronExpression = '*/5 0-23 * * ? 0';
|
||||
component.onCronExpressionChange();
|
||||
expect(component.cronValidationError).toBeNull();
|
||||
|
||||
component.editingCronExpression = 'invalid';
|
||||
component.onCronExpressionChange();
|
||||
expect(component.cronValidationError).toBe('settingsTasks.cron.validationPrefix');
|
||||
|
||||
component.saveCronExpression(TaskType.CLEAR_PDF_CACHE);
|
||||
expect(taskService.updateCronConfig).not.toHaveBeenCalled();
|
||||
|
||||
component.editingCronExpression = ' 0 15 * * * * ';
|
||||
component.onCronExpressionChange();
|
||||
component.saveCronExpression(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
expect(taskService.updateCronConfig).toHaveBeenCalledWith(TaskType.CLEAR_PDF_CACHE, {
|
||||
cronExpression: '0 15 * * * *',
|
||||
});
|
||||
expect(component.isEditingCron(TaskType.CLEAR_PDF_CACHE)).toBe(false);
|
||||
expect(component.cronValidationError).toBeNull();
|
||||
});
|
||||
|
||||
it('updates cron state and exposes helper text and metadata helpers', () => {
|
||||
component.taskInfos = [clearPdfTask];
|
||||
component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, {
|
||||
...pendingHistory,
|
||||
status: TaskStatus.COMPLETED,
|
||||
completedAt: '2026-03-27T03:05:50Z',
|
||||
updatedAt: '2026-03-27T03:05:50Z',
|
||||
});
|
||||
|
||||
component.toggleCronEnabled(TaskType.CLEAR_PDF_CACHE);
|
||||
expect(taskService.updateCronConfig).toHaveBeenCalledWith(TaskType.CLEAR_PDF_CACHE, {
|
||||
enabled: false,
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'common.success',
|
||||
detail: 'settingsTasks.cron.updateSuccess',
|
||||
});
|
||||
|
||||
expect(component.getCronConfig(TaskType.CLEAR_PDF_CACHE)).toEqual({
|
||||
enabled: true,
|
||||
cronExpression: '0 0 * * * *',
|
||||
});
|
||||
expect(component.getMetadataReplaceDescription(MetadataReplaceMode.REPLACE_ALL)).toBe('settingsTasks.metadataReplace.replaceAllDesc');
|
||||
expect(component.getMetadataReplaceDescription(MetadataReplaceMode.REPLACE_MISSING)).toBe('settingsTasks.metadataReplace.replaceMissingDesc');
|
||||
expect(component.getTaskDisplayName(TaskType.CLEAR_PDF_CACHE)).toBe('Clear PDF cache');
|
||||
expect(component.getTaskDescription(TaskType.CLEAR_PDF_CACHE)).toBe('Clear the cached PDF files.');
|
||||
expect(component.getTaskLabel(TaskType.CLEAR_PDF_CACHE)).toBe('8. Clear PDF cache');
|
||||
expect(component.getTaskIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi-database');
|
||||
expect(component.getMetadataIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi-database');
|
||||
expect(component.hasMetadata(TaskType.CLEAR_PDF_CACHE)).toBe(true);
|
||||
expect(component.getLastRunMessage(TaskType.CLEAR_PDF_CACHE)).toBe('settingsTasks.status.justNow');
|
||||
expect(component.getLastRunInfoClass(TaskType.CLEAR_PDF_CACHE)).toBe('success');
|
||||
expect(component.getTaskButtonIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi pi-database');
|
||||
expect(component.getCancelButtonIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi pi-times');
|
||||
expect(component.formatDate('2026-03-27T03:00:00Z')).toContain('2026');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
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 {firstValueFrom} from 'rxjs';
|
||||
import {skip} from 'rxjs/operators';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MetadataReplaceMode, TaskService, TaskStatus, TaskType} from './task.service';
|
||||
|
||||
describe('TaskService', () => {
|
||||
let service: TaskService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
TaskService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(TaskService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads available tasks', async () => {
|
||||
const resultPromise = firstValueFrom(service.getAvailableTasks());
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([{taskType: TaskType.CLEAR_PDF_CACHE, name: 'Clear cache', description: 'desc', parallel: false, async: false, cronSupported: false, cronConfig: null}]);
|
||||
|
||||
await expect(resultPromise).resolves.toEqual([{taskType: TaskType.CLEAR_PDF_CACHE, name: 'Clear cache', description: 'desc', parallel: false, async: false, cronSupported: false, cronConfig: null}]);
|
||||
});
|
||||
|
||||
it('starts tasks with the provided options', async () => {
|
||||
const requestPromise = firstValueFrom(service.startTask({
|
||||
taskType: TaskType.REFRESH_METADATA_MANUAL,
|
||||
options: {metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL}
|
||||
}));
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/start`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({
|
||||
taskType: TaskType.REFRESH_METADATA_MANUAL,
|
||||
options: {metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL}
|
||||
});
|
||||
request.flush({type: TaskType.REFRESH_METADATA_MANUAL, status: TaskStatus.ACCEPTED});
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({type: TaskType.REFRESH_METADATA_MANUAL, status: TaskStatus.ACCEPTED});
|
||||
});
|
||||
|
||||
it('loads the latest task for each type', async () => {
|
||||
const requestPromise = firstValueFrom(service.getLatestTasksForEachType());
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/last`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({taskHistories: []});
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({taskHistories: []});
|
||||
});
|
||||
|
||||
it('cancels tasks', async () => {
|
||||
const requestPromise = firstValueFrom(service.cancelTask('task-1'));
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/task-1/cancel`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush({taskId: 'task-1', cancelled: true, message: 'done'});
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({taskId: 'task-1', cancelled: true, message: 'done'});
|
||||
});
|
||||
|
||||
it('updates cron config', async () => {
|
||||
const requestPromise = firstValueFrom(service.updateCronConfig('task-type', {cronExpression: '0 0 * * *', enabled: true}));
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/task-type/cron`);
|
||||
expect(request.request.method).toBe('PATCH');
|
||||
expect(request.request.body).toEqual({cronExpression: '0 0 * * *', enabled: true});
|
||||
request.flush({id: 1, taskType: 'task-type', cronExpression: '0 0 * * *', enabled: true, options: null, createdAt: null, updatedAt: null});
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({id: 1, taskType: 'task-type', cronExpression: '0 0 * * *', enabled: true, options: null, createdAt: null, updatedAt: null});
|
||||
});
|
||||
|
||||
it('publishes task progress updates', async () => {
|
||||
const progressPromise = firstValueFrom(service.taskProgress$.pipe(skip(1)));
|
||||
|
||||
service.handleTaskProgress({taskId: 'task-1', taskType: 'refresh', message: 'working', progress: 25, taskStatus: TaskStatus.IN_PROGRESS});
|
||||
|
||||
await expect(progressPromise).resolves.toEqual({taskId: 'task-1', taskType: 'refresh', message: 'working', progress: 25, taskStatus: TaskStatus.IN_PROGRESS});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {
|
||||
AGE_RATING_OPTIONS,
|
||||
CONTENT_RATINGS,
|
||||
ContentRating,
|
||||
ContentRestriction,
|
||||
ContentRestrictionMode,
|
||||
ContentRestrictionType
|
||||
} from './content-restriction.model';
|
||||
|
||||
describe('content-restriction.model', () => {
|
||||
it('exposes supported restriction enums and derived content ratings', () => {
|
||||
expect(ContentRestrictionType.CATEGORY).toBe('CATEGORY');
|
||||
expect(ContentRestrictionMode.ALLOW_ONLY).toBe('ALLOW_ONLY');
|
||||
expect(CONTENT_RATINGS).toEqual(Object.values(ContentRating));
|
||||
});
|
||||
|
||||
it('defines age rating options in ascending order', () => {
|
||||
expect(AGE_RATING_OPTIONS[0]).toEqual({value: '0', label: 'All Ages'});
|
||||
expect(AGE_RATING_OPTIONS.at(-1)).toEqual({value: '21', label: '21+'});
|
||||
});
|
||||
|
||||
it('supports persisted restriction records', () => {
|
||||
const restriction: ContentRestriction = {
|
||||
id: 1,
|
||||
userId: 99,
|
||||
restrictionType: ContentRestrictionType.TAG,
|
||||
mode: ContentRestrictionMode.EXCLUDE,
|
||||
value: 'spoilers',
|
||||
createdAt: '2026-03-26T10:00:00Z'
|
||||
};
|
||||
|
||||
expect(restriction.value).toBe('spoilers');
|
||||
expect(restriction.mode).toBe(ContentRestrictionMode.EXCLUDE);
|
||||
});
|
||||
});
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
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 {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {ContentRestriction, ContentRestrictionMode, ContentRestrictionType} from './content-restriction.model';
|
||||
import {ContentRestrictionService} from './content-restriction.service';
|
||||
|
||||
describe('ContentRestrictionService', () => {
|
||||
let service: ContentRestrictionService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
ContentRestrictionService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(ContentRestrictionService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads content restrictions', () => {
|
||||
const restrictions = [{
|
||||
id: 1,
|
||||
userId: 11,
|
||||
restrictionType: ContentRestrictionType.TAG,
|
||||
mode: ContentRestrictionMode.EXCLUDE,
|
||||
value: 'TAG'
|
||||
} as ContentRestriction];
|
||||
|
||||
service.getUserRestrictions(11).subscribe(result => {
|
||||
expect(result).toEqual(restrictions);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(restrictions);
|
||||
});
|
||||
|
||||
it('adds a restriction', () => {
|
||||
const restriction = {
|
||||
id: 1,
|
||||
userId: 11,
|
||||
restrictionType: ContentRestrictionType.TAG,
|
||||
mode: ContentRestrictionMode.EXCLUDE,
|
||||
value: 'TAG'
|
||||
} as ContentRestriction;
|
||||
|
||||
service.addRestriction(11, restriction).subscribe(result => {
|
||||
expect(result).toEqual(restriction);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(restriction);
|
||||
request.flush(restriction);
|
||||
});
|
||||
|
||||
it('updates restrictions', () => {
|
||||
const restrictions = [{
|
||||
id: 1,
|
||||
userId: 11,
|
||||
restrictionType: ContentRestrictionType.TAG,
|
||||
mode: ContentRestrictionMode.EXCLUDE,
|
||||
value: 'TAG'
|
||||
} as ContentRestriction];
|
||||
|
||||
service.updateRestrictions(11, restrictions).subscribe(result => {
|
||||
expect(result).toEqual(restrictions);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`);
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual(restrictions);
|
||||
request.flush(restrictions);
|
||||
});
|
||||
|
||||
it('deletes a single restriction', () => {
|
||||
service.deleteRestriction(11, 9).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions/9`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('deletes all restrictions for a user', () => {
|
||||
service.deleteAllRestrictions(11).subscribe(result => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around metadata-derived option lists,
|
||||
// restriction-service mutations, and translated message flows so restriction editing can be
|
||||
// asserted without mounting the full editable select stack.
|
||||
describe.skip('ContentRestrictionsEditorComponent', () => {
|
||||
it('needs metadata seams to verify option derivation, type-label helpers, and allow versus exclude grouping', () => {
|
||||
// TODO(seam): Cover getValueOptions and the grouping helpers once the computed metadata signal is isolated for direct assertions.
|
||||
});
|
||||
|
||||
it('needs mutation seams to verify loading, duplicate prevention, and add and remove restriction flows', () => {
|
||||
// TODO(seam): Cover loadRestrictions, addRestriction, and removeRestriction after extracting service and toast side effects behind test doubles.
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around the large reactive form, admin
|
||||
// permission fan-out side effects, and dialog-close behavior so the create-user workflow can be
|
||||
// tested without mounting the full Prime form stack.
|
||||
describe.skip('CreateUserDialogComponent', () => {
|
||||
it('needs form seams to verify validator setup, admin permission propagation, and library selection shaping', () => {
|
||||
// TODO(seam): Cover ngOnInit once the reactive-form and valueChanges runtime is isolated for deterministic assertions.
|
||||
});
|
||||
|
||||
it('needs mutation seams to verify invalid-form warnings and create-user success and failure flows', () => {
|
||||
// TODO(seam): Cover createUser after extracting message and dialog-close side effects behind test doubles.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around table row editing, confirm dialog
|
||||
// usage, password dialog state, and dialog-launcher interactions so user administration can be
|
||||
// exercised without building the full Prime table and modal stack.
|
||||
describe.skip('UserManagementComponent', () => {
|
||||
it('needs service seams to verify user loading, edit toggling, and save payload shaping', () => {
|
||||
// TODO(seam): Cover loadUsers, toggleEdit, and saveUser once the table-editing state and async user-service flows are isolated.
|
||||
});
|
||||
|
||||
it('needs dialog seams to verify create-user refresh, delete confirmation, and password-change validation', () => {
|
||||
// TODO(seam): Cover openCreateUserDialog, deleteUser, and submitPasswordChange after extracting confirm and modal runtime concerns.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {CURRENT_USER_QUERY_KEY} from './user-query-keys';
|
||||
|
||||
describe('user-query-keys', () => {
|
||||
it('uses a stable cache key for the current user record', () => {
|
||||
expect(CURRENT_USER_QUERY_KEY).toEqual(['currentUser']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
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 {UserStatsService} from './user-stats.service';
|
||||
|
||||
describe('UserStatsService', () => {
|
||||
let service: UserStatsService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
UserStatsService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(UserStatsService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('requests the yearly heatmap with the year query param', () => {
|
||||
let result: unknown;
|
||||
service.getHeatmapForYear(2026).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/user-stats/reading/heatmap')
|
||||
&& req.params.get('year') === '2026'
|
||||
);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([{date: '2026-03-26', count: 3}]);
|
||||
|
||||
expect(result).toEqual([{date: '2026-03-26', count: 3}]);
|
||||
});
|
||||
|
||||
it('requests the weekly reading timeline with both year and week params', () => {
|
||||
service.getTimelineForWeek(2026, 13).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/user-stats/reading/timeline')
|
||||
&& req.params.get('year') === '2026'
|
||||
&& req.params.get('week') === '13'
|
||||
);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('omits optional params when requesting favorite days without filters', () => {
|
||||
service.getFavoriteDays().subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/user-stats/reading/favorite-days')
|
||||
);
|
||||
expect(request.request.params.keys()).toEqual([]);
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('includes optional params for peak hours when year and month are provided', () => {
|
||||
service.getPeakHours(2026, 3).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/user-stats/reading/peak-hours')
|
||||
&& req.params.get('year') === '2026'
|
||||
&& req.params.get('month') === '3'
|
||||
);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('requests the remaining stats endpoints with the expected URLs', () => {
|
||||
service.getGenreStats().subscribe();
|
||||
service.getCompletionTimelineForYear(2026).subscribe();
|
||||
service.getPageTurnerScores().subscribe();
|
||||
service.getCompletionRace(2026).subscribe();
|
||||
service.getReadingDates().subscribe();
|
||||
service.getSessionScatter(2026).subscribe();
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/user-stats/reading/genres')).flush([]);
|
||||
httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/user-stats/reading/completion-timeline')
|
||||
&& req.params.get('year') === '2026'
|
||||
).flush([]);
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/user-stats/reading/page-turner-scores')).flush([]);
|
||||
httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/user-stats/reading/completion-race')
|
||||
&& req.params.get('year') === '2026'
|
||||
).flush([]);
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/user-stats/reading/dates')).flush([]);
|
||||
httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('/api/v1/user-stats/reading/session-scatter')
|
||||
&& req.params.get('year') === '2026'
|
||||
).flush([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
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 {CURRENT_USER_QUERY_KEY} from './user-query-keys';
|
||||
import {type User, type UserSettings, UserService} from './user.service';
|
||||
|
||||
type BuildUserOverrides = Omit<Partial<User>, 'permissions' | 'userSettings'> & {
|
||||
permissions?: Partial<User['permissions']>;
|
||||
userSettings?: Partial<UserSettings>;
|
||||
};
|
||||
|
||||
function buildUserSettings(overrides: Partial<UserSettings> = {}): UserSettings {
|
||||
return {
|
||||
perBookSetting: {pdf: 'pdf', epub: 'epub', cbx: 'cbx'},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
|
||||
epubReaderSetting: {
|
||||
theme: 'light',
|
||||
font: 'serif',
|
||||
fontSize: 16,
|
||||
flow: 'paginated',
|
||||
spread: 'auto',
|
||||
lineHeight: 1.5,
|
||||
margin: 1,
|
||||
letterSpacing: 0,
|
||||
},
|
||||
ebookReaderSetting: {
|
||||
lineHeight: 1.5,
|
||||
justify: true,
|
||||
hyphenate: true,
|
||||
maxColumnCount: 1,
|
||||
gap: 1,
|
||||
fontSize: 16,
|
||||
theme: 'light',
|
||||
maxInlineSize: 100,
|
||||
maxBlockSize: 100,
|
||||
fontFamily: 'serif',
|
||||
isDark: false,
|
||||
flow: 'paginated',
|
||||
},
|
||||
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'ASC',
|
||||
view: 'GRID',
|
||||
coverSize: 100,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: false,
|
||||
},
|
||||
overrides: [],
|
||||
},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: true,
|
||||
...overrides,
|
||||
} as UserSettings;
|
||||
}
|
||||
|
||||
function buildUser(overrides: BuildUserOverrides = {}): User {
|
||||
const {permissions: permissionOverrides, userSettings, ...userOverrides} = overrides;
|
||||
const permissions: User['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,
|
||||
canBulkResetGrimmoryReadProgress: false,
|
||||
canBulkResetBookloreReadProgress: false,
|
||||
canBulkResetKoReaderReadProgress: false,
|
||||
canBulkResetBookReadStatus: false,
|
||||
};
|
||||
|
||||
if (permissionOverrides) {
|
||||
Object.assign(permissions, permissionOverrides);
|
||||
}
|
||||
|
||||
return {
|
||||
id: 7,
|
||||
username: 'reader',
|
||||
name: 'Reader',
|
||||
email: 'reader@example.test',
|
||||
assignedLibraries: [],
|
||||
permissions,
|
||||
userSettings: buildUserSettings(userSettings),
|
||||
...userOverrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function flushCurrentUserQuery(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
flushSignalAndQueryEffects();
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
}
|
||||
|
||||
describe('UserService', () => {
|
||||
let service: UserService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
|
||||
beforeEach(() => {
|
||||
authService = createAuthServiceStub();
|
||||
queryClientHarness = createQueryClientHarness();
|
||||
queryClientHarness.queryClient.setDefaultOptions({
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...queryClientHarness.providers,
|
||||
UserService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(UserService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
flushSignalAndQueryEffects();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClientHarness.queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('eagerly fetches /users/me and normalizes the permission alias into current-user state', async () => {
|
||||
expect(service.currentUser()).toBeNull();
|
||||
expect(service.isUserLoading()).toBe(true);
|
||||
expect(service.userError()).toBeNull();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush(buildUser({
|
||||
permissions: {
|
||||
canBulkResetGrimmoryReadProgress: undefined,
|
||||
canBulkResetBookloreReadProgress: true,
|
||||
},
|
||||
}));
|
||||
await flushCurrentUserQuery();
|
||||
|
||||
expect(service.currentUser()).toEqual(expect.objectContaining({
|
||||
id: 7,
|
||||
username: 'reader',
|
||||
}));
|
||||
expect(service.currentUser()?.permissions.canBulkResetGrimmoryReadProgress).toBe(true);
|
||||
expect(service.currentUser()?.permissions.canBulkResetBookloreReadProgress).toBe(true);
|
||||
expect(service.isUserLoading()).toBe(false);
|
||||
expect(service.userError()).toBeNull();
|
||||
});
|
||||
|
||||
it('derives a query error when the eager current-user request fails', async () => {
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me'));
|
||||
request.flush({message: 'boom'}, {status: 500, statusText: 'Server Error'});
|
||||
await flushCurrentUserQuery();
|
||||
|
||||
expect(service.currentUser()).toBeNull();
|
||||
expect(service.isUserLoading()).toBe(false);
|
||||
expect(service.userError()).toBe('Failed to load user');
|
||||
});
|
||||
|
||||
it('removes the current-user cache when the auth token is cleared', async () => {
|
||||
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries');
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me')).flush(buildUser());
|
||||
await flushCurrentUserQuery();
|
||||
expect(queryClientHarness.queryClient.getQueryData(CURRENT_USER_QUERY_KEY)).toEqual(expect.objectContaining({id: 7}));
|
||||
|
||||
authService.token.set(null);
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: CURRENT_USER_QUERY_KEY});
|
||||
expect(queryClientHarness.queryClient.getQueryData(CURRENT_USER_QUERY_KEY)).toBeUndefined();
|
||||
expect(service.currentUser()).toBeNull();
|
||||
expect(service.isUserLoading()).toBe(false);
|
||||
expect(service.userError()).toBeNull();
|
||||
});
|
||||
|
||||
it('updates the cached current user after updateUserSetting succeeds', async () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me')).flush(buildUser());
|
||||
await flushCurrentUserQuery();
|
||||
service.setInitialUser(buildUser({
|
||||
id: 21,
|
||||
userSettings: buildUserSettings({filterMode: 'and'}),
|
||||
}));
|
||||
await flushCurrentUserQuery();
|
||||
|
||||
service.updateUserSetting(21, 'filterMode', 'or');
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/21/settings'));
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual({key: 'filterMode', value: 'or'});
|
||||
expect(request.request.headers.get('Content-Type')).toBe('application/json');
|
||||
request.flush('');
|
||||
await flushCurrentUserQuery();
|
||||
|
||||
expect(service.currentUser()?.userSettings.filterMode).toBe('or');
|
||||
expect(queryClientHarness.queryClient.getQueryData<User>(CURRENT_USER_QUERY_KEY)).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 21,
|
||||
userSettings: expect.objectContaining({filterMode: 'or'}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around the user-service signal effect,
|
||||
// PrimeNG password controls, and toast/dialog side effects so profile edit and password-change
|
||||
// branches can be asserted without mounting the full dialog runtime.
|
||||
describe.skip('UserProfileDialogComponent', () => {
|
||||
it('needs user-signal seams to verify profile bootstrap, edit toggling, no-change exits, and update failures', () => {
|
||||
// TODO(seam): Cover resetEditForm and updateProfile after the current-user signal and updateUser observable can be driven through deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs form and dialog seams to verify password validation, password-change outcomes, and close behavior', () => {
|
||||
// TODO(seam): Cover passwordMatchValidator, submitPasswordChange, and closeDialog after the password inputs and message service are isolated behind a stable test harness.
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around signal-backed user-preference
|
||||
// hydration, drag/drop reorder behavior, and PrimeNG selection widgets so filter persistence can
|
||||
// be asserted without the full view-preferences runtime.
|
||||
describe.skip('FilterPreferencesComponent', () => {
|
||||
it('needs preference seams to verify bootstrap, reset, and save behavior for filter visibility state', () => {
|
||||
// TODO(seam): Cover the effect-driven settings sync once user preferences can be injected through deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs drag/drop seams to verify ordering and selection changes without CDK/PrimeNG widget runtime coupling', () => {
|
||||
// TODO(seam): Cover reorder and toggle flows after the drag-drop and pick-list interactions are isolated behind a testable adapter.
|
||||
});
|
||||
});
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of} from 'rxjs';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {MetaCenterViewModeComponent} from './meta-center-view-mode-component';
|
||||
import {User, UserService} from '../../user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
describe('MetaCenterViewModeComponent', () => {
|
||||
function createUser(preferences: Partial<User['userSettings']> = {}): User {
|
||||
return {
|
||||
id: 7,
|
||||
userSettings: {
|
||||
metadataCenterViewMode: 'dialog',
|
||||
enableSeriesView: true,
|
||||
perBookSetting: {pdf: 'Global', epub: 'Global', cbx: 'Global'},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
|
||||
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
|
||||
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
|
||||
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: true,
|
||||
...preferences,
|
||||
},
|
||||
permissions: {admin: false, canManageFonts: true},
|
||||
username: 'reader',
|
||||
name: 'Reader',
|
||||
email: 'reader@example.test',
|
||||
assignedLibraries: [],
|
||||
} as unknown as User;
|
||||
}
|
||||
|
||||
it('hydrates preferences from the current user and persists changes', () => {
|
||||
const currentUser = signal<User | null>(null);
|
||||
const updateUserSetting = vi.fn();
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string) => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [MetaCenterViewModeComponent],
|
||||
providers: [
|
||||
{provide: UserService, useValue: {currentUser, getCurrentUser: vi.fn(() => currentUser()), updateUserSetting}},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {
|
||||
translate,
|
||||
config: {reRenderOnLangChange: false},
|
||||
langChanges$: of('en'),
|
||||
_loadDependencies: vi.fn(() => of([])),
|
||||
}},
|
||||
]
|
||||
});
|
||||
|
||||
currentUser.set(createUser());
|
||||
|
||||
const fixture = TestBed.createComponent(MetaCenterViewModeComponent);
|
||||
fixture.detectChanges();
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
expect(component.viewMode).toBe('dialog');
|
||||
expect(component.seriesViewMode).toBe(true);
|
||||
|
||||
component.onViewModeChange('route');
|
||||
component.onSeriesViewModeChange(false);
|
||||
|
||||
expect(updateUserSetting).toHaveBeenNthCalledWith(1, 7, 'metadataCenterViewMode', 'route');
|
||||
expect(updateUserSetting).toHaveBeenNthCalledWith(2, 7, 'enableSeriesView', false);
|
||||
expect(messageAdd).toHaveBeenNthCalledWith(1, {
|
||||
severity: 'success',
|
||||
summary: 'settingsView.metaCenter.prefsUpdated',
|
||||
detail: 'settingsView.metaCenter.metaCenterSaved',
|
||||
life: 1500,
|
||||
});
|
||||
expect(messageAdd).toHaveBeenNthCalledWith(2, {
|
||||
severity: 'success',
|
||||
summary: 'settingsView.metaCenter.prefsUpdated',
|
||||
detail: 'settingsView.metaCenter.seriesViewSaved',
|
||||
life: 1500,
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores save attempts until a user is available', () => {
|
||||
const currentUser = signal<User | null>(null);
|
||||
const updateUserSetting = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [MetaCenterViewModeComponent],
|
||||
providers: [
|
||||
{provide: UserService, useValue: {currentUser, getCurrentUser: vi.fn(() => null), updateUserSetting}},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: TranslocoService, useValue: {
|
||||
translate: vi.fn(),
|
||||
config: {reRenderOnLangChange: false},
|
||||
langChanges$: of('en'),
|
||||
_loadDependencies: vi.fn(() => of([])),
|
||||
}},
|
||||
]
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(MetaCenterViewModeComponent);
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component.onViewModeChange('dialog');
|
||||
component.onSeriesViewModeChange(true);
|
||||
|
||||
expect(updateUserSetting).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {User, UserService, UserSettings} from '../../user-management/user.service';
|
||||
import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences.component';
|
||||
|
||||
function createUserSettings(): UserSettings {
|
||||
return {
|
||||
perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
|
||||
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
|
||||
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
|
||||
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
|
||||
sidebarLibrarySorting: {field: 'name', order: 'asc'},
|
||||
sidebarShelfSorting: {field: 'id', order: 'desc'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'desc'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: true,
|
||||
} as UserSettings;
|
||||
}
|
||||
|
||||
function createUser(): User {
|
||||
return {
|
||||
id: 9,
|
||||
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: createUserSettings(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('SidebarSortingPreferencesComponent', () => {
|
||||
let fixture: ComponentFixture<SidebarSortingPreferencesComponent>;
|
||||
let updateUserSetting: ReturnType<typeof vi.fn>;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
updateUserSetting = vi.fn();
|
||||
messageService = {add: vi.fn()};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [SidebarSortingPreferencesComponent, getTranslocoModule({translocoConfig: {reRenderOnLangChange: false}})],
|
||||
providers: [
|
||||
{provide: UserService, useValue: {currentUser: signal(createUser()), updateUserSetting}},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(SidebarSortingPreferencesComponent);
|
||||
TestBed.flushEffects();
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('hydrates sidebar sorting selections from the current user', () => {
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
expect(component.selectedLibrarySorting).toEqual({field: 'name', order: 'asc'});
|
||||
expect(component.selectedShelfSorting).toEqual({field: 'id', order: 'desc'});
|
||||
expect(component.sortingOptions).not.toHaveLength(0);
|
||||
});
|
||||
|
||||
it('persists library sorting changes and shows a success toast', () => {
|
||||
const component = fixture.componentInstance;
|
||||
component.selectedLibrarySorting = {field: 'id', order: 'asc'};
|
||||
|
||||
component.onLibrarySortingChange();
|
||||
|
||||
expect(updateUserSetting).toHaveBeenCalledWith(9, 'sidebarLibrarySorting', {field: 'id', order: 'asc'});
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
});
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ViewPreferencesParentComponent} from './view-preferences-parent.component';
|
||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
describe('ViewPreferencesParentComponent', () => {
|
||||
it('loads and saves the sidebar width', () => {
|
||||
const localStorageGet = vi.fn(() => 312);
|
||||
const localStorageSet = vi.fn();
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn(key => key);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ViewPreferencesParentComponent],
|
||||
providers: [
|
||||
{provide: LocalStorageService, useValue: {get: localStorageGet, set: localStorageSet}},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(ViewPreferencesParentComponent);
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component.ngOnInit();
|
||||
expect(component.sidebarWidth).toBe(312);
|
||||
|
||||
component.saveSidebarWidth();
|
||||
|
||||
expect(localStorageSet).toHaveBeenCalledWith('sidebarWidth', 312);
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'settingsView.layout.saved',
|
||||
detail: 'settingsView.layout.savedDetail'
|
||||
});
|
||||
});
|
||||
|
||||
it('updates the sidebar CSS variable when the width changes', () => {
|
||||
const localStorageGet = vi.fn(() => 225);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ViewPreferencesParentComponent],
|
||||
providers: [
|
||||
{provide: LocalStorageService, useValue: {get: localStorageGet, set: vi.fn()}},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: TranslocoService, useValue: {translate: vi.fn()}},
|
||||
]
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(ViewPreferencesParentComponent);
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component.sidebarWidth = 287;
|
||||
component.onSidebarWidthChange();
|
||||
|
||||
expect(document.documentElement.style.getPropertyValue('--sidebar-width')).toBe('287px');
|
||||
});
|
||||
|
||||
it('falls back to the default width when no value is stored', () => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ViewPreferencesParentComponent],
|
||||
providers: [
|
||||
{provide: LocalStorageService, useValue: {get: vi.fn(() => null), set: vi.fn()}},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: TranslocoService, useValue: {translate: vi.fn()}},
|
||||
]
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(ViewPreferencesParentComponent);
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.sidebarWidth).toBe(225);
|
||||
});
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around effect-driven user hydration,
|
||||
// multiple live collection services, drag-drop ordering, and popover-driven multi-sort editing so
|
||||
// preference persistence can be asserted without booting the full settings surface.
|
||||
describe.skip('ViewPreferencesComponent', () => {
|
||||
it('needs collection and drag-drop seams to verify global and override preference persistence deterministically', () => {
|
||||
// TODO(seam): Cover visible-sort-field ordering, override creation, and auto-save interactions after the collection/popover flows are isolated.
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user