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,17 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Honest coverage for this component needs a PrimeNG FileUpload host seam,
|
||||
// controllable library/settings signals, and a stable upload-progress harness for `HttpRequest`
|
||||
// event streams and dialog close behavior. The current surface mixes view-child state, effects,
|
||||
// progress events, and UI messaging too tightly for a reliable low-noise unit spec tonight.
|
||||
describe.skip('BookUploaderComponent', () => {
|
||||
it('needs a file-upload seam to verify destination validation, duplicate filtering, and size failures', () => {
|
||||
// TODO(seam): Cover file selection and validation after the PrimeNG file chooser state is
|
||||
// wrapped behind a testable adapter instead of relying on the live FileUpload view child.
|
||||
});
|
||||
|
||||
it('needs an upload-progress seam to verify request batching, status transitions, and bookdrop close behavior', () => {
|
||||
// TODO(seam): Cover progress updates and terminal states once upload event streams can be
|
||||
// driven without coupling the spec to the full PrimeNG/http runtime.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {AuthService} from '../../service/auth.service';
|
||||
import {ChangePasswordComponent} from './change-password.component';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
describe('ChangePasswordComponent', () => {
|
||||
let fixture: ComponentFixture<ChangePasswordComponent>;
|
||||
let component: ChangePasswordComponent;
|
||||
let userService: {changePassword: ReturnType<typeof vi.fn>};
|
||||
let authService: {logout: ReturnType<typeof vi.fn>};
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let translocoService: TranslocoService;
|
||||
|
||||
beforeEach(async () => {
|
||||
userService = {
|
||||
changePassword: vi.fn(() => of(void 0)),
|
||||
};
|
||||
authService = {
|
||||
logout: vi.fn(),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ChangePasswordComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(ChangePasswordComponent);
|
||||
component = fixture.componentInstance;
|
||||
translocoService = TestBed.inject(TranslocoService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('tracks whether the new passwords match', () => {
|
||||
component.newPassword = 'new-password';
|
||||
component.confirmNewPassword = 'new-password';
|
||||
expect(component.passwordsMatch).toBe(true);
|
||||
|
||||
component.confirmNewPassword = 'different';
|
||||
expect(component.passwordsMatch).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects submissions with missing fields before calling the service', () => {
|
||||
component.currentPassword = 'current';
|
||||
component.newPassword = '';
|
||||
component.confirmNewPassword = 'new-password';
|
||||
|
||||
component.changePassword();
|
||||
|
||||
expect(component.errorMessage).toBe(
|
||||
translocoService.translate('shared.changePassword.validation.allFieldsRequired')
|
||||
);
|
||||
expect(userService.changePassword).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects submissions when the new passwords do not match', () => {
|
||||
component.currentPassword = 'current';
|
||||
component.newPassword = 'new-password';
|
||||
component.confirmNewPassword = 'different';
|
||||
|
||||
component.changePassword();
|
||||
|
||||
expect(component.errorMessage).toBe(
|
||||
translocoService.translate('shared.changePassword.validation.passwordsDoNotMatch')
|
||||
);
|
||||
expect(userService.changePassword).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects submissions when the new password matches the current password', () => {
|
||||
component.currentPassword = 'same-password';
|
||||
component.newPassword = 'same-password';
|
||||
component.confirmNewPassword = 'same-password';
|
||||
|
||||
component.changePassword();
|
||||
|
||||
expect(component.errorMessage).toBe(
|
||||
translocoService.translate('shared.changePassword.validation.sameAsCurrentPassword')
|
||||
);
|
||||
expect(userService.changePassword).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('changes the password and logs the user out on success', () => {
|
||||
component.currentPassword = 'current-password';
|
||||
component.newPassword = 'new-password';
|
||||
component.confirmNewPassword = 'new-password';
|
||||
|
||||
component.changePassword();
|
||||
|
||||
expect(userService.changePassword).toHaveBeenCalledWith('current-password', 'new-password');
|
||||
expect(component.successMessage).toBe(
|
||||
translocoService.translate('shared.changePassword.toast.success')
|
||||
);
|
||||
expect(authService.logout).toHaveBeenCalled();
|
||||
expect(messageService.add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces backend failures through the error message and toast service', () => {
|
||||
userService.changePassword.mockReturnValueOnce(
|
||||
throwError(() => ({message: 'Password update failed'}))
|
||||
);
|
||||
component.currentPassword = 'current-password';
|
||||
component.newPassword = 'new-password';
|
||||
component.confirmNewPassword = 'new-password';
|
||||
|
||||
component.changePassword();
|
||||
|
||||
expect(component.errorMessage).toBe('Password update failed');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: translocoService.translate('shared.changePassword.toast.failedSummary'),
|
||||
detail: 'Password update failed',
|
||||
});
|
||||
expect(authService.logout).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {CoverGeneratorComponent} from './cover-generator.component';
|
||||
|
||||
describe('CoverGeneratorComponent', () => {
|
||||
let fixture: ComponentFixture<CoverGeneratorComponent>;
|
||||
let component: CoverGeneratorComponent;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CoverGeneratorComponent],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(CoverGeneratorComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function decodeCover(dataUrl: string): string {
|
||||
const encoded = dataUrl.replace('data:image/svg+xml;base64,', '');
|
||||
return decodeURIComponent(
|
||||
Array.from(atob(encoded))
|
||||
.map(char => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`)
|
||||
.join('')
|
||||
);
|
||||
}
|
||||
|
||||
it('generates a base64-encoded ebook cover with escaped title and author text', () => {
|
||||
component.title = 'Dune & <Messiah>';
|
||||
component.author = 'Frank "Herbert"';
|
||||
|
||||
const svg = decodeCover(component.generateCover());
|
||||
|
||||
expect(svg).toContain('<svg');
|
||||
expect(svg).toContain('Dune &');
|
||||
expect(svg).toContain('<Messiah>');
|
||||
expect(svg).toContain('"Herbert"');
|
||||
expect(svg).toContain('width="250" height="350"');
|
||||
});
|
||||
|
||||
it('generates a square audiobook cover when requested', () => {
|
||||
component.title = 'Project Hail Mary';
|
||||
component.author = 'Andy Weir';
|
||||
component.isSquare = true;
|
||||
|
||||
const svg = decodeCover(component.generateCover());
|
||||
|
||||
expect(svg).toContain('width="250" height="250"');
|
||||
expect(svg).toContain('L-6,8 L8,0 Z');
|
||||
});
|
||||
|
||||
it('wraps and truncates long titles into multiple lines', () => {
|
||||
component.title = 'A Very Long Book Title That Keeps Going Beyond The Expected Width Of The Cover';
|
||||
component.author = 'Someone';
|
||||
|
||||
const svg = decodeCover(component.generateCover());
|
||||
|
||||
expect((svg.match(/<text x="125"/g) ?? []).length).toBeGreaterThan(2);
|
||||
expect(svg).toContain('Going Beyond');
|
||||
expect(svg).not.toContain('Expected Width');
|
||||
});
|
||||
|
||||
it('produces deterministic palette selection for the same inputs', () => {
|
||||
component.title = 'Dune';
|
||||
component.author = 'Frank Herbert';
|
||||
|
||||
const first = component.generateCover();
|
||||
const second = component.generateCover();
|
||||
|
||||
expect(first).toBe(second);
|
||||
});
|
||||
});
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {DirectoryPickerComponent} from './directory-picker.component';
|
||||
import {UtilityService} from './utility.service';
|
||||
|
||||
describe('DirectoryPickerComponent', () => {
|
||||
let fixture: ComponentFixture<DirectoryPickerComponent>;
|
||||
let component: DirectoryPickerComponent;
|
||||
let utilityService: {getFolders: ReturnType<typeof vi.fn>};
|
||||
let dialogRef: {close: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
utilityService = {
|
||||
getFolders: vi.fn(() => of(['/books', '/comics'])),
|
||||
};
|
||||
dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [DirectoryPickerComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: UtilityService, useValue: utilityService},
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(DirectoryPickerComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the root folders on init and updates loading state after the delayed response', () => {
|
||||
component.ngOnInit();
|
||||
|
||||
expect(utilityService.getFolders).toHaveBeenCalledWith('/');
|
||||
expect(component.isLoading).toBe(true);
|
||||
|
||||
vi.advanceTimersByTime(100);
|
||||
|
||||
expect(component.paths).toEqual(['/books', '/comics']);
|
||||
expect(component.filteredPaths).toEqual(['/books', '/comics']);
|
||||
expect(component.isLoading).toBe(false);
|
||||
expect(component.breadcrumbItems).toEqual([]);
|
||||
});
|
||||
|
||||
it('builds breadcrumb items for nested paths', () => {
|
||||
component.updateBreadcrumb('/books/scifi/dune');
|
||||
|
||||
expect(component.breadcrumbItems.map(item => item.label)).toEqual(['books', 'scifi', 'dune']);
|
||||
});
|
||||
|
||||
it('filters visible paths using a case-insensitive search', () => {
|
||||
component.paths = ['/Books', '/Comics', '/Magazines'];
|
||||
component.searchQuery = 'co';
|
||||
|
||||
component.onSearch();
|
||||
|
||||
expect(component.filteredPaths).toEqual(['/Comics']);
|
||||
});
|
||||
|
||||
it('tracks checkbox selection and exposes the selection state', () => {
|
||||
component.onCheckboxChange('/books', true);
|
||||
expect(component.selectedFolders).toEqual(['/books']);
|
||||
expect(component.isFolderSelected('/books')).toBe(true);
|
||||
|
||||
component.onCheckboxChange('/books', false);
|
||||
expect(component.selectedFolders).toEqual([]);
|
||||
expect(component.isFolderSelected('/books')).toBe(false);
|
||||
});
|
||||
|
||||
it('navigates up to the parent path and clears the active search', () => {
|
||||
const getFoldersSpy = vi.spyOn(component, 'getFolders').mockImplementation(() => undefined);
|
||||
component.selectedProductName = '/books/scifi';
|
||||
component.searchQuery = 'du';
|
||||
|
||||
component.goUp();
|
||||
|
||||
expect(component.selectedProductName).toBe('/books');
|
||||
expect(component.searchQuery).toBe('');
|
||||
expect(getFoldersSpy).toHaveBeenCalledWith('/books');
|
||||
});
|
||||
|
||||
it('selects all filtered folders and can clear them again', () => {
|
||||
component.filteredPaths = ['/books', '/comics'];
|
||||
|
||||
component.selectAll();
|
||||
expect(component.selectedFolders).toEqual(['/books', '/comics']);
|
||||
expect(component.selectedFoldersMap).toMatchObject({
|
||||
'/books': true,
|
||||
'/comics': true,
|
||||
});
|
||||
|
||||
component.deselectAll();
|
||||
expect(component.selectedFolders).toEqual([]);
|
||||
expect(component.selectedFoldersMap).toMatchObject({
|
||||
'/books': false,
|
||||
'/comics': false,
|
||||
});
|
||||
});
|
||||
|
||||
it('closes the dialog with the selected folders or null', () => {
|
||||
component.selectedFolders = ['/books'];
|
||||
|
||||
component.onSelect();
|
||||
component.onCancel();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenNthCalledWith(1, ['/books']);
|
||||
expect(dialogRef.close).toHaveBeenNthCalledWith(2, null);
|
||||
});
|
||||
|
||||
it('clears loading state when folder loading fails', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
utilityService.getFolders.mockReturnValueOnce(throwError(() => new Error('boom')));
|
||||
|
||||
component.getFolders('/broken');
|
||||
|
||||
expect(component.isLoading).toBe(false);
|
||||
expect(console.error).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('extracts the final folder name from a path', () => {
|
||||
expect(component.getFolderName('/books/scifi')).toBe('scifi');
|
||||
expect(component.getFolderName('/')).toBe('/');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
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 {UtilityService} from './utility.service';
|
||||
|
||||
describe('UtilityService', () => {
|
||||
let service: UtilityService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
UtilityService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(UtilityService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('requests folders for the provided path', () => {
|
||||
const response = ['/books', '/books/scifi'];
|
||||
|
||||
let result: string[] | undefined;
|
||||
service.getFolders('/books').subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/path'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
expect(request.request.params.get('path')).toBe('/books');
|
||||
request.flush(response);
|
||||
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {EmptyComponent} from './empty.component';
|
||||
|
||||
describe('EmptyComponent', () => {
|
||||
let fixture: ComponentFixture<EmptyComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [EmptyComponent],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(EmptyComponent);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('creates successfully', () => {
|
||||
expect(fixture.componentInstance).toBeTruthy();
|
||||
});
|
||||
|
||||
it('renders the empty state template', () => {
|
||||
expect(fixture.nativeElement.textContent?.trim().length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ExternalDocLinkComponent} from './external-doc-link.component';
|
||||
|
||||
describe('ExternalDocLinkComponent', () => {
|
||||
let fixture: ComponentFixture<ExternalDocLinkComponent>;
|
||||
let component: ExternalDocLinkComponent;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ExternalDocLinkComponent],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(ExternalDocLinkComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('opens the configured documentation link in a new tab', () => {
|
||||
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
component.docType = 'taskManagement';
|
||||
|
||||
component.openLink();
|
||||
|
||||
expect(openSpy).toHaveBeenCalledWith('https://grimmory.org/docs/tools/task-manager', '_blank');
|
||||
});
|
||||
|
||||
it('does nothing when the doc type is unknown at runtime', () => {
|
||||
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
(component as unknown as {docType: string}).docType = 'unknown';
|
||||
|
||||
component.openLink();
|
||||
|
||||
expect(openSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders the clickable icon with the configured size', () => {
|
||||
component.docType = 'authentication';
|
||||
component.tooltip = 'Read the docs';
|
||||
component.tooltipPosition = 'left';
|
||||
component.size = '1.5rem';
|
||||
fixture.detectChanges();
|
||||
|
||||
const icon = fixture.nativeElement.querySelector('i') as HTMLElement;
|
||||
expect(icon.getAttribute('role')).toBe('button');
|
||||
expect(icon.getAttribute('tabindex')).toBe('0');
|
||||
expect(icon.style.fontSize).toBe('1.5rem');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around dialog config input,
|
||||
// library-query reactivity, placeholder resolution, and file-operation side effects so
|
||||
// preview generation and move submission can be asserted without reproducing the full runtime graph.
|
||||
describe.skip('FileMoverComponent', () => {
|
||||
it('needs a query-and-dialog seam to verify preview generation and target-library path updates', () => {
|
||||
// TODO(seam): Cover applyPattern and library/path change flows once dialog config and reactive library data are injectable test seams.
|
||||
});
|
||||
|
||||
it('needs a file-operations seam to verify move submission and toast behavior without coupling to runtime app settings effects', () => {
|
||||
// TODO(seam): Cover move execution, success/failure messaging, and pattern source selection after extracting the side-effectful workflow.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {SafeHtml} from '@angular/platform-browser';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {IconDisplayComponent} from './icon-display.component';
|
||||
import {IconCacheService} from '../../services/icon-cache.service';
|
||||
import {IconService} from '../../services/icon.service';
|
||||
|
||||
describe('IconDisplayComponent', () => {
|
||||
let fixture: ComponentFixture<IconDisplayComponent>;
|
||||
let component: IconDisplayComponent;
|
||||
let iconCache: {
|
||||
getCachedSanitized: ReturnType<typeof vi.fn>;
|
||||
cacheIcon: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let iconService: {getSanitizedSvgContent: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
iconCache = {
|
||||
getCachedSanitized: vi.fn(() => null),
|
||||
cacheIcon: vi.fn(),
|
||||
};
|
||||
iconService = {
|
||||
getSanitizedSvgContent: vi.fn(() => of('<svg>ok</svg>' as SafeHtml)),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [IconDisplayComponent],
|
||||
providers: [
|
||||
{provide: IconCacheService, useValue: iconCache},
|
||||
{provide: IconService, useValue: iconService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(IconDisplayComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('normalizes PrimeNG icon class names', () => {
|
||||
expect(component.getPrimeNgIconClass('pi pi-book')).toBe('pi pi-book');
|
||||
expect(component.getPrimeNgIconClass('pi-book')).toBe('pi pi-book');
|
||||
expect(component.getPrimeNgIconClass('book')).toBe('pi pi-book');
|
||||
});
|
||||
|
||||
it('builds PrimeNG styles from the configured size and extra icon style', () => {
|
||||
component.size = '20px';
|
||||
component.iconStyle = {color: 'tomato'};
|
||||
|
||||
expect(component.getPrimeNgStyle()).toEqual({
|
||||
fontSize: '17px',
|
||||
width: '20px',
|
||||
height: '20px',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'tomato',
|
||||
});
|
||||
});
|
||||
|
||||
it('loads uncached custom SVG icons on initialization', () => {
|
||||
component.icon = {type: 'CUSTOM_SVG', value: 'dragon'};
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(iconCache.getCachedSanitized).toHaveBeenCalledWith('dragon');
|
||||
expect(iconService.getSanitizedSvgContent).toHaveBeenCalledWith('dragon');
|
||||
});
|
||||
|
||||
it('does not reload the same custom SVG when the value has not changed', () => {
|
||||
const loadSpy = vi.spyOn(component as never, 'loadIconIfNeeded');
|
||||
component.ngOnChanges({
|
||||
icon: {
|
||||
currentValue: {type: 'CUSTOM_SVG', value: 'dragon'},
|
||||
previousValue: {type: 'CUSTOM_SVG', value: 'dragon'},
|
||||
firstChange: false,
|
||||
isFirstChange: () => false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(loadSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reloads when the custom SVG icon value changes', () => {
|
||||
const loadSpy = vi.spyOn(component as never, 'loadIconIfNeeded');
|
||||
|
||||
component.ngOnChanges({
|
||||
icon: {
|
||||
currentValue: {type: 'CUSTOM_SVG', value: 'dragon'},
|
||||
previousValue: {type: 'CUSTOM_SVG', value: 'phoenix'},
|
||||
firstChange: false,
|
||||
isFirstChange: () => false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(loadSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('exposes cached SVG content and empty-icon dimensions', () => {
|
||||
iconCache.getCachedSanitized.mockReturnValueOnce('<svg>cached</svg>' as SafeHtml);
|
||||
component.size = '2rem';
|
||||
|
||||
expect(component.getSvgContent('cached')).toBe('<svg>cached</svg>' as SafeHtml);
|
||||
expect(component.getEmptyIconStyle()).toEqual({
|
||||
width: '2rem',
|
||||
height: '2rem',
|
||||
});
|
||||
});
|
||||
|
||||
it('caches an error SVG when loading a custom icon fails', () => {
|
||||
iconService.getSanitizedSvgContent.mockReturnValueOnce(
|
||||
throwError(() => new Error('nope'))
|
||||
);
|
||||
component.icon = {type: 'CUSTOM_SVG', value: 'broken'};
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(iconCache.cacheIcon).toHaveBeenCalledOnce();
|
||||
expect(iconCache.cacheIcon.mock.calls[0]?.[0]).toBe('broken');
|
||||
expect(iconCache.cacheIcon.mock.calls[0]?.[1]).toContain('stroke="red"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around DOMPurify preview generation,
|
||||
// batch-upload side effects, dialog closing, and drag/drop DOM events so the SVG-management
|
||||
// flow can be proven without changing runtime code or reproducing browser-only behavior inline.
|
||||
describe.skip('IconPickerComponent', () => {
|
||||
it('needs a browser-event seam to verify SVG preview, validation, and drag-to-delete flows', () => {
|
||||
// TODO(seam): Cover SVG parsing, preview generation, and drag/drop delete behavior once event/DOM seams exist.
|
||||
});
|
||||
|
||||
it('needs an upload-result seam to verify partial-success batch messaging and cache refresh behavior', () => {
|
||||
// TODO(seam): Cover saveAllSvgs and loadSvgIcons without coupling the spec to live DOMPurify and dialog runtime behavior.
|
||||
});
|
||||
});
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import {Subject} from 'rxjs';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {NotificationEventService} from '../../websocket/notification-event.service';
|
||||
import {LogNotification, Severity} from '../../websocket/model/log-notification.model';
|
||||
import {LiveNotificationBoxComponent} from './live-notification-box.component';
|
||||
|
||||
describe('LiveNotificationBoxComponent', () => {
|
||||
let notifications$: Subject<LogNotification>;
|
||||
let langChanges$: Subject<string>;
|
||||
let component: LiveNotificationBoxComponent;
|
||||
|
||||
beforeEach(() => {
|
||||
notifications$ = new Subject<LogNotification>();
|
||||
langChanges$ = new Subject<string>();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
LiveNotificationBoxComponent,
|
||||
{
|
||||
provide: NotificationEventService,
|
||||
useValue: {latestNotification$: notifications$},
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
translate: (key: string) => `translated:${key}`,
|
||||
langChanges$,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
component = TestBed.inject(LiveNotificationBoxComponent);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('starts with the translated default message', () => {
|
||||
expect(component.latestNotification).toEqual({
|
||||
message: 'translated:shared.liveNotification.defaultMessage',
|
||||
});
|
||||
});
|
||||
|
||||
it('replaces the latest notification when a websocket event arrives', () => {
|
||||
notifications$.next({message: 'Metadata updated', severity: Severity.INFO});
|
||||
|
||||
expect(component.latestNotification).toEqual({
|
||||
message: 'Metadata updated',
|
||||
severity: Severity.INFO,
|
||||
});
|
||||
});
|
||||
|
||||
it('refreshes the default message on language changes until a notification arrives', () => {
|
||||
langChanges$.next('fr');
|
||||
|
||||
expect(component.latestNotification).toEqual({
|
||||
message: 'translated:shared.liveNotification.defaultMessage',
|
||||
});
|
||||
|
||||
notifications$.next({message: 'Build finished', severity: Severity.WARN});
|
||||
langChanges$.next('de');
|
||||
|
||||
expect(component.latestNotification).toEqual({
|
||||
message: 'Build finished',
|
||||
severity: Severity.WARN,
|
||||
});
|
||||
});
|
||||
|
||||
it('maps severities to the expected tag colors', () => {
|
||||
expect(component.getSeverityColor(Severity.ERROR)).toBe('red');
|
||||
expect(component.getSeverityColor(Severity.WARN)).toBe('amber');
|
||||
expect(component.getSeverityColor(Severity.INFO)).toBe('green');
|
||||
expect(component.getSeverityColor(undefined)).toBe('gray');
|
||||
});
|
||||
|
||||
it('stops reacting to streams after destruction', () => {
|
||||
component.ngOnDestroy();
|
||||
notifications$.next({message: 'Ignored', severity: Severity.ERROR});
|
||||
langChanges$.next('es');
|
||||
|
||||
expect(component.latestNotification).toEqual({
|
||||
message: 'translated:shared.liveNotification.defaultMessage',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of, throwError} from 'rxjs';
|
||||
|
||||
import {OidcService} from '../../../core/security/oidc.service';
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {PublicAppSettings} from '../../service/app-settings.service';
|
||||
import {AuthService} from '../../service/auth.service';
|
||||
import {AppSettingsService} from '../../service/app-settings.service';
|
||||
import {LoginComponent} from './login.component';
|
||||
|
||||
function createPublicSettings(overrides: Partial<PublicAppSettings> = {}): PublicAppSettings {
|
||||
return {
|
||||
oidcEnabled: true,
|
||||
remoteAuthEnabled: false,
|
||||
oidcForceOnlyMode: false,
|
||||
oidcProviderDetails: {
|
||||
providerName: 'Pocket ID',
|
||||
clientId: 'client-id',
|
||||
issuerUri: 'https://issuer.example',
|
||||
scopes: 'openid profile email',
|
||||
claimMapping: {
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'name',
|
||||
groups: 'groups',
|
||||
}
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('LoginComponent', () => {
|
||||
let fixture: ComponentFixture<LoginComponent>;
|
||||
let component: LoginComponent;
|
||||
let publicSettingsSignal: ReturnType<typeof signal<PublicAppSettings | null>>;
|
||||
|
||||
const authService = {
|
||||
clearSessionOnLoginPage: vi.fn(),
|
||||
internalLogin: vi.fn(),
|
||||
};
|
||||
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
|
||||
const oidcService = {
|
||||
generatePkce: vi.fn(),
|
||||
fetchState: vi.fn(),
|
||||
generateRandomString: vi.fn(),
|
||||
storePkceState: vi.fn(),
|
||||
buildAuthUrl: vi.fn(),
|
||||
};
|
||||
|
||||
function configureComponent(
|
||||
queryParams: Record<string, string> = {},
|
||||
settingsOverrides: Partial<PublicAppSettings> = {},
|
||||
autoDetectChanges = true
|
||||
): void {
|
||||
publicSettingsSignal = signal<PublicAppSettings | null>(createPublicSettings(settingsOverrides));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [
|
||||
LoginComponent,
|
||||
getTranslocoModule(),
|
||||
],
|
||||
providers: [
|
||||
{provide: AuthService, useValue: authService},
|
||||
{provide: Router, useValue: router},
|
||||
{provide: OidcService, useValue: oidcService},
|
||||
{
|
||||
provide: AppSettingsService,
|
||||
useValue: {
|
||||
publicAppSettings: publicSettingsSignal,
|
||||
}
|
||||
},
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: {
|
||||
queryParams: of(queryParams),
|
||||
}
|
||||
},
|
||||
]
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(LoginComponent);
|
||||
component = fixture.componentInstance;
|
||||
if (autoDetectChanges) {
|
||||
fixture.detectChanges();
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
sessionStorage.clear();
|
||||
|
||||
authService.clearSessionOnLoginPage.mockReset();
|
||||
authService.internalLogin.mockReset();
|
||||
router.navigate.mockClear();
|
||||
oidcService.generatePkce.mockReset();
|
||||
oidcService.fetchState.mockReset();
|
||||
oidcService.generateRandomString.mockReset();
|
||||
oidcService.storePkceState.mockReset();
|
||||
oidcService.buildAuthUrl.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sessionStorage.clear();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('clears the session and shows the session revoked message from query params', () => {
|
||||
configureComponent({reason: 'session_revoked'});
|
||||
|
||||
expect(authService.clearSessionOnLoginPage).toHaveBeenCalledOnce();
|
||||
expect(component.infoMessage).toBe('auth.login.sessionRevoked');
|
||||
});
|
||||
|
||||
it('maps known OIDC callback errors to translated messages', () => {
|
||||
configureComponent({oidcError: 'exchange_failed'});
|
||||
|
||||
expect(component.errorMessage).toBe('auth.login.oidcErrors.exchangeFailed');
|
||||
});
|
||||
|
||||
it('keeps the local login visible when OIDC-only mode is not enabled', () => {
|
||||
configureComponent();
|
||||
|
||||
expect(component.oidcEnabled).toBe(true);
|
||||
expect(component.oidcName).toBe('Pocket ID');
|
||||
expect(component.showLocalLogin).toBe(true);
|
||||
});
|
||||
|
||||
it('auto-redirects to OIDC in force-only mode when there is no local override or callback error', async () => {
|
||||
configureComponent({}, {oidcForceOnlyMode: true}, false);
|
||||
const loginWithOidcSpy = vi.spyOn(component, 'loginWithOidc').mockResolvedValue(undefined);
|
||||
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
|
||||
expect(component.showLocalLogin).toBe(false);
|
||||
expect(sessionStorage.getItem('oidc_redirect_count')).toBe('1');
|
||||
expect(loginWithOidcSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('stops the OIDC auto-redirect loop after the maximum retry count', async () => {
|
||||
sessionStorage.setItem('oidc_redirect_count', '3');
|
||||
configureComponent({}, {oidcForceOnlyMode: true}, false);
|
||||
const loginWithOidcSpy = vi.spyOn(component, 'loginWithOidc').mockResolvedValue(undefined);
|
||||
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
|
||||
expect([
|
||||
'auth.login.oidcOnlyRedirectFailed',
|
||||
'Unable to reach the identity provider. Please contact your administrator.'
|
||||
]).toContain(component.errorMessage);
|
||||
expect(component.showLocalLogin).toBe(false);
|
||||
expect(sessionStorage.getItem('oidc_redirect_count')).toBeNull();
|
||||
expect(loginWithOidcSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('navigates to change-password when the server marks the password as default', () => {
|
||||
configureComponent();
|
||||
authService.internalLogin.mockReturnValue(of({isDefaultPassword: 'true'}));
|
||||
|
||||
component.username = 'admin';
|
||||
component.password = 'password';
|
||||
component.login();
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||
});
|
||||
|
||||
it('navigates to the dashboard after a successful non-default-password login', () => {
|
||||
configureComponent();
|
||||
authService.internalLogin.mockReturnValue(of({isDefaultPassword: 'false'}));
|
||||
|
||||
component.username = 'admin';
|
||||
component.password = 'password';
|
||||
component.login();
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
|
||||
it('shows translated messages for network and rate-limit login failures', () => {
|
||||
configureComponent();
|
||||
|
||||
authService.internalLogin.mockReturnValueOnce(throwError(() => ({status: 0})));
|
||||
component.login();
|
||||
expect(component.errorMessage).toBe('Cannot connect to the server. Please check your connection and try again.');
|
||||
|
||||
authService.internalLogin.mockReturnValueOnce(throwError(() => ({status: 429})));
|
||||
component.login();
|
||||
expect(component.errorMessage).toBe('Too many failed login attempts. Please try again later.');
|
||||
});
|
||||
|
||||
it('uses the backend error message when login fails unexpectedly', () => {
|
||||
configureComponent();
|
||||
authService.internalLogin.mockReturnValue(
|
||||
throwError(() => ({status: 500, error: {message: 'Bad credentials'}}))
|
||||
);
|
||||
|
||||
component.login();
|
||||
|
||||
expect(component.errorMessage).toBe('Bad credentials');
|
||||
});
|
||||
|
||||
it('requires provider details before starting the OIDC flow', async () => {
|
||||
configureComponent();
|
||||
publicSettingsSignal.set(createPublicSettings({oidcProviderDetails: undefined as unknown as PublicAppSettings['oidcProviderDetails']}));
|
||||
|
||||
await component.loginWithOidc();
|
||||
|
||||
expect(component.errorMessage).toBe('Failed to initiate OIDC login. Please try again or use local login.');
|
||||
expect(component.isOidcLoginInProgress).toBe(false);
|
||||
});
|
||||
|
||||
it('builds the OIDC auth URL and redirects the browser', async () => {
|
||||
configureComponent();
|
||||
oidcService.generatePkce.mockResolvedValue({codeVerifier: 'verifier', codeChallenge: 'challenge'});
|
||||
oidcService.fetchState.mockResolvedValue('state-token');
|
||||
oidcService.generateRandomString.mockReturnValue('nonce-token');
|
||||
oidcService.buildAuthUrl.mockResolvedValue('https://issuer.example/auth');
|
||||
|
||||
await component.loginWithOidc();
|
||||
|
||||
expect(oidcService.storePkceState).toHaveBeenCalledWith({
|
||||
codeVerifier: 'verifier',
|
||||
state: 'state-token',
|
||||
nonce: 'nonce-token',
|
||||
});
|
||||
expect(oidcService.buildAuthUrl).toHaveBeenCalledWith(
|
||||
'https://issuer.example',
|
||||
'client-id',
|
||||
'challenge',
|
||||
'state-token',
|
||||
'nonce-token',
|
||||
undefined,
|
||||
'openid profile email'
|
||||
);
|
||||
expect(component.errorMessage).toBe('');
|
||||
});
|
||||
|
||||
it('shows a translated provider error when OIDC login initialization fails', async () => {
|
||||
configureComponent();
|
||||
oidcService.generatePkce.mockRejectedValue(new Error('crypto unavailable'));
|
||||
|
||||
await component.loginWithOidc();
|
||||
|
||||
expect(component.errorMessage).toBe('Could not reach the OIDC provider. Please try again later.');
|
||||
expect(component.isOidcLoginInProgress).toBe(false);
|
||||
expect(component.showLocalLogin).toBe(true);
|
||||
});
|
||||
});
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {BehaviorSubject, of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../model/metadata-batch-progress.model';
|
||||
import {MetadataTaskService} from '../../../features/book/service/metadata-task';
|
||||
import {TaskService} from '../../../features/settings/task-management/task.service';
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {MetadataProgressWidgetComponent} from './metadata-progress-widget-component';
|
||||
import {MetadataProgressService} from '../../service/metadata-progress.service';
|
||||
import {DialogLauncherService} from '../../services/dialog-launcher.service';
|
||||
|
||||
describe('MetadataProgressWidgetComponent', () => {
|
||||
let fixture: ComponentFixture<MetadataProgressWidgetComponent>;
|
||||
let component: MetadataProgressWidgetComponent;
|
||||
let activeTasksSubject: BehaviorSubject<Record<string, MetadataBatchProgressNotification>>;
|
||||
let metadataProgressService: {
|
||||
activeTasks$: BehaviorSubject<Record<string, MetadataBatchProgressNotification>>;
|
||||
clearTask: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let metadataTaskService: {deleteTask: ReturnType<typeof vi.fn>};
|
||||
let taskService: {cancelTask: ReturnType<typeof vi.fn>};
|
||||
let dialogLauncherService: {openMetadataReviewDialog: ReturnType<typeof vi.fn>};
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let translocoService: TranslocoService;
|
||||
|
||||
const task: MetadataBatchProgressNotification = {
|
||||
taskId: 'task-1',
|
||||
completed: 2,
|
||||
total: 5,
|
||||
message: 'Running',
|
||||
status: MetadataBatchStatus.IN_PROGRESS,
|
||||
review: false,
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
activeTasksSubject = new BehaviorSubject<Record<string, MetadataBatchProgressNotification>>({});
|
||||
metadataProgressService = {
|
||||
activeTasks$: activeTasksSubject,
|
||||
clearTask: vi.fn(),
|
||||
};
|
||||
metadataTaskService = {
|
||||
deleteTask: vi.fn(() => of(void 0)),
|
||||
};
|
||||
taskService = {
|
||||
cancelTask: vi.fn(() => of({cancelled: true})),
|
||||
};
|
||||
dialogLauncherService = {
|
||||
openMetadataReviewDialog: vi.fn(),
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [MetadataProgressWidgetComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: MetadataProgressService, useValue: metadataProgressService},
|
||||
{provide: MetadataTaskService, useValue: metadataTaskService},
|
||||
{provide: TaskService, useValue: taskService},
|
||||
{provide: DialogLauncherService, useValue: dialogLauncherService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(MetadataProgressWidgetComponent);
|
||||
component = fixture.componentInstance;
|
||||
translocoService = TestBed.inject(TranslocoService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('tracks active tasks from the progress service and marks stalled tasks as errors', () => {
|
||||
component.ngOnInit();
|
||||
|
||||
activeTasksSubject.next({[task.taskId]: task});
|
||||
expect(component.activeTasks).toEqual({[task.taskId]: task});
|
||||
|
||||
vi.advanceTimersByTime(60000);
|
||||
|
||||
expect(component.activeTasks[task.taskId]).toMatchObject({
|
||||
status: MetadataBatchStatus.ERROR,
|
||||
message: translocoService.translate('shared.metadataProgress.taskStalled'),
|
||||
});
|
||||
});
|
||||
|
||||
it('computes progress percentages and tag severity values', () => {
|
||||
expect(component.getProgressPercent({...task, total: 0})).toBe(0);
|
||||
expect(component.getProgressPercent({...task, status: MetadataBatchStatus.COMPLETED})).toBe(100);
|
||||
expect(component.getProgressPercent(task)).toBe(40);
|
||||
expect(component.getTagSeverity(MetadataBatchStatus.IN_PROGRESS)).toBe('info');
|
||||
expect(component.getTagSeverity(MetadataBatchStatus.COMPLETED)).toBe('success');
|
||||
expect(component.getTagSeverity(MetadataBatchStatus.ERROR)).toBe('danger');
|
||||
expect(component.getTagSeverity(MetadataBatchStatus.CANCELLED)).toBe('warn');
|
||||
});
|
||||
|
||||
it('clears a task through the metadata task API and local progress store', () => {
|
||||
component.ngOnInit();
|
||||
activeTasksSubject.next({[task.taskId]: task});
|
||||
|
||||
component.clearTask(task.taskId);
|
||||
|
||||
expect(metadataTaskService.deleteTask).toHaveBeenCalledWith(task.taskId);
|
||||
expect(metadataProgressService.clearTask).toHaveBeenCalledWith(task.taskId);
|
||||
});
|
||||
|
||||
it('opens the review dialog for a task', () => {
|
||||
component.reviewTask(task.taskId);
|
||||
|
||||
expect(dialogLauncherService.openMetadataReviewDialog).toHaveBeenCalledWith(task.taskId);
|
||||
});
|
||||
|
||||
it('marks tasks cancelled and shows a success toast when cancellation is scheduled', () => {
|
||||
component.activeTasks = {[task.taskId]: task};
|
||||
|
||||
component.cancelTask(task.taskId);
|
||||
|
||||
expect(taskService.cancelTask).toHaveBeenCalledWith(task.taskId);
|
||||
expect(component.activeTasks[task.taskId]).toMatchObject({
|
||||
status: MetadataBatchStatus.CANCELLED,
|
||||
message: translocoService.translate('shared.metadataProgress.taskCancelled'),
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: translocoService.translate('shared.metadataProgress.cancellationScheduledSummary'),
|
||||
detail: translocoService.translate('shared.metadataProgress.cancellationScheduledDetail'),
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error toast when cancellation fails', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
taskService.cancelTask.mockReturnValueOnce(throwError(() => new Error('boom')));
|
||||
|
||||
component.cancelTask(task.taskId);
|
||||
|
||||
expect(console.error).toHaveBeenCalled();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: translocoService.translate('shared.metadataProgress.cancelFailedSummary'),
|
||||
detail: translocoService.translate('shared.metadataProgress.cancelFailedDetail'),
|
||||
});
|
||||
});
|
||||
|
||||
it('returns translated status labels and clears timers on destroy', () => {
|
||||
component.ngOnInit();
|
||||
activeTasksSubject.next({[task.taskId]: task});
|
||||
|
||||
expect(component.getStatusLabel(MetadataBatchStatus.ERROR)).toBe(
|
||||
translocoService.translate('shared.metadataProgress.statusError')
|
||||
);
|
||||
|
||||
component.ngOnDestroy();
|
||||
vi.advanceTimersByTime(60000);
|
||||
|
||||
expect(component.activeTasks[task.taskId]).toEqual(task);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {LoginGuard} from './login.guard';
|
||||
|
||||
describe('LoginGuard', () => {
|
||||
const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
|
||||
let guard: LoginGuard;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
router.navigate.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
{provide: Router, useValue: router},
|
||||
LoginGuard,
|
||||
]
|
||||
});
|
||||
|
||||
guard = TestBed.inject(LoginGuard);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('allows access when setup has already completed', async () => {
|
||||
const resultPromise = firstValueFrom(guard.canActivate());
|
||||
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: true});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to setup when the setup status request fails', async () => {
|
||||
const resultPromise = firstValueFrom(guard.canActivate());
|
||||
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush('boom', {status: 500, statusText: 'Server Error'});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/setup']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router, UrlTree} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {LoginGuard} from './login.guard';
|
||||
import {SetupGuard} from './setup.guard';
|
||||
import {SetupRedirectGuard} from './setup-redirect.guard';
|
||||
|
||||
describe('setup and login guards', () => {
|
||||
const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`;
|
||||
const router = {
|
||||
createUrlTree: vi.fn((commands: string[]) => ({commands}) as unknown as UrlTree),
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
|
||||
let httpTestingController: HttpTestingController;
|
||||
let setupGuard: SetupGuard;
|
||||
let loginGuard: LoginGuard;
|
||||
let setupRedirectGuard: SetupRedirectGuard;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
router.createUrlTree.mockClear();
|
||||
router.navigate.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
{provide: Router, useValue: router},
|
||||
SetupGuard,
|
||||
LoginGuard,
|
||||
SetupRedirectGuard,
|
||||
]
|
||||
});
|
||||
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
setupGuard = TestBed.inject(SetupGuard);
|
||||
loginGuard = TestBed.inject(LoginGuard);
|
||||
setupRedirectGuard = TestBed.inject(SetupRedirectGuard);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('allows setup when the instance is not configured yet', async () => {
|
||||
const resultPromise = firstValueFrom(setupGuard.canActivate());
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: false});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('redirects setup to login when setup is already complete', async () => {
|
||||
const resultPromise = firstValueFrom(setupGuard.canActivate());
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: true});
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({commands: ['/login']});
|
||||
expect(router.createUrlTree).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('allows login only after setup is complete', async () => {
|
||||
const resultPromise = firstValueFrom(loginGuard.canActivate());
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: true});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects login to setup when setup is incomplete', async () => {
|
||||
const resultPromise = firstValueFrom(loginGuard.canActivate());
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: false});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/setup']);
|
||||
});
|
||||
|
||||
it('redirects login to setup when the setup status request fails', async () => {
|
||||
const resultPromise = firstValueFrom(loginGuard.canActivate());
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush('boom', {status: 500, statusText: 'Server Error'});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/setup']);
|
||||
});
|
||||
|
||||
it('sends users from the root route to setup when configuration is missing', async () => {
|
||||
const resultPromise = firstValueFrom(setupRedirectGuard.canActivate());
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: false});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/setup']);
|
||||
});
|
||||
|
||||
it('sends users from the root route to the dashboard when setup is complete', async () => {
|
||||
const resultPromise = firstValueFrom(setupRedirectGuard.canActivate());
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: true});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {SetupRedirectGuard} from './setup-redirect.guard';
|
||||
|
||||
describe('SetupRedirectGuard', () => {
|
||||
const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`;
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
|
||||
let guard: SetupRedirectGuard;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
router.navigate.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
{provide: Router, useValue: router},
|
||||
SetupRedirectGuard,
|
||||
]
|
||||
});
|
||||
|
||||
guard = TestBed.inject(SetupRedirectGuard);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('sends users to setup when the instance is not configured', async () => {
|
||||
const resultPromise = firstValueFrom(guard.canActivate());
|
||||
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: false});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/setup']);
|
||||
});
|
||||
|
||||
it('sends users to the dashboard when setup is complete', async () => {
|
||||
const resultPromise = firstValueFrom(guard.canActivate());
|
||||
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: true});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {SetupComponent} from './setup.component';
|
||||
import {SetupService} from './setup.service';
|
||||
|
||||
describe('SetupComponent', () => {
|
||||
let fixture: ComponentFixture<SetupComponent>;
|
||||
let component: SetupComponent;
|
||||
let setupService: {createAdmin: ReturnType<typeof vi.fn>};
|
||||
let router: {navigate: ReturnType<typeof vi.fn>};
|
||||
let translocoService: TranslocoService;
|
||||
|
||||
beforeEach(async () => {
|
||||
setupService = {
|
||||
createAdmin: vi.fn(() => of(void 0)),
|
||||
};
|
||||
router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [SetupComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: SetupService, useValue: setupService},
|
||||
{provide: Router, useValue: router},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(SetupComponent);
|
||||
component = fixture.componentInstance;
|
||||
translocoService = TestBed.inject(TranslocoService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function fillValidForm() {
|
||||
component.setupForm.setValue({
|
||||
name: 'Admin User',
|
||||
username: 'admin',
|
||||
email: 'admin@example.com',
|
||||
password: 'supersecure',
|
||||
confirmPassword: 'supersecure',
|
||||
});
|
||||
}
|
||||
|
||||
it('refuses to submit when the form is invalid', () => {
|
||||
component.setupForm.patchValue({
|
||||
name: 'Admin User',
|
||||
username: 'admin',
|
||||
});
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(setupService.createAdmin).not.toHaveBeenCalled();
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('submits the admin payload without confirmPassword', () => {
|
||||
fillValidForm();
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(component.loading).toBe(true);
|
||||
expect(component.error).toBe(null);
|
||||
expect(setupService.createAdmin).toHaveBeenCalledWith({
|
||||
name: 'Admin User',
|
||||
username: 'admin',
|
||||
email: 'admin@example.com',
|
||||
password: 'supersecure',
|
||||
});
|
||||
});
|
||||
|
||||
it('marks success and redirects to login after the delay', async () => {
|
||||
fillValidForm();
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(component.success).toBe(true);
|
||||
expect(component.loading).toBe(true);
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(1500);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('surfaces backend error messages and clears loading', () => {
|
||||
fillValidForm();
|
||||
setupService.createAdmin.mockReturnValueOnce(
|
||||
throwError(() => ({error: {message: 'Setup failed'}}))
|
||||
);
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(component.loading).toBe(false);
|
||||
expect(component.error).toBe('Setup failed');
|
||||
expect(component.success).toBe(false);
|
||||
});
|
||||
|
||||
it('uses the translated fallback error when the backend does not provide one', () => {
|
||||
fillValidForm();
|
||||
setupService.createAdmin.mockReturnValueOnce(throwError(() => ({error: {}})));
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(component.error).toBe(
|
||||
translocoService.translate('shared.setup.toast.createFailedDefault')
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router, UrlTree} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {SetupGuard} from './setup.guard';
|
||||
|
||||
describe('SetupGuard', () => {
|
||||
const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`;
|
||||
const router = {
|
||||
createUrlTree: vi.fn((commands: string[]) => ({commands}) as unknown as UrlTree),
|
||||
};
|
||||
|
||||
let guard: SetupGuard;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
router.createUrlTree.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
{provide: Router, useValue: router},
|
||||
SetupGuard,
|
||||
]
|
||||
});
|
||||
|
||||
guard = TestBed.inject(SetupGuard);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('allows access when setup is still incomplete', async () => {
|
||||
const resultPromise = firstValueFrom(guard.canActivate());
|
||||
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: false});
|
||||
|
||||
await expect(resultPromise).resolves.toBe(true);
|
||||
expect(router.createUrlTree).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns a login redirect tree once setup is complete', async () => {
|
||||
const resultPromise = firstValueFrom(guard.canActivate());
|
||||
|
||||
const request = httpTestingController.expectOne(setupStatusUrl);
|
||||
request.flush({data: true});
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({commands: ['/login']});
|
||||
expect(router.createUrlTree).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
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 {SetupService} from './setup.service';
|
||||
|
||||
describe('SetupService', () => {
|
||||
const setupUrl = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
|
||||
let service: SetupService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
SetupService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(SetupService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('posts the admin setup payload to the setup endpoint', () => {
|
||||
service.createAdmin({email: 'admin@example.com', password: 'secret'}).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(setupUrl);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({
|
||||
email: 'admin@example.com',
|
||||
password: 'secret',
|
||||
});
|
||||
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import {Component} from '@angular/core';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {TagColor, TagComponent, TagSize, TagVariant} from './tag.component';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
imports: [TagComponent],
|
||||
template: `
|
||||
<app-tag
|
||||
[color]="color"
|
||||
[size]="size"
|
||||
[variant]="variant"
|
||||
[rounded]="rounded"
|
||||
[pill]="pill"
|
||||
[customBgColor]="customBgColor"
|
||||
[customTextColor]="customTextColor"
|
||||
>
|
||||
Test
|
||||
</app-tag>
|
||||
`,
|
||||
})
|
||||
class TestHostComponent {
|
||||
color: TagColor = 'primary';
|
||||
size: TagSize = 'm';
|
||||
variant: TagVariant = 'label';
|
||||
rounded = false;
|
||||
pill = false;
|
||||
customBgColor = '#112233';
|
||||
customTextColor = '#fefefe';
|
||||
}
|
||||
|
||||
describe('TagComponent', () => {
|
||||
let fixture: ComponentFixture<TestHostComponent>;
|
||||
let host: TestHostComponent;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TestHostComponent],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(TestHostComponent);
|
||||
host = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('renders the default color and size classes', () => {
|
||||
const tag = fixture.nativeElement.querySelector('span') as HTMLSpanElement;
|
||||
|
||||
expect(tag.className).toContain('app-tag');
|
||||
expect(tag.className).toContain('app-tag-primary');
|
||||
expect(tag.className).toContain('app-tag-m');
|
||||
expect(tag.textContent?.trim()).toBe('Test');
|
||||
});
|
||||
|
||||
it('adds pill and rounded classes when those inputs are enabled', () => {
|
||||
host.variant = 'pill';
|
||||
host.rounded = true;
|
||||
host.pill = true;
|
||||
fixture.detectChanges();
|
||||
|
||||
const tag = fixture.nativeElement.querySelector('span') as HTMLSpanElement;
|
||||
expect(tag.className).toContain('app-tag-variant-pill');
|
||||
expect(tag.className).toContain('app-tag-rounded');
|
||||
expect(tag.className).toContain('app-tag-pill');
|
||||
});
|
||||
|
||||
it('applies the provided custom colors inline', () => {
|
||||
const tag = fixture.nativeElement.querySelector('span') as HTMLSpanElement;
|
||||
|
||||
expect(tag.style.backgroundColor).toBe('rgb(17, 34, 51)');
|
||||
expect(tag.style.color).toBe('rgb(254, 254, 254)');
|
||||
});
|
||||
});
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookdropFileService} from '../../../features/bookdrop/service/bookdrop-file.service';
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {MetadataBatchStatus} from '../../model/metadata-batch-progress.model';
|
||||
import {MetadataProgressService} from '../../service/metadata-progress.service';
|
||||
import {UnifiedNotificationBoxComponent} from './unified-notification-popover-component';
|
||||
|
||||
describe('UnifiedNotificationBoxComponent', () => {
|
||||
let fixture: ComponentFixture<UnifiedNotificationBoxComponent>;
|
||||
let component: UnifiedNotificationBoxComponent;
|
||||
let activeTasks$: BehaviorSubject<Record<string, unknown>>;
|
||||
let hasPendingFiles$: BehaviorSubject<boolean>;
|
||||
|
||||
beforeEach(async () => {
|
||||
activeTasks$ = new BehaviorSubject<Record<string, unknown>>({});
|
||||
hasPendingFiles$ = new BehaviorSubject(false);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [UnifiedNotificationBoxComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{
|
||||
provide: MetadataProgressService,
|
||||
useValue: {activeTasks$},
|
||||
},
|
||||
{
|
||||
provide: BookdropFileService,
|
||||
useValue: {hasPendingFiles$},
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(UnifiedNotificationBoxComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('reports whether there are metadata tasks to show', () => {
|
||||
let hasMetadataTasks: boolean | undefined;
|
||||
component.hasMetadataTasks$.subscribe(value => {
|
||||
hasMetadataTasks = value;
|
||||
});
|
||||
|
||||
expect(hasMetadataTasks).toBe(false);
|
||||
|
||||
activeTasks$.next({
|
||||
'task-1': {
|
||||
taskId: 'task-1',
|
||||
completed: 1,
|
||||
total: 2,
|
||||
message: 'running',
|
||||
status: MetadataBatchStatus.IN_PROGRESS,
|
||||
review: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(hasMetadataTasks).toBe(true);
|
||||
});
|
||||
|
||||
it('forwards the bookdrop pending-file signal', () => {
|
||||
let hasPendingFiles: boolean | undefined;
|
||||
component.hasPendingBookdropFiles$.subscribe(value => {
|
||||
hasPendingFiles = value;
|
||||
});
|
||||
|
||||
expect(hasPendingFiles).toBe(false);
|
||||
hasPendingFiles$.next(true);
|
||||
expect(hasPendingFiles).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {ResetProgressType, ResetProgressTypes} from './reset-progress-type';
|
||||
|
||||
describe('reset-progress-type', () => {
|
||||
it('keeps the backend compatibility alias for the grimmory reset type', () => {
|
||||
expect(ResetProgressTypes).toEqual({
|
||||
KOREADER: 'KOREADER',
|
||||
GRIMMORY: 'BOOKLORE',
|
||||
KOBO: 'KOBO'
|
||||
});
|
||||
});
|
||||
|
||||
it('narrows the union to the exported reset progress values', () => {
|
||||
expectTypeOf<ResetProgressType>().toEqualTypeOf<'KOREADER' | 'BOOKLORE' | 'KOBO'>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {IconCategoriesHelper} from './icon-categories.helper';
|
||||
|
||||
describe('IconCategoriesHelper', () => {
|
||||
it('creates a prime icon class list from the static categories', () => {
|
||||
const icons = IconCategoriesHelper.createIconList();
|
||||
|
||||
expect(icons[0]).toBe('pi pi-address-book');
|
||||
expect(icons.at(-1)).toBe('pi pi-youtube');
|
||||
expect(new Set(icons).size).toBe(icons.length);
|
||||
expect(icons).toContain('pi pi-book');
|
||||
expect(icons).toContain('pi pi-shield');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {MenuChangeEvent} from './menuchangeevent';
|
||||
|
||||
describe('menuchangeevent', () => {
|
||||
it('supports route-backed menu change events', () => {
|
||||
const event: MenuChangeEvent = {
|
||||
key: 'settings',
|
||||
routeEvent: true
|
||||
};
|
||||
|
||||
expect(event.key).toBe('settings');
|
||||
expect(event.routeEvent).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps routeEvent optional', () => {
|
||||
expectTypeOf<MenuChangeEvent['routeEvent']>().toEqualTypeOf<boolean | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Honest layout coverage needs a host harness for router events, renderer
|
||||
// listeners, overlay subscriptions, body-scroll mutation, and view-child/sidebar interactions.
|
||||
// In its current shape the component is mostly runtime orchestration around global DOM listeners.
|
||||
describe.skip('AppLayoutComponent', () => {
|
||||
it('needs a router-overlay seam to verify menu hiding on navigation and overlay clicks', () => {
|
||||
// TODO(seam): Cover outside-click detection and overlay subscription behavior after router
|
||||
// events and renderer listeners are exposed behind a testable boundary.
|
||||
});
|
||||
|
||||
it('needs a document-style seam to verify sidebar width initialization and body scroll toggling', () => {
|
||||
// TODO(seam): Cover local-storage width hydration and blocked-scroll lifecycle once global
|
||||
// document mutations can be asserted without brittle DOM listener wiring.
|
||||
});
|
||||
});
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {LayoutService} from './app.layout.service';
|
||||
|
||||
describe('LayoutService', () => {
|
||||
let service: LayoutService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [LayoutService],
|
||||
});
|
||||
|
||||
service = TestBed.inject(LayoutService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('detects when the configured theme style changes', () => {
|
||||
expect(service.updateStyle(service.config())).toBe(false);
|
||||
|
||||
service.config.set({
|
||||
...service.config(),
|
||||
theme: 'lara-dark-indigo',
|
||||
});
|
||||
|
||||
expect(service.updateStyle(service.config())).toBe(true);
|
||||
});
|
||||
|
||||
it('toggles the overlay menu and emits overlay-open notifications on desktop', () => {
|
||||
let overlayOpenCount = 0;
|
||||
service.config.set({
|
||||
...service.config(),
|
||||
menuMode: 'overlay',
|
||||
});
|
||||
service.overlayOpen$.subscribe(() => {
|
||||
overlayOpenCount += 1;
|
||||
});
|
||||
|
||||
Object.defineProperty(window, 'innerWidth', {configurable: true, value: 1280});
|
||||
service.onMenuToggle();
|
||||
|
||||
expect(service.state.overlayMenuActive).toBe(true);
|
||||
expect(service.state.staticMenuDesktopInactive).toBe(true);
|
||||
expect(overlayOpenCount).toBe(1);
|
||||
});
|
||||
|
||||
it('toggles the mobile static menu and emits overlay-open notifications on small screens', () => {
|
||||
let overlayOpenCount = 0;
|
||||
service.overlayOpen$.subscribe(() => {
|
||||
overlayOpenCount += 1;
|
||||
});
|
||||
|
||||
Object.defineProperty(window, 'innerWidth', {configurable: true, value: 768});
|
||||
service.onMenuToggle();
|
||||
|
||||
expect(service.state.staticMenuMobileActive).toBe(true);
|
||||
expect(overlayOpenCount).toBe(1);
|
||||
});
|
||||
|
||||
it('derives the replacement theme href from the current config', () => {
|
||||
const replaceThemeLinkSpy = vi.spyOn(service, 'replaceThemeLink').mockImplementation(() => undefined);
|
||||
const themeLink = document.createElement('link');
|
||||
themeLink.id = 'theme-css';
|
||||
themeLink.setAttribute('href', '/themes/lara-light-indigo/theme-light/theme.css');
|
||||
document.body.appendChild(themeLink);
|
||||
|
||||
service._config = {
|
||||
...service._config,
|
||||
theme: 'lara-light-indigo',
|
||||
colorScheme: 'light',
|
||||
};
|
||||
service.config.set({
|
||||
...service.config(),
|
||||
theme: 'lara-dark-indigo',
|
||||
colorScheme: 'dark',
|
||||
});
|
||||
|
||||
service.changeTheme();
|
||||
|
||||
expect(replaceThemeLinkSpy).toHaveBeenCalledWith('/themes/lara-dark-indigo/theme-dark/theme.css');
|
||||
themeLink.remove();
|
||||
});
|
||||
|
||||
it('updates the document root font size when the scale changes', () => {
|
||||
service.changeScale(18);
|
||||
|
||||
expect(document.documentElement.style.fontSize).toBe('18px');
|
||||
});
|
||||
});
|
||||
@@ -104,9 +104,9 @@ export class LayoutService {
|
||||
.split('/')
|
||||
.map((el) =>
|
||||
el == this._config.theme
|
||||
? (el = config.theme)
|
||||
? config.theme
|
||||
: el == `theme-${this._config.colorScheme}`
|
||||
? (el = `theme-${config.colorScheme}`)
|
||||
? `theme-${config.colorScheme}`
|
||||
: el
|
||||
)
|
||||
.join('/');
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real menu coverage needs coordinated signals for libraries, shelves,
|
||||
// magic shelves, authors, books, user permissions, translation changes, and version/dialog
|
||||
// behavior. The component is a large computed-menu assembler, and a low-value shallow spec would
|
||||
// not honestly verify the menu trees that matter.
|
||||
describe.skip('AppMenuComponent', () => {
|
||||
it('needs a menu-data seam to verify computed home/library/shelf/magic-shelf menu trees', () => {
|
||||
// TODO(seam): Cover computed menu composition once the dependent signals/services can be
|
||||
// driven through a stable test harness rather than an all-up runtime mock graph.
|
||||
});
|
||||
|
||||
it('needs a version-dialog and local-storage seam to verify side effects around dialogs and sidebar sizing', () => {
|
||||
// TODO(seam): Cover version dialog and sidebar width behavior after those side effects are
|
||||
// exposed behind a narrower facade.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): This menu item coordinates router state, menu-service broadcasts, user
|
||||
// permission effects, dialog launchers, nested expansion state, and link/view-child behavior.
|
||||
// Useful coverage needs a purpose-built menu host seam, not a brittle isolated mock tangle.
|
||||
describe.skip('AppMenuitemComponent', () => {
|
||||
it('needs a menu-service and router seam to verify active-state propagation and route activation', () => {
|
||||
// TODO(seam): Cover route-driven activation, menu broadcasts, and nested expansion after the
|
||||
// component can be exercised inside a stable menu host harness.
|
||||
});
|
||||
|
||||
it('needs a dialog/link seam to verify openDialog, triggerLink, and icon/count formatting behavior', () => {
|
||||
// TODO(seam): Cover command, dialog, and link behavior once those side effects are surfaced
|
||||
// behind a narrower, test-friendly contract.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {MenuService} from './app.menu.service';
|
||||
|
||||
describe('MenuService', () => {
|
||||
it('broadcasts menu state changes and reset events', () => {
|
||||
const service = new MenuService();
|
||||
const menuEvents: unknown[] = [];
|
||||
const resets: unknown[] = [];
|
||||
|
||||
const menuSubscription = service.menuSource$.subscribe(event => menuEvents.push(event));
|
||||
const resetSubscription = service.resetSource$.subscribe(event => resets.push(event));
|
||||
|
||||
service.onMenuStateChange({key: 'settings'});
|
||||
service.reset();
|
||||
|
||||
expect(menuEvents).toEqual([{key: 'settings'}]);
|
||||
expect(resets).toEqual([true]);
|
||||
|
||||
menuSubscription.unsubscribe();
|
||||
resetSubscription.unsubscribe();
|
||||
});
|
||||
});
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {VersionService} from '../../../../service/version.service';
|
||||
import {VersionChangelogDialogComponent} from './version-changelog-dialog.component';
|
||||
|
||||
describe('VersionChangelogDialogComponent', () => {
|
||||
let fixture: ComponentFixture<VersionChangelogDialogComponent>;
|
||||
let component: VersionChangelogDialogComponent;
|
||||
let versionService: {getChangelog: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
versionService = {
|
||||
getChangelog: vi.fn(() => of([
|
||||
{
|
||||
version: '1.2.3',
|
||||
name: 'Stable',
|
||||
changelog: '## Added\n- New feature',
|
||||
url: 'https://example.com/releases/1.2.3',
|
||||
publishedAt: '2026-03-26T00:00:00Z',
|
||||
},
|
||||
])),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VersionChangelogDialogComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: VersionService, useValue: versionService},
|
||||
{provide: DynamicDialogRef, useValue: {close: vi.fn()}},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(VersionChangelogDialogComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads the changelog on init and clears the loading state', () => {
|
||||
component.ngOnInit();
|
||||
|
||||
expect(versionService.getChangelog).toHaveBeenCalled();
|
||||
expect(component.changelog).toHaveLength(1);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('clears the loading state when the changelog request fails', () => {
|
||||
versionService.getChangelog.mockReturnValueOnce(
|
||||
throwError(() => new Error('failed'))
|
||||
);
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.changelog).toEqual([]);
|
||||
expect(component.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('converts markdown to sanitized HTML and normalizes headings to h3', () => {
|
||||
const html = component.markdownToHtml('## Heading\n\n<script>alert(1)</script><b>Safe</b>');
|
||||
|
||||
expect(html).toContain('<h3');
|
||||
expect(html).not.toContain('<h2');
|
||||
expect(html).not.toContain('<script>');
|
||||
expect(html).toContain('<b>Safe</b>');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): This component is effectively a thin runtime bridge to layout state plus
|
||||
// a nested menu tree. A worthwhile spec should be written together with a host/layout seam rather
|
||||
// than as an empty shell assertion.
|
||||
describe.skip('AppSidebarComponent', () => {
|
||||
it('needs a layout host seam to verify sidebar/menu integration without shallow shell noise', () => {
|
||||
// TODO(seam): Cover layout state and nested menu rendering once the sidebar is exercised
|
||||
// through the same host harness that will be needed for layout/menu behavior.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real topbar coverage needs a dedicated host harness for view queries,
|
||||
// timer-driven pulse behavior, router navigation, auth/logout, user-permission signals,
|
||||
// metadata/bookdrop streams, menu overlays, and transloco language switching. In the current
|
||||
// shape those concerns are fused tightly enough that a shallow spec would be noisy and dishonest.
|
||||
describe.skip('AppTopBarComponent', () => {
|
||||
it('needs a host-view seam to verify menu visibility, pulse state, and notification/task aggregation', () => {
|
||||
// TODO(seam): Cover timer-driven pulse resets, task counts, and bookdrop visibility after
|
||||
// the component exposes a narrower facade over its view and timer dependencies.
|
||||
});
|
||||
|
||||
it('needs a navigation and language seam to verify route actions and active language switching', () => {
|
||||
// TODO(seam): Cover router commands, stats menu composition, and localStorage language writes
|
||||
// once those side effects can be driven without mocking the entire topbar runtime.
|
||||
});
|
||||
});
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BackgroundUploadService} from './background-upload.service';
|
||||
|
||||
describe('BackgroundUploadService', () => {
|
||||
let service: BackgroundUploadService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BackgroundUploadService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BackgroundUploadService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('uploads a file as multipart form data and maps the returned URL', () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
const file = new File(['image-bytes'], 'background.png', {type: 'image/png'});
|
||||
let result: string | undefined;
|
||||
|
||||
service.uploadFile(file).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/background/upload'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body instanceof FormData).toBe(true);
|
||||
expect((request.request.body as FormData).get('file')).toBe(file);
|
||||
request.flush({url: 'https://example.test/background.png'});
|
||||
|
||||
expect(result).toBe('https://example.test/background.png');
|
||||
expect(logSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads a background URL and maps the returned URL', () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
let result: string | undefined;
|
||||
|
||||
service.uploadUrl('https://example.test/source.jpg').subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/background/url'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({url: 'https://example.test/source.jpg'});
|
||||
request.flush({url: 'https://example.test/normalized.jpg'});
|
||||
|
||||
expect(result).toBe('https://example.test/normalized.jpg');
|
||||
expect(logSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {FaviconService} from './favicon-service';
|
||||
|
||||
describe('FaviconService', () => {
|
||||
it('updates an existing favicon link with a generated SVG URL', () => {
|
||||
const favicon = {type: '', href: ''} as HTMLLinkElement;
|
||||
const querySelectorSpy = vi.spyOn(document, 'querySelector').mockReturnValue(favicon);
|
||||
const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:favicon');
|
||||
|
||||
const service = new FaviconService();
|
||||
service.updateFavicon('#123456');
|
||||
|
||||
expect(querySelectorSpy).toHaveBeenCalledWith("link[rel*='icon']");
|
||||
expect(createObjectUrlSpy).toHaveBeenCalledOnce();
|
||||
expect(favicon.type).toBe('image/svg+xml');
|
||||
expect(favicon.href).toBe('blob:favicon');
|
||||
});
|
||||
|
||||
it('creates and appends a favicon link when one does not already exist', () => {
|
||||
const appended: HTMLLinkElement[] = [];
|
||||
const favicon = {rel: '', type: '', href: ''} as HTMLLinkElement;
|
||||
|
||||
vi.spyOn(document, 'querySelector').mockReturnValue(null);
|
||||
vi.spyOn(document, 'createElement').mockReturnValue(favicon);
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation(node => {
|
||||
appended.push(node as HTMLLinkElement);
|
||||
return node;
|
||||
});
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:new-favicon');
|
||||
|
||||
const service = new FaviconService();
|
||||
service.updateFavicon('#abcdef');
|
||||
|
||||
expect(appended).toEqual([favicon]);
|
||||
expect(favicon.rel).toBe('icon');
|
||||
expect(favicon.type).toBe('image/svg+xml');
|
||||
expect(favicon.href).toBe('blob:new-favicon');
|
||||
});
|
||||
});
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs a stable app-config signal seam plus favicon
|
||||
// side-effect interception. The component is mostly computed/effect wiring over `AppConfigService`
|
||||
// state, palette tokens, and `FaviconService`, so a useful spec should validate those reactions
|
||||
// without reaching through private signal internals.
|
||||
describe.skip('ThemeConfiguratorComponent', () => {
|
||||
it('needs an app-config seam to verify selected palette derivation and color updates', () => {
|
||||
// TODO(seam): Cover computed primary/surface selections and updateColors state writes once
|
||||
// the config signal can be driven through a stable public harness.
|
||||
});
|
||||
|
||||
it('needs a favicon side-effect seam to verify palette-to-favicon synchronization', () => {
|
||||
// TODO(seam): Cover favicon updates after exposing a testable effect boundary around the
|
||||
// config-driven favicon sync.
|
||||
});
|
||||
});
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {BackgroundUploadService} from '../background-upload.service';
|
||||
import {UploadDialogComponent} from './upload-dialog.component';
|
||||
|
||||
describe('UploadDialogComponent', () => {
|
||||
let fixture: ComponentFixture<UploadDialogComponent>;
|
||||
let component: UploadDialogComponent;
|
||||
let dialogRef: {close: ReturnType<typeof vi.fn>};
|
||||
let backgroundUploadService: {
|
||||
uploadFile: ReturnType<typeof vi.fn>;
|
||||
uploadUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let translocoService: TranslocoService;
|
||||
|
||||
beforeEach(async () => {
|
||||
dialogRef = {
|
||||
close: vi.fn(),
|
||||
};
|
||||
backgroundUploadService = {
|
||||
uploadFile: vi.fn(() => of('https://example.com/uploaded.png')),
|
||||
uploadUrl: vi.fn(() => of('https://example.com/from-url.png')),
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [UploadDialogComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
{provide: DynamicDialogRef, useValue: dialogRef},
|
||||
{provide: BackgroundUploadService, useValue: backgroundUploadService},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(UploadDialogComponent);
|
||||
component = fixture.componentInstance;
|
||||
translocoService = TestBed.inject(TranslocoService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('stores the selected file and clears the URL field', () => {
|
||||
const file = new File(['image'], 'cover.png', {type: 'image/png'});
|
||||
const event = {
|
||||
target: {
|
||||
files: [file],
|
||||
},
|
||||
} as unknown as Event;
|
||||
component.uploadImageUrl = 'https://example.com/old.png';
|
||||
|
||||
component.onFileSelected(event);
|
||||
|
||||
expect(component.uploadFile).toBe(file);
|
||||
expect(component.uploadImageUrl).toBe('');
|
||||
});
|
||||
|
||||
it('requires either a file or a URL before uploading', () => {
|
||||
component.submit();
|
||||
|
||||
expect(component.uploadError).toBe(
|
||||
translocoService.translate('layout.uploadDialog.errorNoInput')
|
||||
);
|
||||
expect(backgroundUploadService.uploadFile).not.toHaveBeenCalled();
|
||||
expect(backgroundUploadService.uploadUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads a selected file and closes the dialog with the returned URL', () => {
|
||||
const file = new File(['image'], 'cover.png', {type: 'image/png'});
|
||||
component.uploadFile = file;
|
||||
|
||||
component.submit();
|
||||
|
||||
expect(backgroundUploadService.uploadFile).toHaveBeenCalledWith(file);
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({
|
||||
imageUrl: 'https://example.com/uploaded.png',
|
||||
});
|
||||
});
|
||||
|
||||
it('uploads a trimmed URL and closes the dialog with the returned value', () => {
|
||||
component.uploadImageUrl = ' https://example.com/bg.png ';
|
||||
|
||||
component.submit();
|
||||
|
||||
expect(backgroundUploadService.uploadUrl).toHaveBeenCalledWith('https://example.com/bg.png');
|
||||
expect(dialogRef.close).toHaveBeenCalledWith({
|
||||
imageUrl: 'https://example.com/from-url.png',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error when the upload succeeds without returning an image URL', () => {
|
||||
backgroundUploadService.uploadUrl.mockReturnValueOnce(of(''));
|
||||
component.uploadImageUrl = 'https://example.com/bg.png';
|
||||
|
||||
component.submit();
|
||||
|
||||
expect(component.uploadError).toBe('Failed to upload image.');
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a generic upload error when the upload request fails', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
backgroundUploadService.uploadFile.mockReturnValueOnce(
|
||||
throwError(() => new Error('boom'))
|
||||
);
|
||||
component.uploadFile = new File(['image'], 'cover.png', {type: 'image/png'});
|
||||
|
||||
component.submit();
|
||||
|
||||
expect(component.uploadError).toBe('Upload failed. Please try again.');
|
||||
expect(console.error).toHaveBeenCalled();
|
||||
expect(dialogRef.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('closes the dialog when cancel is clicked', () => {
|
||||
component.cancel();
|
||||
|
||||
expect(dialogRef.close).toHaveBeenCalledWith();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import Aura from '@primeuix/themes/aura';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import ExtendedAura from './theme-palette-extend';
|
||||
|
||||
describe('theme-palette-extend', () => {
|
||||
it('extends Aura with the custom primitive palettes', () => {
|
||||
const primitive = Aura.primitive as Record<string, Record<string, string>>;
|
||||
|
||||
expect(ExtendedAura).toBe(Aura);
|
||||
expect(primitive).toBeTruthy();
|
||||
expect(primitive['coralSunset']['500']).toBe('#ef7550');
|
||||
expect(primitive['skyBlue']['700']).toBe('#2e88e6');
|
||||
expect(primitive['dustyNeutral']['950']).toBe('#2f2821');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {hasMetadataWriter, isFieldEmbeddable} from './embeddable-fields.config';
|
||||
|
||||
describe('embeddable-fields.config', () => {
|
||||
it('reports writer support only for embeddable book types', () => {
|
||||
expect(hasMetadataWriter('EPUB')).toBe(true);
|
||||
expect(hasMetadataWriter('PDF')).toBe(true);
|
||||
expect(hasMetadataWriter('CBX')).toBe(true);
|
||||
expect(hasMetadataWriter('AUDIOBOOK')).toBe(true);
|
||||
expect(hasMetadataWriter('FB2')).toBe(false);
|
||||
expect(hasMetadataWriter(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('checks embeddable field membership by book type', () => {
|
||||
expect(isFieldEmbeddable('EPUB', 'title')).toBe(true);
|
||||
expect(isFieldEmbeddable('EPUB', 'narrator')).toBe(false);
|
||||
expect(isFieldEmbeddable('AUDIOBOOK', 'narrator')).toBe(true);
|
||||
expect(isFieldEmbeddable('CBX', 'comicIssueNumber')).toBe(true);
|
||||
expect(isFieldEmbeddable(undefined, 'title')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import * as metadataIndex from './index';
|
||||
import {getTopFields} from './metadata-field.config';
|
||||
import {hasMetadataWriter} from './embeddable-fields.config';
|
||||
|
||||
describe('shared metadata index', () => {
|
||||
it('re-exports metadata field helpers', () => {
|
||||
expect(metadataIndex.getTopFields).toBe(getTopFields);
|
||||
});
|
||||
|
||||
it('re-exports embeddable field helpers', () => {
|
||||
expect(metadataIndex.hasMetadataWriter).toBe(hasMetadataWriter);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {
|
||||
ALL_COMIC_METADATA_FIELDS,
|
||||
ALL_METADATA_FIELDS,
|
||||
COMIC_FORM_TO_MODEL_LOCK,
|
||||
getArrayFields,
|
||||
getBookDetailsFields,
|
||||
getBottomFields,
|
||||
getProviderFields,
|
||||
getSeriesFields,
|
||||
getTextareaFields,
|
||||
getTopFields
|
||||
} from './metadata-field.config';
|
||||
|
||||
describe('metadata-field.config', () => {
|
||||
it('exposes stable grouped field selectors', () => {
|
||||
expect(getTopFields().map((field) => field.controlName)).toEqual([
|
||||
'title',
|
||||
'subtitle',
|
||||
'publisher',
|
||||
'publishedDate'
|
||||
]);
|
||||
expect(getSeriesFields().map((field) => field.controlName)).toEqual([
|
||||
'seriesName',
|
||||
'seriesNumber',
|
||||
'seriesTotal'
|
||||
]);
|
||||
expect(getBookDetailsFields().map((field) => field.controlName)).toEqual([
|
||||
'language',
|
||||
'isbn10',
|
||||
'isbn13',
|
||||
'pageCount'
|
||||
]);
|
||||
});
|
||||
|
||||
it('splits array and textarea metadata fields correctly', () => {
|
||||
expect(getArrayFields().map((field) => field.controlName)).toEqual(['authors', 'categories', 'moods', 'tags']);
|
||||
expect(getTextareaFields().map((field) => field.controlName)).toEqual(['description']);
|
||||
});
|
||||
|
||||
it('filters provider-backed fields when provider flags are supplied', () => {
|
||||
const enabledFields = {
|
||||
googleId: true,
|
||||
asin: false,
|
||||
amazonRating: false,
|
||||
amazonReviewCount: false,
|
||||
goodreadsId: false,
|
||||
goodreadsRating: false,
|
||||
goodreadsReviewCount: false,
|
||||
hardcoverId: false,
|
||||
hardcoverBookId: false,
|
||||
hardcoverRating: false,
|
||||
hardcoverReviewCount: false,
|
||||
comicvineId: false,
|
||||
lubimyczytacId: false,
|
||||
lubimyczytacRating: false,
|
||||
ranobedbId: false,
|
||||
ranobedbRating: false,
|
||||
audibleId: false,
|
||||
audibleRating: false,
|
||||
audibleReviewCount: false
|
||||
};
|
||||
|
||||
expect(getProviderFields(enabledFields).map((field) => field.controlName)).toEqual(['googleId']);
|
||||
expect(getBottomFields(enabledFields).some((field) => field.controlName === 'googleId')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps comic metadata fields and lock mappings aligned', () => {
|
||||
expect(ALL_COMIC_METADATA_FIELDS.length).toBeGreaterThan(0);
|
||||
expect(COMIC_FORM_TO_MODEL_LOCK['comicIssueNumberLocked']).toBe('issueNumberLocked');
|
||||
expect(ALL_METADATA_FIELDS.some((field) => field.controlName === 'title')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import {FormControl, FormGroup} from '@angular/forms';
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {MetadataFormBuilder} from './metadata-form.builder';
|
||||
|
||||
describe('MetadataFormBuilder', () => {
|
||||
const builder = new MetadataFormBuilder();
|
||||
|
||||
it('builds controls with defaults for requested, audiobook, comic, and cover fields', () => {
|
||||
const form = builder.buildForm(true, [
|
||||
{label: 'Title', controlName: 'title', lockedKey: 'titleLocked', fetchedKey: 'title', type: 'string'},
|
||||
{label: 'Authors', controlName: 'authors', lockedKey: 'authorsLocked', fetchedKey: 'authors', type: 'array'},
|
||||
{label: 'Series #', controlName: 'seriesNumber', lockedKey: 'seriesNumberLocked', fetchedKey: 'seriesNumber', type: 'number'},
|
||||
]);
|
||||
|
||||
expect(form.get('title')?.value).toBe('');
|
||||
expect(form.get('authors')?.value).toEqual([]);
|
||||
expect(form.get('seriesNumber')?.value).toBeNull();
|
||||
expect(form.get('titleLocked')?.value).toBe(false);
|
||||
expect(form.get('narrator')?.value).toBe('');
|
||||
expect(form.get('abridged')?.value).toBeNull();
|
||||
expect(form.get('comicIssueNumber')?.value).toBe('');
|
||||
expect(form.get('comicCharacters')?.value).toEqual([]);
|
||||
expect(form.get('thumbnailUrl')?.value).toBe('');
|
||||
expect(form.get('coverLocked')?.value).toBe(false);
|
||||
expect(form.get('audiobookCoverLocked')?.value).toBe(false);
|
||||
});
|
||||
|
||||
it('omits locked controls when the caller disables them', () => {
|
||||
const form = builder.buildForm(false, [
|
||||
{label: 'Title', controlName: 'title', lockedKey: 'titleLocked', fetchedKey: 'title', type: 'string'},
|
||||
]);
|
||||
|
||||
expect(form.get('title')).toBeTruthy();
|
||||
expect(form.get('titleLocked')).toBeNull();
|
||||
expect(form.get('coverLocked')).toBeNull();
|
||||
expect(form.get('audiobookCoverLocked')).toBeNull();
|
||||
});
|
||||
|
||||
it('applies lock states after re-enabling unlocked controls first', () => {
|
||||
const form = new FormGroup({
|
||||
title: new FormControl('Title'),
|
||||
titleLocked: new FormControl(false),
|
||||
authors: new FormControl<string[]>(['A']),
|
||||
authorsLocked: new FormControl(false),
|
||||
narrator: new FormControl('Narrator'),
|
||||
narratorLocked: new FormControl(false),
|
||||
comicIssueNumber: new FormControl('7'),
|
||||
comicIssueNumberLocked: new FormControl(false),
|
||||
});
|
||||
|
||||
form.get('title')?.disable();
|
||||
form.get('authors')?.disable();
|
||||
|
||||
builder.applyLockStates(form, {
|
||||
titleLocked: true,
|
||||
narratorLocked: true,
|
||||
comicIssueNumberLocked: false,
|
||||
});
|
||||
|
||||
expect(form.get('title')?.disabled).toBe(true);
|
||||
expect(form.get('authors')?.enabled).toBe(true);
|
||||
expect(form.get('narrator')?.disabled).toBe(true);
|
||||
expect(form.get('comicIssueNumber')?.enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('toggles all locked fields and matching control enabled state together', () => {
|
||||
const form = new FormGroup({
|
||||
title: new FormControl('Title'),
|
||||
titleLocked: new FormControl(false),
|
||||
authors: new FormControl<string[]>(['A']),
|
||||
authorsLocked: new FormControl(false),
|
||||
});
|
||||
|
||||
builder.setAllFieldsLocked(form, true);
|
||||
expect(form.get('titleLocked')?.value).toBe(true);
|
||||
expect(form.get('authorsLocked')?.value).toBe(true);
|
||||
expect(form.get('title')?.disabled).toBe(true);
|
||||
expect(form.get('authors')?.disabled).toBe(true);
|
||||
|
||||
builder.setAllFieldsLocked(form, false);
|
||||
expect(form.get('titleLocked')?.value).toBe(false);
|
||||
expect(form.get('authorsLocked')?.value).toBe(false);
|
||||
expect(form.get('title')?.enabled).toBe(true);
|
||||
expect(form.get('authors')?.enabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import {FormControl, FormGroup} from '@angular/forms';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookMetadata} from '../../features/book/model/book.model';
|
||||
import {MetadataUtilsService} from './metadata-utils.service';
|
||||
|
||||
describe('MetadataUtilsService', () => {
|
||||
const service = new MetadataUtilsService();
|
||||
|
||||
function createForm(): FormGroup {
|
||||
return new FormGroup({
|
||||
title: new FormControl(''),
|
||||
titleLocked: new FormControl(false),
|
||||
authors: new FormControl<string[]>([]),
|
||||
authorsLocked: new FormControl(false),
|
||||
seriesName: new FormControl('Existing Series'),
|
||||
seriesNameLocked: new FormControl(true),
|
||||
pageCount: new FormControl<number | null>(null),
|
||||
pageCountLocked: new FormControl(false),
|
||||
description: new FormControl(''),
|
||||
descriptionLocked: new FormControl(false),
|
||||
});
|
||||
}
|
||||
|
||||
it('copies a non-empty fetched field into the form and marks it as copied', () => {
|
||||
const form = createForm();
|
||||
const copiedFields: Record<string, boolean> = {};
|
||||
const metadata = {title: 'Hyperion'} as BookMetadata;
|
||||
|
||||
const copied = service.copyFieldToForm('title', metadata, form, copiedFields);
|
||||
|
||||
expect(copied).toBe(true);
|
||||
expect(form.get('title')?.value).toBe('Hyperion');
|
||||
expect(copiedFields['title']).toBe(true);
|
||||
});
|
||||
|
||||
it('does not copy empty fetched values into the form', () => {
|
||||
const form = createForm();
|
||||
const copiedFields: Record<string, boolean> = {};
|
||||
const metadata = {title: ''} as BookMetadata;
|
||||
|
||||
const copied = service.copyFieldToForm('title', metadata, form, copiedFields);
|
||||
|
||||
expect(copied).toBe(false);
|
||||
expect(form.get('title')?.value).toBe('');
|
||||
expect(copiedFields['title']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('copies only unlocked empty fields that have fetched values', () => {
|
||||
const form = createForm();
|
||||
const copyCallback = vi.fn();
|
||||
const metadata = {
|
||||
title: 'Hyperion',
|
||||
authors: ['Dan Simmons'],
|
||||
seriesName: 'Should Stay Locked',
|
||||
pageCount: null,
|
||||
} as BookMetadata;
|
||||
|
||||
service.copyMissingFields(metadata, form, {}, copyCallback);
|
||||
|
||||
expect(copyCallback).toHaveBeenCalledTimes(2);
|
||||
expect(copyCallback).toHaveBeenCalledWith('title');
|
||||
expect(copyCallback).toHaveBeenCalledWith('authors');
|
||||
});
|
||||
|
||||
it('copies all unlocked non-empty fields except excluded ones', () => {
|
||||
const form = createForm();
|
||||
const copyCallback = vi.fn();
|
||||
const metadata = {
|
||||
title: 'Hyperion',
|
||||
authors: ['Dan Simmons'],
|
||||
seriesName: 'Locked Series',
|
||||
thumbnailUrl: 'https://example.test/cover.jpg',
|
||||
} as BookMetadata;
|
||||
|
||||
service.copyAllFields(metadata, form, copyCallback);
|
||||
|
||||
expect(copyCallback).toHaveBeenCalledTimes(2);
|
||||
expect(copyCallback).toHaveBeenCalledWith('title');
|
||||
expect(copyCallback).toHaveBeenCalledWith('authors');
|
||||
});
|
||||
|
||||
it('detects empty values consistently', () => {
|
||||
expect(service.isValueEmpty(null)).toBe(true);
|
||||
expect(service.isValueEmpty(undefined)).toBe(true);
|
||||
expect(service.isValueEmpty('')).toBe(true);
|
||||
expect(service.isValueEmpty([])).toBe(true);
|
||||
expect(service.isValueEmpty(['value'])).toBe(false);
|
||||
expect(service.isValueEmpty('value')).toBe(false);
|
||||
});
|
||||
|
||||
it('normalizes arrays for comparison without caring about order', () => {
|
||||
expect(service.areFieldsEqual(['b', 'a'], ['a', 'b'])).toBe(true);
|
||||
expect(service.areFieldsEqual('3', 3)).toBe(true);
|
||||
expect(service.areFieldsEqual(['a'], ['a', 'b'])).toBe(false);
|
||||
});
|
||||
|
||||
it('tracks when form values differ from the original or fetched metadata', () => {
|
||||
const form = createForm();
|
||||
form.get('authors')?.setValue(['beta', 'alpha']);
|
||||
form.get('title')?.setValue('Edited Title');
|
||||
|
||||
const original = {
|
||||
authors: ['alpha', 'beta'],
|
||||
title: 'Original Title',
|
||||
} as BookMetadata;
|
||||
const fetched = {
|
||||
authors: ['other'],
|
||||
title: 'Fetched Title',
|
||||
} as BookMetadata;
|
||||
|
||||
expect(service.isValueChanged('authors', form, original)).toBe(false);
|
||||
expect(service.isValueChanged('title', form, original)).toBe(true);
|
||||
expect(service.isFetchedDifferent('authors', form, fetched)).toBe(true);
|
||||
expect(service.isFetchedDifferent('title', form, fetched)).toBe(true);
|
||||
});
|
||||
|
||||
it('resets a field to the original value and clears copied and hovered flags', () => {
|
||||
const form = createForm();
|
||||
form.get('title')?.setValue('Edited Title');
|
||||
|
||||
const copiedFields = {title: true};
|
||||
const hoveredFields = {title: true};
|
||||
const original = {title: 'Original Title'} as BookMetadata;
|
||||
|
||||
service.resetField('title', form, original, copiedFields, hoveredFields);
|
||||
|
||||
expect(form.get('title')?.value).toBe('Original Title');
|
||||
expect(copiedFields['title']).toBe(false);
|
||||
expect(hoveredFields['title']).toBe(false);
|
||||
});
|
||||
|
||||
it('patches metadata arrays as sorted values and applies lock defaults', () => {
|
||||
const form = new FormGroup({
|
||||
authors: new FormControl<string[]>([]),
|
||||
authorsLocked: new FormControl(false),
|
||||
title: new FormControl(''),
|
||||
titleLocked: new FormControl(false),
|
||||
});
|
||||
const metadata = {
|
||||
authors: ['zeta', 'alpha'],
|
||||
authorsLocked: true,
|
||||
title: 'Patched Title',
|
||||
titleLocked: false,
|
||||
} as BookMetadata;
|
||||
|
||||
service.patchMetadataToForm(metadata, form, [
|
||||
{controlName: 'authors', lockedKey: 'authorsLocked', type: 'array'},
|
||||
{controlName: 'title', lockedKey: 'titleLocked', type: 'string'},
|
||||
]);
|
||||
|
||||
expect(form.get('authors')?.value).toEqual(['alpha', 'zeta']);
|
||||
expect(form.get('authorsLocked')?.value).toBe(true);
|
||||
expect(form.get('title')?.value).toBe('Patched Title');
|
||||
expect(form.get('titleLocked')?.value).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {
|
||||
AppSettingKey,
|
||||
AppSettings,
|
||||
MetadataMatchWeights,
|
||||
OidcTestResult
|
||||
} from './app-settings.model';
|
||||
|
||||
describe('app-settings.model', () => {
|
||||
it('exposes stable keys for persisted app settings', () => {
|
||||
expect(AppSettingKey.AUTO_BOOK_SEARCH).toBe('AUTO_BOOK_SEARCH');
|
||||
expect(AppSettingKey.METADATA_PROVIDER_SETTINGS).toBe('METADATA_PROVIDER_SETTINGS');
|
||||
expect(AppSettingKey.OIDC_FORCE_ONLY_MODE).toBe('OIDC_FORCE_ONLY_MODE');
|
||||
});
|
||||
|
||||
it('keeps metadata match weights numerically typed', () => {
|
||||
const weights: MetadataMatchWeights = {
|
||||
title: 10,
|
||||
subtitle: 5,
|
||||
description: 3,
|
||||
authors: 10,
|
||||
publisher: 2,
|
||||
publishedDate: 2,
|
||||
seriesName: 4,
|
||||
seriesNumber: 4,
|
||||
seriesTotal: 2,
|
||||
isbn13: 8,
|
||||
isbn10: 8,
|
||||
language: 2,
|
||||
pageCount: 1,
|
||||
categories: 2,
|
||||
amazonRating: 1,
|
||||
amazonReviewCount: 1,
|
||||
goodreadsRating: 1,
|
||||
goodreadsReviewCount: 1,
|
||||
hardcoverRating: 1,
|
||||
hardcoverReviewCount: 1,
|
||||
doubanRating: 1,
|
||||
doubanReviewCount: 1,
|
||||
lubimyczytacRating: 1,
|
||||
ranobedbRating: 1,
|
||||
audibleRating: 1,
|
||||
audibleReviewCount: 1,
|
||||
coverImage: 6
|
||||
};
|
||||
|
||||
expect(weights.title).toBeGreaterThan(weights.coverImage);
|
||||
expectTypeOf(weights.coverImage).toEqualTypeOf<number>();
|
||||
});
|
||||
|
||||
it('supports OIDC test results and app-setting contract typing', () => {
|
||||
const result: OidcTestResult = {
|
||||
success: false,
|
||||
checks: [
|
||||
{name: 'issuer', status: 'PASS', message: 'reachable'},
|
||||
{name: 'jwks', status: 'WARN', message: 'slow'}
|
||||
]
|
||||
};
|
||||
|
||||
expect(result.checks[1].status).toBe('WARN');
|
||||
expectTypeOf<AppSettings['diskType']>().toEqualTypeOf<string>();
|
||||
expectTypeOf<AppSettings['oidcSessionDurationHours']>().toEqualTypeOf<number | null>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {AppState} from './app-state.model';
|
||||
|
||||
describe('app-state.model', () => {
|
||||
it('supports partially specified visual state presets', () => {
|
||||
const appState: AppState = {
|
||||
preset: 'midnight',
|
||||
primary: '#112233'
|
||||
};
|
||||
|
||||
expect(appState.preset).toBe('midnight');
|
||||
expect(appState.surface).toBeUndefined();
|
||||
});
|
||||
|
||||
it('keeps each field optional and string-based', () => {
|
||||
expectTypeOf<AppState['preset']>().toEqualTypeOf<string | undefined>();
|
||||
expectTypeOf<AppState['primary']>().toEqualTypeOf<string | undefined>();
|
||||
expectTypeOf<AppState['surface']>().toEqualTypeOf<string | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {FontFormat, formatFileSize} from './custom-font.model';
|
||||
|
||||
describe('custom-font model', () => {
|
||||
it('exposes stable font format enums', () => {
|
||||
expect(FontFormat.TTF).toBe('TTF');
|
||||
expect(FontFormat.OTF).toBe('OTF');
|
||||
expect(FontFormat.WOFF).toBe('WOFF');
|
||||
expect(FontFormat.WOFF2).toBe('WOFF2');
|
||||
});
|
||||
|
||||
it('formats file sizes across byte, kilobyte, and megabyte ranges', () => {
|
||||
expect(formatFileSize(0)).toBe('0 Bytes');
|
||||
expect(formatFileSize(512)).toBe('512 Bytes');
|
||||
expect(formatFileSize(1536)).toBe('1.5 KB');
|
||||
expect(formatFileSize(2 * 1024 * 1024)).toBe('2 MB');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {MetadataBatchStatus, MetadataBatchStatusLabels} from './metadata-batch-progress.model';
|
||||
|
||||
describe('metadata-batch-progress model', () => {
|
||||
it('keeps the status enum and labels in sync', () => {
|
||||
expect(MetadataBatchStatus.IN_PROGRESS).toBe('IN_PROGRESS');
|
||||
expect(MetadataBatchStatus.COMPLETED).toBe('COMPLETED');
|
||||
expect(MetadataBatchStatus.ERROR).toBe('ERROR');
|
||||
expect(MetadataBatchStatus.CANCELLED).toBe('CANCELLED');
|
||||
|
||||
expect(MetadataBatchStatusLabels).toEqual({
|
||||
[MetadataBatchStatus.IN_PROGRESS]: 'In Progress',
|
||||
[MetadataBatchStatus.COMPLETED]: 'Completed',
|
||||
[MetadataBatchStatus.ERROR]: 'Error',
|
||||
[MetadataBatchStatus.CANCELLED]: 'Cancelled',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {OidcGroupMapping} from './oidc-group-mapping.model';
|
||||
|
||||
describe('oidc-group-mapping.model', () => {
|
||||
it('supports group claims with library-specific permissions', () => {
|
||||
const mapping: OidcGroupMapping = {
|
||||
id: 1,
|
||||
oidcGroupClaim: 'admins',
|
||||
isAdmin: true,
|
||||
permissions: ['books.read', 'books.write'],
|
||||
libraryIds: [10, 11],
|
||||
description: 'Admin access'
|
||||
};
|
||||
|
||||
expect(mapping.libraryIds).toEqual([10, 11]);
|
||||
expect(mapping.isAdmin).toBe(true);
|
||||
expectTypeOf(mapping.permissions).toEqualTypeOf<string[]>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {APIException} from './api-exception.model';
|
||||
|
||||
describe('api-exception.model', () => {
|
||||
it('captures API exception payloads with optional details', () => {
|
||||
const error: APIException = {
|
||||
status: 500,
|
||||
message: 'Boom',
|
||||
timestamp: '2026-03-26T10:00:00Z',
|
||||
error: 'Internal Server Error'
|
||||
};
|
||||
|
||||
expect(error.status).toBe(500);
|
||||
expect(error.message).toBe('Boom');
|
||||
expectTypeOf(error.timestamp).toEqualTypeOf<string | undefined>();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {AnnotationService} from './annotation.service';
|
||||
|
||||
describe('AnnotationService', () => {
|
||||
const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/annotations`;
|
||||
|
||||
let service: AnnotationService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
AnnotationService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(AnnotationService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads annotations for a book', () => {
|
||||
service.getAnnotationsForBook(5).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/book/5`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('creates and updates annotations', () => {
|
||||
const createRequest = {
|
||||
bookId: 5,
|
||||
cfi: 'epubcfi(/6/8)',
|
||||
text: 'Important passage',
|
||||
};
|
||||
|
||||
service.createAnnotation(createRequest).subscribe();
|
||||
const createHttpRequest = httpTestingController.expectOne(baseUrl);
|
||||
expect(createHttpRequest.request.method).toBe('POST');
|
||||
expect(createHttpRequest.request.body).toEqual(createRequest);
|
||||
createHttpRequest.flush({...createRequest, id: 8, color: '#ff0', style: 'highlight', createdAt: '2024-01-01'});
|
||||
|
||||
const updateRequest = {
|
||||
note: 'Review later',
|
||||
style: 'underline' as const,
|
||||
};
|
||||
|
||||
service.updateAnnotation(8, updateRequest).subscribe();
|
||||
const updateHttpRequest = httpTestingController.expectOne(`${baseUrl}/8`);
|
||||
expect(updateHttpRequest.request.method).toBe('PUT');
|
||||
expect(updateHttpRequest.request.body).toEqual(updateRequest);
|
||||
updateHttpRequest.flush({
|
||||
...createRequest,
|
||||
...updateRequest,
|
||||
id: 8,
|
||||
color: '#ff0',
|
||||
createdAt: '2024-01-01',
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes annotations by id', () => {
|
||||
service.deleteAnnotation(8).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/8`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs a theme-runtime seam around Prime theme tokens,
|
||||
// localStorage hydration, DOM mutation, and browser-only effects so app state initialization can be
|
||||
// asserted without changing runtime code.
|
||||
describe.skip('AppConfigService', () => {
|
||||
it('needs a browser storage and theme-token seam to validate state hydration and persistence effects', () => {
|
||||
// Intentionally skipped until storage and theme runtime hooks are controllable in tests.
|
||||
});
|
||||
|
||||
it('needs a document mutation seam to validate theme updates without coupling the spec to runtime DOM side effects', () => {
|
||||
// Intentionally skipped until DOM-side theme application can be driven deterministically.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {APP_SETTINGS_QUERY_KEY, PUBLIC_SETTINGS_QUERY_KEY} from './app-settings-query-keys';
|
||||
|
||||
describe('app-settings-query-keys', () => {
|
||||
it('uses stable cache keys for private and public settings', () => {
|
||||
expect(APP_SETTINGS_QUERY_KEY).toEqual(['appSettings']);
|
||||
expect(PUBLIC_SETTINGS_QUERY_KEY).toEqual(['publicSettings']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,200 @@
|
||||
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 './auth.service';
|
||||
import {APP_SETTINGS_QUERY_KEY, PUBLIC_SETTINGS_QUERY_KEY} from './app-settings-query-keys';
|
||||
import {AppSettingsService, type PublicAppSettings} from './app-settings.service';
|
||||
import type {AppSettings} from '../model/app-settings.model';
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../core/testing/query-testing';
|
||||
|
||||
function buildPublicSettings(overrides: Partial<PublicAppSettings> = {}): PublicAppSettings {
|
||||
return {
|
||||
oidcEnabled: true,
|
||||
remoteAuthEnabled: true,
|
||||
oidcProviderDetails: {
|
||||
providerName: 'OIDC',
|
||||
clientId: 'client-id',
|
||||
issuerUri: 'https://issuer.example',
|
||||
claimMapping: {
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'name',
|
||||
groups: 'groups',
|
||||
},
|
||||
},
|
||||
oidcForceOnlyMode: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildAppSettings(overrides: Partial<AppSettings> = {}): AppSettings {
|
||||
const publicSettings = buildPublicSettings();
|
||||
|
||||
return {
|
||||
autoBookSearch: true,
|
||||
similarBookRecommendation: true,
|
||||
defaultMetadataRefreshOptions: {} as never,
|
||||
libraryMetadataRefreshOptions: [],
|
||||
uploadPattern: '{Title}',
|
||||
opdsServerEnabled: true,
|
||||
komgaApiEnabled: false,
|
||||
komgaGroupUnknown: false,
|
||||
remoteAuthEnabled: publicSettings.remoteAuthEnabled,
|
||||
oidcEnabled: publicSettings.oidcEnabled,
|
||||
oidcProviderDetails: publicSettings.oidcProviderDetails,
|
||||
oidcAutoProvisionDetails: {
|
||||
enableAutoProvisioning: false,
|
||||
allowLocalAccountLinking: false,
|
||||
defaultPermissions: [],
|
||||
defaultLibraryIds: [],
|
||||
},
|
||||
maxFileUploadSizeInMb: 50,
|
||||
metadataProviderSettings: {} as never,
|
||||
metadataMatchWeights: {} as never,
|
||||
metadataPersistenceSettings: {} as never,
|
||||
metadataPublicReviewsSettings: {
|
||||
downloadEnabled: false,
|
||||
autoDownloadEnabled: false,
|
||||
providers: [],
|
||||
},
|
||||
koboSettings: {} as never,
|
||||
coverCroppingSettings: {} as never,
|
||||
metadataDownloadOnBookdrop: false,
|
||||
metadataProviderSpecificFields: {} as never,
|
||||
oidcSessionDurationHours: null,
|
||||
oidcGroupSyncMode: null,
|
||||
oidcForceOnlyMode: publicSettings.oidcForceOnlyMode,
|
||||
diskType: 'LOCAL',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function flushInitialSettingsRequests(
|
||||
httpTestingController: HttpTestingController,
|
||||
overrides: {
|
||||
publicSettings?: Partial<PublicAppSettings>;
|
||||
appSettings?: Partial<AppSettings>;
|
||||
} = {},
|
||||
): {
|
||||
publicSettings: PublicAppSettings;
|
||||
appSettings: AppSettings;
|
||||
} {
|
||||
const publicSettings = buildPublicSettings(overrides.publicSettings);
|
||||
const appSettings = buildAppSettings({
|
||||
oidcEnabled: publicSettings.oidcEnabled,
|
||||
remoteAuthEnabled: publicSettings.remoteAuthEnabled,
|
||||
oidcProviderDetails: publicSettings.oidcProviderDetails,
|
||||
oidcForceOnlyMode: publicSettings.oidcForceOnlyMode,
|
||||
...overrides.appSettings,
|
||||
});
|
||||
|
||||
const publicRequests = httpTestingController.match(req => req.url.endsWith('/api/v1/public-settings'));
|
||||
expect(publicRequests.length).toBeGreaterThan(0);
|
||||
publicRequests.forEach(request => request.flush(publicSettings));
|
||||
|
||||
const appRequests = httpTestingController.match(req => req.url.endsWith('/api/v1/settings') && req.method === 'GET');
|
||||
expect(appRequests.length).toBeGreaterThan(0);
|
||||
appRequests.forEach(request => request.flush(appSettings));
|
||||
|
||||
return {publicSettings, appSettings};
|
||||
}
|
||||
|
||||
describe('AppSettingsService', () => {
|
||||
let service: AppSettingsService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
|
||||
beforeEach(() => {
|
||||
authService = createAuthServiceStub();
|
||||
queryClientHarness = createQueryClientHarness();
|
||||
vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
...queryClientHarness.providers,
|
||||
AppSettingsService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(AppSettingsService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
flushSignalAndQueryEffects();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
queryClientHarness.queryClient.clear();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('exposes a public-settings query option that fetches the expected payload', async () => {
|
||||
const publicSettings = buildPublicSettings({
|
||||
oidcEnabled: false,
|
||||
remoteAuthEnabled: false,
|
||||
oidcForceOnlyMode: true,
|
||||
});
|
||||
flushInitialSettingsRequests(httpTestingController);
|
||||
const queryFn = service.getPublicSettingsQueryOptions().queryFn as (context: never) => Promise<PublicAppSettings>;
|
||||
|
||||
const queryResultPromise = queryFn({} as never);
|
||||
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/public-settings')).flush(publicSettings);
|
||||
|
||||
await expect(queryResultPromise).resolves.toEqual(publicSettings);
|
||||
});
|
||||
|
||||
it('removes authenticated settings queries when the auth token becomes null', () => {
|
||||
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
|
||||
flushInitialSettingsRequests(httpTestingController);
|
||||
|
||||
authService.token.set(null);
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: APP_SETTINGS_QUERY_KEY});
|
||||
});
|
||||
|
||||
it('updates both caches when OIDC is toggled successfully', async () => {
|
||||
const initialSettings = flushInitialSettingsRequests(httpTestingController, {
|
||||
publicSettings: {
|
||||
oidcEnabled: true,
|
||||
remoteAuthEnabled: true,
|
||||
oidcForceOnlyMode: false,
|
||||
},
|
||||
appSettings: {
|
||||
oidcEnabled: true,
|
||||
remoteAuthEnabled: true,
|
||||
oidcForceOnlyMode: false,
|
||||
},
|
||||
});
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
const setQueryDataSpy = vi.spyOn(queryClientHarness.queryClient, 'setQueryData');
|
||||
Object.assign(service, {
|
||||
appSettings: () => initialSettings.appSettings,
|
||||
});
|
||||
queryClientHarness.queryClient.setQueryData(PUBLIC_SETTINGS_QUERY_KEY, initialSettings.publicSettings);
|
||||
|
||||
service.toggleOidcEnabled(false).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/settings') && req.method === 'PUT');
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual([{name: 'OIDC_ENABLED', value: false}]);
|
||||
request.flush(null);
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
|
||||
expect(setQueryDataSpy).toHaveBeenCalledWith(
|
||||
APP_SETTINGS_QUERY_KEY,
|
||||
expect.objectContaining({oidcEnabled: false}),
|
||||
);
|
||||
expect(setQueryDataSpy).toHaveBeenCalledWith(
|
||||
PUBLIC_SETTINGS_QUERY_KEY,
|
||||
expect.objectContaining({oidcEnabled: false}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ReadingSessionApiService} from './reading-session-api.service';
|
||||
import {AudiobookSessionService} from './audiobook-session.service';
|
||||
|
||||
describe('AudiobookSessionService', () => {
|
||||
let createSession: ReturnType<typeof vi.fn>;
|
||||
let sendSessionBeacon: ReturnType<typeof vi.fn>;
|
||||
let service: AudiobookSessionService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-03-26T00:00:00Z'));
|
||||
|
||||
createSession = vi.fn(() => of(void 0));
|
||||
sendSessionBeacon = vi.fn(() => true);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
AudiobookSessionService,
|
||||
{
|
||||
provide: ReadingSessionApiService,
|
||||
useValue: {
|
||||
createSession,
|
||||
sendSessionBeacon,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(AudiobookSessionService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('starts a session and reports current listening time while playback is active', () => {
|
||||
service.startSession(7, 0, 1);
|
||||
|
||||
vi.advanceTimersByTime(12_000);
|
||||
|
||||
expect(service.isSessionActive()).toBe(true);
|
||||
expect(service.isPlaying()).toBe(true);
|
||||
expect(service.getCurrentListeningTime()).toBe(12);
|
||||
});
|
||||
|
||||
it('accumulates listening time on pause using the playback rate', () => {
|
||||
service.startSession(7, 30_000, 1.5);
|
||||
|
||||
vi.advanceTimersByTime(10_000);
|
||||
service.pauseSession(45_000);
|
||||
|
||||
expect(service.isPlaying()).toBe(false);
|
||||
expect(service.getCurrentListeningTime()).toBe(15);
|
||||
});
|
||||
|
||||
it('discards short sessions without sending them to the backend', () => {
|
||||
service.startSession(8, 0, 1);
|
||||
|
||||
vi.advanceTimersByTime(20_000);
|
||||
service.endSession(20_000);
|
||||
|
||||
expect(createSession).not.toHaveBeenCalled();
|
||||
expect(service.isSessionActive()).toBe(false);
|
||||
});
|
||||
|
||||
it('sends completed sessions that meet the minimum duration threshold', () => {
|
||||
service.startSession(11, 0, 1, 99, 2);
|
||||
|
||||
vi.advanceTimersByTime(31_000);
|
||||
service.endSession(90_000);
|
||||
|
||||
expect(createSession).toHaveBeenCalledOnce();
|
||||
expect(createSession).toHaveBeenCalledWith(expect.objectContaining({
|
||||
bookId: 11,
|
||||
bookType: 'AUDIOBOOK',
|
||||
durationSeconds: 31,
|
||||
durationFormatted: '31s',
|
||||
startLocation: '0:00',
|
||||
endLocation: '1:30',
|
||||
}));
|
||||
expect(service.isSessionActive()).toBe(false);
|
||||
});
|
||||
|
||||
it('sends a beacon on unload for long enough active sessions', () => {
|
||||
service.startSession(12, 65_000, 1);
|
||||
|
||||
vi.advanceTimersByTime(35_000);
|
||||
window.dispatchEvent(new Event('beforeunload'));
|
||||
|
||||
expect(sendSessionBeacon).toHaveBeenCalledOnce();
|
||||
expect(sendSessionBeacon).toHaveBeenCalledWith(expect.objectContaining({
|
||||
bookId: 12,
|
||||
bookType: 'AUDIOBOOK',
|
||||
durationSeconds: 35,
|
||||
startLocation: '1:05',
|
||||
endLocation: '1:05',
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
|
||||
import {RxStompService} from '../websocket/rx-stomp.service';
|
||||
import {AuthService, websocketInitializer} from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
const router = {
|
||||
navigate: vi.fn(() => Promise.resolve(true)),
|
||||
};
|
||||
const rxStompService = {
|
||||
activate: vi.fn(),
|
||||
deactivate: vi.fn(),
|
||||
updateConfig: vi.fn(),
|
||||
};
|
||||
const postLoginInitializer = {
|
||||
initialize: vi.fn(() => of(undefined)),
|
||||
};
|
||||
|
||||
let service: AuthService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
localStorage.clear();
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
{provide: Router, useValue: router},
|
||||
{provide: RxStompService, useValue: rxStompService},
|
||||
{provide: PostLoginInitializerService, useValue: postLoginInitializer},
|
||||
AuthService,
|
||||
]
|
||||
});
|
||||
|
||||
router.navigate.mockClear();
|
||||
rxStompService.activate.mockClear();
|
||||
rxStompService.deactivate.mockClear();
|
||||
rxStompService.updateConfig.mockClear();
|
||||
postLoginInitializer.initialize.mockClear();
|
||||
|
||||
service = TestBed.inject(AuthService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
localStorage.clear();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('logs in with internal credentials and initializes the authenticated session', () => {
|
||||
service.internalLogin({username: 'admin', password: 'secret'}).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/login`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({username: 'admin', password: 'secret'});
|
||||
request.flush({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'});
|
||||
|
||||
expect(service.getInternalAccessToken()).toBe('access');
|
||||
expect(service.getInternalRefreshToken()).toBe('refresh');
|
||||
expect(service.token()).toBe('access');
|
||||
expect(rxStompService.updateConfig).toHaveBeenCalledOnce();
|
||||
expect(rxStompService.activate).toHaveBeenCalledOnce();
|
||||
expect(postLoginInitializer.initialize).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('refreshes the token and persists the new values', () => {
|
||||
localStorage.setItem('refreshToken_Internal', 'refresh-token');
|
||||
|
||||
service.internalRefreshToken().subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
|
||||
expect(request.request.body).toEqual({refreshToken: 'refresh-token'});
|
||||
request.flush({accessToken: 'new-access', refreshToken: 'new-refresh'});
|
||||
|
||||
expect(service.getInternalAccessToken()).toBe('new-access');
|
||||
expect(service.getInternalRefreshToken()).toBe('new-refresh');
|
||||
});
|
||||
|
||||
it('handles remote login the same way as an internal login', () => {
|
||||
service.remoteLogin().subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/remote`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: 'false'});
|
||||
|
||||
expect(service.getInternalAccessToken()).toBe('remote-access');
|
||||
expect(rxStompService.activate).toHaveBeenCalledOnce();
|
||||
expect(postLoginInitializer.initialize).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('logs out locally when the backend does not return a remote logout url', async () => {
|
||||
localStorage.setItem('accessToken_Internal', 'access');
|
||||
localStorage.setItem('refreshToken_Internal', 'refresh');
|
||||
|
||||
service.logout();
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`);
|
||||
request.flush({logoutUrl: null});
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
expect(service.token()).toBeNull();
|
||||
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('logs out locally when the backend logout request fails', async () => {
|
||||
localStorage.setItem('accessToken_Internal', 'access');
|
||||
localStorage.setItem('refreshToken_Internal', 'refresh');
|
||||
|
||||
service.logout();
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`);
|
||||
request.flush('boom', {status: 500, statusText: 'Server Error'});
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
expect(service.token()).toBeNull();
|
||||
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('clears the session and navigates with a reason during force logout', () => {
|
||||
localStorage.setItem('accessToken_Internal', 'access');
|
||||
localStorage.setItem('refreshToken_Internal', 'refresh');
|
||||
|
||||
service.forceLogout('session_revoked');
|
||||
|
||||
expect(service.token()).toBeNull();
|
||||
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login'], {
|
||||
queryParams: {reason: 'session_revoked'},
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the session when the login page is opened', () => {
|
||||
localStorage.setItem('accessToken_Internal', 'access');
|
||||
localStorage.setItem('refreshToken_Internal', 'refresh');
|
||||
|
||||
service.clearSessionOnLoginPage();
|
||||
|
||||
expect(service.token()).toBeNull();
|
||||
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('skips websocket initialization when there is no access token', () => {
|
||||
service.initializeWebSocketConnection();
|
||||
|
||||
expect(rxStompService.updateConfig).not.toHaveBeenCalled();
|
||||
expect(postLoginInitializer.initialize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('initializes the websocket connection and post-login hooks only once', () => {
|
||||
service.saveInternalTokens('access', 'refresh');
|
||||
|
||||
service.initializeWebSocketConnection();
|
||||
service.initializeWebSocketConnection();
|
||||
|
||||
expect(rxStompService.updateConfig).toHaveBeenCalledTimes(2);
|
||||
expect(rxStompService.activate).toHaveBeenCalledTimes(2);
|
||||
expect(postLoginInitializer.initialize).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('provides a websocket initializer wrapper', () => {
|
||||
const initializeSpy = vi.spyOn(service, 'initializeWebSocketConnection').mockImplementation(() => undefined);
|
||||
|
||||
websocketInitializer(service)();
|
||||
|
||||
expect(initializeSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('continues after post-login initialization failures', () => {
|
||||
postLoginInitializer.initialize.mockReturnValue(
|
||||
throwError(() => new Error('initializer failed'))
|
||||
);
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
service.saveInternalTokens('access', 'refresh');
|
||||
service.initializeWebSocketConnection();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledOnce();
|
||||
expect(rxStompService.activate).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
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 {BookMarkService} from './book-mark.service';
|
||||
|
||||
describe('BookMarkService', () => {
|
||||
const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/bookmarks`;
|
||||
|
||||
let service: BookMarkService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookMarkService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookMarkService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads bookmarks for a book', () => {
|
||||
service.getBookmarksForBook(9).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/book/9`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('creates and updates bookmarks', () => {
|
||||
const createRequest = {
|
||||
bookId: 9,
|
||||
cfi: 'epubcfi(/6/4)',
|
||||
title: 'Great quote',
|
||||
};
|
||||
|
||||
service.createBookmark(createRequest).subscribe();
|
||||
const createHttpRequest = httpTestingController.expectOne(baseUrl);
|
||||
expect(createHttpRequest.request.method).toBe('POST');
|
||||
expect(createHttpRequest.request.body).toEqual(createRequest);
|
||||
createHttpRequest.flush({...createRequest, id: 12, createdAt: '2024-01-01'});
|
||||
|
||||
const updateRequest = {
|
||||
title: 'Updated quote',
|
||||
notes: 'Look here again',
|
||||
};
|
||||
|
||||
service.updateBookmark(12, updateRequest).subscribe();
|
||||
const updateHttpRequest = httpTestingController.expectOne(`${baseUrl}/12`);
|
||||
expect(updateHttpRequest.request.method).toBe('PUT');
|
||||
expect(updateHttpRequest.request.body).toEqual(updateRequest);
|
||||
updateHttpRequest.flush({...createRequest, ...updateRequest, id: 12, createdAt: '2024-01-01'});
|
||||
});
|
||||
|
||||
it('deletes bookmarks by id', () => {
|
||||
service.deleteBookmark(12).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/12`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookMetadataHostService} from './book-metadata-host.service';
|
||||
|
||||
describe('BookMetadataHostService', () => {
|
||||
it('emits book switch requests through the shared subject', () => {
|
||||
const service = new BookMetadataHostService();
|
||||
const received: number[] = [];
|
||||
|
||||
const subscription = service.bookSwitches$.subscribe(bookId => received.push(bookId));
|
||||
|
||||
service.requestBookSwitch(42);
|
||||
service.switchBook(84);
|
||||
|
||||
expect(received).toEqual([42, 84]);
|
||||
|
||||
subscription.unsubscribe();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
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 {BookNoteV2Service} from './book-note-v2.service';
|
||||
|
||||
describe('BookNoteV2Service', () => {
|
||||
const baseUrl = `${API_CONFIG.BASE_URL}/api/v2/book-notes`;
|
||||
|
||||
let service: BookNoteV2Service;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookNoteV2Service,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookNoteV2Service);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads v2 notes for a book', () => {
|
||||
service.getNotesForBook(22).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/book/22`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('creates and updates v2 notes', () => {
|
||||
const createRequest = {
|
||||
bookId: 22,
|
||||
cfi: 'epubcfi(/6/2[chapter1])',
|
||||
noteContent: 'Remember this passage',
|
||||
};
|
||||
|
||||
service.createNote(createRequest).subscribe();
|
||||
const createHttpRequest = httpTestingController.expectOne(baseUrl);
|
||||
expect(createHttpRequest.request.method).toBe('POST');
|
||||
expect(createHttpRequest.request.body).toEqual(createRequest);
|
||||
createHttpRequest.flush({...createRequest, id: 4, createdAt: '2024-01-01'});
|
||||
|
||||
const updateRequest = {
|
||||
noteContent: 'Updated note',
|
||||
color: '#ff0',
|
||||
};
|
||||
|
||||
service.updateNote(4, updateRequest).subscribe();
|
||||
const updateHttpRequest = httpTestingController.expectOne(`${baseUrl}/4`);
|
||||
expect(updateHttpRequest.request.method).toBe('PUT');
|
||||
expect(updateHttpRequest.request.body).toEqual(updateRequest);
|
||||
updateHttpRequest.flush({...createRequest, ...updateRequest, id: 4, createdAt: '2024-01-01'});
|
||||
});
|
||||
|
||||
it('deletes v2 notes by id', () => {
|
||||
service.deleteNote(4).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/4`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
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 {BookNoteService} from './book-note.service';
|
||||
|
||||
describe('BookNoteService', () => {
|
||||
const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/book-notes`;
|
||||
|
||||
let service: BookNoteService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookNoteService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookNoteService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('loads notes for a book', () => {
|
||||
service.getNotesForBook(15).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/book/15`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('creates or updates a note via POST', () => {
|
||||
const requestBody = {
|
||||
bookId: 15,
|
||||
title: 'Chapter 1',
|
||||
content: 'Important note',
|
||||
};
|
||||
|
||||
service.createOrUpdateNote(requestBody).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(baseUrl);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(requestBody);
|
||||
request.flush({...requestBody, id: 3, userId: 9, createdAt: '2024-01-01', updatedAt: '2024-01-02'});
|
||||
});
|
||||
|
||||
it('deletes a note by id', () => {
|
||||
service.deleteNote(3).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(`${baseUrl}/3`);
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs a stable Angular Query harness plus a controllable
|
||||
// FontFace/document.fonts environment so query cache mutation and browser font registration can be
|
||||
// asserted without changing runtime code.
|
||||
describe.skip('CustomFontService', () => {
|
||||
it('needs a query-client and font-face seam to validate cache updates after upload and deletion', () => {
|
||||
// Intentionally skipped until the service can be exercised without mutating runtime code.
|
||||
});
|
||||
|
||||
it('needs a controllable browser font registry seam to validate loadFontFace and removeFontFace behavior', () => {
|
||||
// Intentionally skipped until document.fonts and FontFace can be driven deterministically.
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import {HttpHeaders, provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {FileDownloadService} from './file-download.service';
|
||||
|
||||
describe('FileDownloadService', () => {
|
||||
let service: FileDownloadService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
FileDownloadService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(FileDownloadService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('downloads a blob using the filename from the response header', () => {
|
||||
const click = vi.fn();
|
||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
||||
const createElementSpy = vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
||||
const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:download');
|
||||
const revokeObjectUrlSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
|
||||
service.downloadFile('/files/1', 'fallback.epub');
|
||||
|
||||
const request = httpTestingController.expectOne('/files/1');
|
||||
expect(request.request.method).toBe('GET');
|
||||
expect(request.request.responseType).toBe('blob');
|
||||
request.flush(new Blob(['content']), {
|
||||
headers: new HttpHeaders({
|
||||
'Content-Disposition': "attachment; filename*=UTF-8''server%20name.epub",
|
||||
}),
|
||||
});
|
||||
|
||||
expect(createElementSpy).toHaveBeenCalledWith('a');
|
||||
expect(createObjectUrlSpy).toHaveBeenCalled();
|
||||
expect(anchor.download).toBe('server name.epub');
|
||||
expect(click).toHaveBeenCalledOnce();
|
||||
expect(revokeObjectUrlSpy).toHaveBeenCalledWith('blob:download');
|
||||
});
|
||||
|
||||
it('falls back to the provided filename when the response has no content-disposition header', () => {
|
||||
const click = vi.fn();
|
||||
const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement;
|
||||
const createElementSpy = vi.spyOn(document, 'createElement').mockReturnValue(anchor);
|
||||
const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:download');
|
||||
const revokeObjectUrlSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
|
||||
service.downloadFile('/files/2', 'fallback.epub');
|
||||
|
||||
const request = httpTestingController.expectOne('/files/2');
|
||||
request.flush(new Blob(['content']));
|
||||
|
||||
expect(createElementSpy).toHaveBeenCalledWith('a');
|
||||
expect(createObjectUrlSpy).toHaveBeenCalled();
|
||||
expect(anchor.download).toBe('fallback.epub');
|
||||
expect(click).toHaveBeenCalledOnce();
|
||||
expect(revokeObjectUrlSpy).toHaveBeenCalledWith('blob:download');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
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 {FileMoveRequest, FileOperationsService} from './file-operations.service';
|
||||
|
||||
describe('FileOperationsService', () => {
|
||||
let service: FileOperationsService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
FileOperationsService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(FileOperationsService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('posts move requests to the file operations endpoint', () => {
|
||||
const requestBody: FileMoveRequest = {
|
||||
bookIds: [4, 9],
|
||||
moves: [
|
||||
{bookId: 4, targetLibraryId: 2, targetLibraryPathId: 10},
|
||||
{bookId: 9, targetLibraryId: null, targetLibraryPathId: null},
|
||||
],
|
||||
};
|
||||
|
||||
let completed = false;
|
||||
service.moveFiles(requestBody).subscribe(() => {
|
||||
completed = true;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/files/move'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(requestBody);
|
||||
request.flush(null);
|
||||
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {firstValueFrom, of} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {DialogLauncherService} from '../services/dialog-launcher.service';
|
||||
import {IconPickerService} from './icon-picker.service';
|
||||
|
||||
describe('IconPickerService', () => {
|
||||
const dialogLauncherService = {
|
||||
openIconPickerDialog: vi.fn(),
|
||||
};
|
||||
|
||||
let service: IconPickerService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
dialogLauncherService.openIconPickerDialog.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
IconPickerService,
|
||||
{provide: DialogLauncherService, useValue: dialogLauncherService},
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(IconPickerService);
|
||||
});
|
||||
|
||||
it('returns the icon selected by the dialog', async () => {
|
||||
dialogLauncherService.openIconPickerDialog.mockReturnValue({
|
||||
onClose: of({type: 'PRIME_NG', value: 'pi pi-book'}),
|
||||
});
|
||||
|
||||
await expect(firstValueFrom(service.open())).resolves.toEqual({
|
||||
type: 'PRIME_NG',
|
||||
value: 'pi pi-book',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {LocalStorageService} from './local-storage.service';
|
||||
|
||||
describe('LocalStorageService', () => {
|
||||
let service: LocalStorageService;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [LocalStorageService],
|
||||
});
|
||||
|
||||
service = TestBed.inject(LocalStorageService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('reads parsed values from local storage', () => {
|
||||
localStorage.setItem('settings', JSON.stringify({theme: 'aura'}));
|
||||
|
||||
expect(service.get<{theme: string}>('settings')).toEqual({theme: 'aura'});
|
||||
});
|
||||
|
||||
it('returns null when the key is missing or invalid', () => {
|
||||
localStorage.setItem('broken', '{not-json');
|
||||
|
||||
expect(service.get('missing')).toBeNull();
|
||||
expect(service.get('broken')).toBeNull();
|
||||
});
|
||||
|
||||
it('serializes values when writing to local storage', () => {
|
||||
service.set('settings', {theme: 'aura'});
|
||||
|
||||
expect(localStorage.getItem('settings')).toBe(JSON.stringify({theme: 'aura'}));
|
||||
});
|
||||
|
||||
it('swallows storage write errors', () => {
|
||||
const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
|
||||
throw new Error('quota exceeded');
|
||||
});
|
||||
|
||||
expect(() => service.set('settings', {theme: 'aura'})).not.toThrow();
|
||||
expect(setItemSpy).toHaveBeenCalled();
|
||||
setItemSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('removes values from local storage', () => {
|
||||
localStorage.setItem('settings', JSON.stringify({theme: 'aura'}));
|
||||
|
||||
service.remove('settings');
|
||||
|
||||
expect(localStorage.getItem('settings')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
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 {MetadataMatchWeightsService} from './metadata-match-weights.service';
|
||||
|
||||
describe('MetadataMatchWeightsService', () => {
|
||||
let service: MetadataMatchWeightsService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
MetadataMatchWeightsService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(MetadataMatchWeightsService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('posts to the metadata score recalculation endpoint', () => {
|
||||
service.recalculateAll().subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`
|
||||
);
|
||||
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({});
|
||||
|
||||
request.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../model/metadata-batch-progress.model';
|
||||
import {MetadataTaskService} from '../../features/book/service/metadata-task';
|
||||
import {UserService} from '../../features/settings/user-management/user.service';
|
||||
import {MetadataProgressService} from './metadata-progress.service';
|
||||
|
||||
describe('MetadataProgressService', () => {
|
||||
const adminUser = {
|
||||
permissions: {
|
||||
admin: true,
|
||||
canEditMetadata: false,
|
||||
},
|
||||
};
|
||||
|
||||
let getActiveTasks: ReturnType<typeof vi.fn>;
|
||||
let currentUser: ReturnType<typeof signal<typeof adminUser | null>>;
|
||||
let service: MetadataProgressService;
|
||||
|
||||
const taskA: MetadataBatchProgressNotification = {
|
||||
taskId: 'task-a',
|
||||
completed: 1,
|
||||
total: 4,
|
||||
message: 'running',
|
||||
status: MetadataBatchStatus.IN_PROGRESS,
|
||||
review: false,
|
||||
};
|
||||
|
||||
const taskB: MetadataBatchProgressNotification = {
|
||||
taskId: 'task-b',
|
||||
completed: 4,
|
||||
total: 4,
|
||||
message: 'done',
|
||||
status: MetadataBatchStatus.COMPLETED,
|
||||
review: true,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
getActiveTasks = vi.fn(() => of([]));
|
||||
currentUser = signal<typeof adminUser | null>(adminUser);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
MetadataProgressService,
|
||||
{
|
||||
provide: MetadataTaskService,
|
||||
useValue: {getActiveTasks},
|
||||
},
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {currentUser},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('initializes active tasks once for users with metadata permissions', () => {
|
||||
getActiveTasks.mockReturnValue(of([taskA]));
|
||||
|
||||
service = TestBed.inject(MetadataProgressService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(getActiveTasks).toHaveBeenCalledOnce();
|
||||
expect(service.getActiveTasks()).toEqual({[taskA.taskId]: taskA});
|
||||
});
|
||||
|
||||
it('does not initialize task loading when the current user lacks metadata permissions', () => {
|
||||
currentUser.set({
|
||||
permissions: {
|
||||
admin: false,
|
||||
canEditMetadata: false,
|
||||
},
|
||||
});
|
||||
|
||||
service = TestBed.inject(MetadataProgressService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(getActiveTasks).not.toHaveBeenCalled();
|
||||
expect(service.getActiveTasks()).toEqual({});
|
||||
});
|
||||
|
||||
it('warns and keeps running when active-task initialization fails', () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
getActiveTasks.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
service = TestBed.inject(MetadataProgressService);
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(getActiveTasks).toHaveBeenCalledOnce();
|
||||
expect(warnSpy).toHaveBeenCalled();
|
||||
expect(service.getActiveTasks()).toEqual({});
|
||||
});
|
||||
|
||||
it('publishes incoming progress updates and keeps the latest task state', () => {
|
||||
service = TestBed.inject(MetadataProgressService);
|
||||
|
||||
const emissions: MetadataBatchProgressNotification[] = [];
|
||||
service.progressUpdates$.subscribe(value => emissions.push(value));
|
||||
|
||||
service.handleIncomingProgress(taskA);
|
||||
service.handleIncomingProgress({...taskA, completed: 3});
|
||||
|
||||
expect(emissions).toHaveLength(2);
|
||||
expect(service.getActiveTasks()).toEqual({
|
||||
[taskA.taskId]: {...taskA, completed: 3},
|
||||
});
|
||||
});
|
||||
|
||||
it('clears tasks from the active task map', () => {
|
||||
service = TestBed.inject(MetadataProgressService);
|
||||
service.handleIncomingProgress(taskA);
|
||||
service.handleIncomingProgress(taskB);
|
||||
|
||||
service.clearTask(taskA.taskId);
|
||||
|
||||
expect(service.getActiveTasks()).toEqual({[taskB.taskId]: taskB});
|
||||
});
|
||||
|
||||
it('unsubscribes cleanly on destroy', () => {
|
||||
service = TestBed.inject(MetadataProgressService);
|
||||
service.handleIncomingProgress(taskA);
|
||||
|
||||
service.ngOnDestroy();
|
||||
|
||||
expect(() => service.getActiveTasks()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
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 {OidcGroupMappingService} from './oidc-group-mapping.service';
|
||||
|
||||
describe('OidcGroupMappingService', () => {
|
||||
const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/admin/oidc-group-mappings`;
|
||||
|
||||
let service: OidcGroupMappingService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
OidcGroupMappingService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(OidcGroupMappingService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('fetches all mappings', () => {
|
||||
service.getAll().subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(baseUrl);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([]);
|
||||
});
|
||||
|
||||
it('creates a mapping', () => {
|
||||
const mapping = {
|
||||
oidcGroupClaim: 'admins',
|
||||
isAdmin: true,
|
||||
permissions: ['BOOK_EDIT'],
|
||||
libraryIds: [1],
|
||||
description: 'Admin group',
|
||||
};
|
||||
|
||||
service.create(mapping).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(baseUrl);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(mapping);
|
||||
request.flush(mapping);
|
||||
});
|
||||
|
||||
it('updates and deletes mappings by id', () => {
|
||||
const mapping = {
|
||||
oidcGroupClaim: 'members',
|
||||
isAdmin: false,
|
||||
permissions: ['BOOK_VIEW'],
|
||||
libraryIds: [2],
|
||||
description: 'Member group',
|
||||
};
|
||||
|
||||
service.update(7, mapping).subscribe();
|
||||
const updateRequest = httpTestingController.expectOne(`${baseUrl}/7`);
|
||||
expect(updateRequest.request.method).toBe('PUT');
|
||||
expect(updateRequest.request.body).toEqual(mapping);
|
||||
updateRequest.flush(mapping);
|
||||
|
||||
service.delete(7).subscribe();
|
||||
const deleteRequest = httpTestingController.expectOne(`${baseUrl}/7`);
|
||||
expect(deleteRequest.request.method).toBe('DELETE');
|
||||
deleteRequest.flush(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Title} from '@angular/platform-browser';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {Book} from '../../features/book/model/book.model';
|
||||
import {PageTitleService} from './page-title.service';
|
||||
|
||||
describe('PageTitleService', () => {
|
||||
const titleService = {
|
||||
setTitle: vi.fn(),
|
||||
};
|
||||
|
||||
let service: PageTitleService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
titleService.setTitle.mockClear();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
PageTitleService,
|
||||
{provide: Title, useValue: titleService},
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(PageTitleService);
|
||||
});
|
||||
|
||||
it('appends the application name to a page title', () => {
|
||||
service.setPageTitle('Dashboard');
|
||||
|
||||
expect(titleService.setTitle).toHaveBeenCalledWith('Dashboard - Grimmory');
|
||||
});
|
||||
|
||||
it('builds a book page title from the available book metadata', () => {
|
||||
const book = {
|
||||
libraryName: 'Central',
|
||||
fileName: 'fallback.epub',
|
||||
metadata: {
|
||||
title: 'Dune',
|
||||
seriesName: 'Chronicles',
|
||||
authors: ['Frank Herbert', 'Brian Herbert'],
|
||||
},
|
||||
primaryFile: {
|
||||
bookType: 'EPUB',
|
||||
},
|
||||
} as Book;
|
||||
|
||||
service.setBookPageTitle(book);
|
||||
|
||||
expect(titleService.setTitle).toHaveBeenCalledWith(
|
||||
'Central/Dune (Chronicles series) - by Frank Herbert and Brian Herbert (EPUB) - Grimmory'
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to the filename when the metadata title is missing', () => {
|
||||
const book = {
|
||||
libraryName: 'Central',
|
||||
fileName: 'fallback.epub',
|
||||
metadata: {},
|
||||
primaryFile: {
|
||||
bookType: 'PDF',
|
||||
},
|
||||
} as Book;
|
||||
|
||||
service.setBookPageTitle(book);
|
||||
|
||||
expect(titleService.setTitle).toHaveBeenCalledWith('Central/fallback.epub (PDF) - Grimmory');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
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 {PdfAnnotationService} from './pdf-annotation.service';
|
||||
|
||||
describe('PdfAnnotationService', () => {
|
||||
let service: PdfAnnotationService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
PdfAnnotationService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(PdfAnnotationService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('fetches annotations for a book', () => {
|
||||
let result: {data: string} | undefined;
|
||||
service.getAnnotations(42).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/pdf-annotations/book/42'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({data: '{"annotations":[]}'});
|
||||
|
||||
expect(result).toEqual({data: '{"annotations":[]}'});
|
||||
});
|
||||
|
||||
it('saves annotations for a book', () => {
|
||||
let completed = false;
|
||||
service.saveAnnotations(7, '{"page":1}').subscribe(() => {
|
||||
completed = true;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/pdf-annotations/book/7'));
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual({data: '{"page":1}'});
|
||||
request.flush(null);
|
||||
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
|
||||
it('deletes annotations for a book', () => {
|
||||
let completed = false;
|
||||
service.deleteAnnotations(9).subscribe(() => {
|
||||
completed = true;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/pdf-annotations/book/9'));
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {ReadingSessionApiService} from './reading-session-api.service';
|
||||
|
||||
describe('ReadingSessionApiService', () => {
|
||||
const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/reading-sessions`;
|
||||
const originalSendBeaconDescriptor = Object.getOwnPropertyDescriptor(navigator, 'sendBeacon');
|
||||
|
||||
let service: ReadingSessionApiService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
ReadingSessionApiService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(ReadingSessionApiService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
if (originalSendBeaconDescriptor) {
|
||||
Object.defineProperty(navigator, 'sendBeacon', originalSendBeaconDescriptor);
|
||||
} else {
|
||||
Object.defineProperty(navigator, 'sendBeacon', {
|
||||
configurable: true,
|
||||
value: undefined,
|
||||
});
|
||||
}
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('creates a reading session', () => {
|
||||
const session = {
|
||||
bookId: 3,
|
||||
bookType: 'EPUB' as const,
|
||||
startTime: '2024-01-01T00:00:00Z',
|
||||
endTime: '2024-01-01T00:10:00Z',
|
||||
durationSeconds: 600,
|
||||
durationFormatted: '10m 0s',
|
||||
};
|
||||
|
||||
service.createSession(session).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(baseUrl);
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(session);
|
||||
request.flush(null);
|
||||
});
|
||||
|
||||
it('loads paged sessions for a book', () => {
|
||||
service.getSessionsByBookId(3, 2, 20).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(
|
||||
requestMatch => requestMatch.url === `${baseUrl}/book/3`
|
||||
&& requestMatch.params.get('page') === '2'
|
||||
&& requestMatch.params.get('size') === '20'
|
||||
);
|
||||
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({
|
||||
content: [],
|
||||
page: {
|
||||
totalElements: 0,
|
||||
totalPages: 0,
|
||||
number: 2,
|
||||
size: 20,
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('uses sendBeacon when the browser supports it and returns false when it throws', () => {
|
||||
const session = {
|
||||
bookId: 3,
|
||||
bookType: 'EPUB' as const,
|
||||
startTime: '2024-01-01T00:00:00Z',
|
||||
endTime: '2024-01-01T00:10:00Z',
|
||||
durationSeconds: 600,
|
||||
durationFormatted: '10m 0s',
|
||||
};
|
||||
const sendBeaconSpy = vi.fn();
|
||||
Object.defineProperty(navigator, 'sendBeacon', {
|
||||
configurable: true,
|
||||
value: sendBeaconSpy,
|
||||
});
|
||||
|
||||
sendBeaconSpy.mockReturnValue(true);
|
||||
expect(service.sendSessionBeacon(session)).toBe(true);
|
||||
|
||||
sendBeaconSpy.mockImplementation(() => {
|
||||
throw new Error('unsupported');
|
||||
});
|
||||
expect(service.sendSessionBeacon(session)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ReadingSessionApiService} from './reading-session-api.service';
|
||||
import {ReadingSessionService} from './reading-session.service';
|
||||
|
||||
describe('ReadingSessionService', () => {
|
||||
let createSession: ReturnType<typeof vi.fn>;
|
||||
let sendSessionBeacon: ReturnType<typeof vi.fn>;
|
||||
let service: ReadingSessionService;
|
||||
let hidden = false;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-03-26T00:00:00Z'));
|
||||
hidden = false;
|
||||
|
||||
Object.defineProperty(document, 'hidden', {
|
||||
configurable: true,
|
||||
get: () => hidden,
|
||||
});
|
||||
|
||||
createSession = vi.fn(() => of(void 0));
|
||||
sendSessionBeacon = vi.fn(() => true);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ReadingSessionService,
|
||||
{
|
||||
provide: ReadingSessionApiService,
|
||||
useValue: {
|
||||
createSession,
|
||||
sendSessionBeacon,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(ReadingSessionService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('starts and tracks an active reading session', () => {
|
||||
service.startSession(4, 'EPUB', 'chapter-1', 12.345);
|
||||
|
||||
expect(service.isSessionActive()).toBe(true);
|
||||
});
|
||||
|
||||
it('discards sessions that are shorter than the minimum duration', () => {
|
||||
service.startSession(5, 'EPUB', 'start', 10);
|
||||
service.updateProgress('middle', 25);
|
||||
|
||||
vi.advanceTimersByTime(20_000);
|
||||
service.endSession('end', 35);
|
||||
|
||||
expect(createSession).not.toHaveBeenCalled();
|
||||
expect(service.isSessionActive()).toBe(false);
|
||||
});
|
||||
|
||||
it('sends completed sessions to the backend with rounded progress values', () => {
|
||||
service.startSession(6, 'PDF', 'page-1', 12.3456);
|
||||
service.updateProgress('page-9', 45.6789);
|
||||
|
||||
vi.advanceTimersByTime(31_000);
|
||||
service.endSession();
|
||||
|
||||
expect(createSession).toHaveBeenCalledOnce();
|
||||
expect(createSession).toHaveBeenCalledWith(expect.objectContaining({
|
||||
bookId: 6,
|
||||
bookType: 'PDF',
|
||||
durationSeconds: 31,
|
||||
durationFormatted: '31s',
|
||||
startLocation: 'page-1',
|
||||
endLocation: 'page-9',
|
||||
startProgress: 12.35,
|
||||
endProgress: 45.68,
|
||||
progressDelta: 33.33,
|
||||
}));
|
||||
expect(service.isSessionActive()).toBe(false);
|
||||
});
|
||||
|
||||
it('sends a beacon on unload for long enough active sessions', () => {
|
||||
service.startSession(7, 'EPUB', 'cfi-1', 5);
|
||||
service.updateProgress('cfi-2', 9.5);
|
||||
|
||||
vi.advanceTimersByTime(35_000);
|
||||
window.dispatchEvent(new Event('beforeunload'));
|
||||
|
||||
expect(sendSessionBeacon).toHaveBeenCalledOnce();
|
||||
expect(sendSessionBeacon).toHaveBeenCalledWith(expect.objectContaining({
|
||||
bookId: 7,
|
||||
bookType: 'EPUB',
|
||||
durationSeconds: 35,
|
||||
startLocation: 'cfi-1',
|
||||
endLocation: 'cfi-2',
|
||||
startProgress: 5,
|
||||
endProgress: 9.5,
|
||||
progressDelta: undefined,
|
||||
}));
|
||||
});
|
||||
|
||||
it('ends sessions that stay hidden longer than the idle timeout once the tab becomes visible again', () => {
|
||||
service.startSession(8, 'EPUB', 'cfi-1', 1);
|
||||
service.updateProgress('cfi-2', 5);
|
||||
|
||||
hidden = true;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
|
||||
vi.advanceTimersByTime(5 * 60 * 1000 + 5_000);
|
||||
|
||||
hidden = false;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
|
||||
expect(createSession).toHaveBeenCalledOnce();
|
||||
expect(service.isSessionActive()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {firstValueFrom, of, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {AppSettingsService} from './app-settings.service';
|
||||
import {SettingsHelperService} from './settings-helper.service';
|
||||
|
||||
describe('SettingsHelperService', () => {
|
||||
const appSettingsService = {
|
||||
saveSettings: vi.fn(),
|
||||
};
|
||||
const messageService = {
|
||||
add: vi.fn(),
|
||||
};
|
||||
const translocoService = {
|
||||
translate: vi.fn((key: string) => `translated:${key}`),
|
||||
};
|
||||
|
||||
let service: SettingsHelperService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
appSettingsService.saveSettings.mockReset();
|
||||
messageService.add.mockClear();
|
||||
translocoService.translate.mockClear();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SettingsHelperService,
|
||||
{provide: AppSettingsService, useValue: appSettingsService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService},
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(SettingsHelperService);
|
||||
});
|
||||
|
||||
it('saves a setting and shows a success message', async () => {
|
||||
appSettingsService.saveSettings.mockReturnValue(of(undefined));
|
||||
|
||||
await firstValueFrom(service.saveSetting('theme', 'dark'));
|
||||
|
||||
expect(appSettingsService.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'dark'}]);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:shared.settingsHelper.settingsSavedSummary',
|
||||
detail: 'translated:shared.settingsHelper.settingsSavedDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows an error message when saving fails', async () => {
|
||||
const error = new Error('save failed');
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
appSettingsService.saveSettings.mockReturnValue(throwError(() => error));
|
||||
|
||||
await expect(firstValueFrom(service.saveSetting('theme', 'dark'))).rejects.toThrow('save failed');
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledWith('Failed to save setting:', error);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:common.error',
|
||||
detail: 'translated:shared.settingsHelper.saveErrorDetail',
|
||||
});
|
||||
});
|
||||
|
||||
it('forwards ad-hoc messages through the message service', () => {
|
||||
service.showMessage('success', 'Saved', 'Everything worked');
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'Everything worked',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {AuthService} from './auth.service';
|
||||
import {StartupService} from './startup.service';
|
||||
import {UserService} from '../../features/settings/user-management/user.service';
|
||||
|
||||
describe('StartupService', () => {
|
||||
it('loads the current user when a token is present', async () => {
|
||||
const fetchQuery = vi.fn().mockResolvedValue({username: 'admin'});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
StartupService,
|
||||
{provide: AuthService, useValue: {token: signal('token')}},
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {
|
||||
getUserQueryOptions: () => queryOptions({
|
||||
queryKey: ['user'],
|
||||
queryFn: async () => ({username: 'admin'}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
{provide: QueryClient, useValue: {fetchQuery}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(StartupService);
|
||||
|
||||
await expect(service.load()).resolves.toBeUndefined();
|
||||
expect(fetchQuery).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('resolves immediately when there is no token', async () => {
|
||||
const fetchQuery = vi.fn();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
StartupService,
|
||||
{provide: AuthService, useValue: {token: signal(null)}},
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {
|
||||
getUserQueryOptions: () => queryOptions({
|
||||
queryKey: ['user'],
|
||||
queryFn: async () => ({username: 'admin'}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
{provide: QueryClient, useValue: {fetchQuery}},
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(StartupService);
|
||||
|
||||
await expect(service.load()).resolves.toBeUndefined();
|
||||
expect(fetchQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {Book, BookType} from '../../features/book/model/book.model';
|
||||
import {BookService} from '../../features/book/service/book.service';
|
||||
import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component';
|
||||
import {AuthService} from './auth.service';
|
||||
import {UrlHelperService} from './url-helper.service';
|
||||
|
||||
describe('UrlHelperService', () => {
|
||||
const authServiceStub = {
|
||||
getInternalAccessToken: vi.fn(),
|
||||
};
|
||||
|
||||
const bookServiceStub = {
|
||||
findBookById: vi.fn(),
|
||||
};
|
||||
|
||||
const routerStub = {
|
||||
createUrlTree: vi.fn((commands: unknown[], extras?: unknown) => ({commands, extras})),
|
||||
};
|
||||
|
||||
let service: UrlHelperService;
|
||||
|
||||
const bookWithMetadata = {
|
||||
id: 42,
|
||||
metadata: {
|
||||
title: 'The Testing Atlas',
|
||||
authors: ['Ada Lovelace', 'Grace Hopper'],
|
||||
},
|
||||
} as Book;
|
||||
|
||||
const supportedReadingRoutes: {bookType: BookType; readerSegment: string}[] = [
|
||||
{bookType: 'PDF', readerSegment: 'pdf-reader'},
|
||||
{bookType: 'EPUB', readerSegment: 'ebook-reader'},
|
||||
{bookType: 'FB2', readerSegment: 'ebook-reader'},
|
||||
{bookType: 'MOBI', readerSegment: 'ebook-reader'},
|
||||
{bookType: 'AZW3', readerSegment: 'ebook-reader'},
|
||||
{bookType: 'CBX', readerSegment: 'cbx-reader'},
|
||||
{bookType: 'AUDIOBOOK', readerSegment: 'audiobook-player'},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
authServiceStub.getInternalAccessToken.mockReturnValue('token-123');
|
||||
bookServiceStub.findBookById.mockReset();
|
||||
bookServiceStub.findBookById.mockReturnValue(undefined);
|
||||
routerStub.createUrlTree.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
UrlHelperService,
|
||||
{provide: AuthService, useValue: authServiceStub},
|
||||
{provide: BookService, useValue: bookServiceStub},
|
||||
{provide: Router, useValue: routerStub},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(UrlHelperService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('generates a portrait cover when cached metadata exists and no updated marker is provided', () => {
|
||||
bookServiceStub.findBookById.mockReturnValue(bookWithMetadata);
|
||||
|
||||
const generateCoverSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockImplementation(function (this: CoverGeneratorComponent) {
|
||||
return `${this.title}|${this.author}|${this.isSquare ? 'square' : 'portrait'}`;
|
||||
});
|
||||
|
||||
const url = service.getThumbnailUrl(42);
|
||||
|
||||
expect(generateCoverSpy).toHaveBeenCalledTimes(1);
|
||||
expect(url).toBe('The Testing Atlas|Ada Lovelace, Grace Hopper|portrait');
|
||||
});
|
||||
|
||||
it('appends the token to thumbnail urls that already have a cache key', () => {
|
||||
const url = service.getThumbnailUrl(42, 'updated-2024');
|
||||
|
||||
expect(url).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/thumbnail?updated-2024&token=token-123`);
|
||||
});
|
||||
|
||||
it('returns direct thumbnail and backup urls without a token when auth is unavailable', () => {
|
||||
authServiceStub.getInternalAccessToken.mockReturnValue(null);
|
||||
|
||||
expect(service.getDirectThumbnailUrl(42)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/thumbnail`);
|
||||
expect(service.getBackupCoverUrl(42)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/backup-cover`);
|
||||
});
|
||||
|
||||
it('generates a square audiobook cover when cached metadata exists', () => {
|
||||
bookServiceStub.findBookById.mockReturnValue(bookWithMetadata);
|
||||
|
||||
const generateCoverSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockImplementation(function (this: CoverGeneratorComponent) {
|
||||
return `${this.title}|${this.author}|${this.isSquare ? 'square' : 'portrait'}`;
|
||||
});
|
||||
|
||||
const url = service.getAudiobookCoverUrl(42);
|
||||
|
||||
expect(generateCoverSpy).toHaveBeenCalledTimes(1);
|
||||
expect(url).toBe('The Testing Atlas|Ada Lovelace, Grace Hopper|square');
|
||||
});
|
||||
|
||||
it('uses the audiobook media url when an updated marker is present', () => {
|
||||
expect(service.getAudiobookThumbnailUrl(42, 'updated-2024')).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/audiobook-thumbnail?updated-2024&token=token-123`);
|
||||
});
|
||||
|
||||
it.each(supportedReadingRoutes)('routes %s books to the correct reader path', ({bookType, readerSegment}: {bookType: BookType; readerSegment: string}) => {
|
||||
const book = {
|
||||
id: 77,
|
||||
primaryFile: {bookType},
|
||||
} as Book;
|
||||
|
||||
expect(service.getBookPrimaryReadingUrl(book)).toEqual({
|
||||
commands: [`/${readerSegment}/book/77`],
|
||||
extras: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to the book page for unsupported primary file types', () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const book = {
|
||||
id: 88,
|
||||
primaryFile: {bookType: undefined},
|
||||
} as Book;
|
||||
|
||||
expect(service.getBookPrimaryReadingUrl(book)).toEqual({
|
||||
commands: ['/book', 88],
|
||||
extras: {queryParams: {tab: 'view'}},
|
||||
});
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Unsupported book type:', undefined);
|
||||
});
|
||||
|
||||
it('builds series and generic book filters with the expected router shape', () => {
|
||||
expect(service.filterBooksBy('series', 'The Wheel of Time')).toEqual({
|
||||
commands: ['/series', 'The Wheel of Time'],
|
||||
extras: undefined,
|
||||
});
|
||||
|
||||
expect(service.filterBooksBy('author', 'Ursula K. Le Guin')).toEqual({
|
||||
commands: ['/all-books'],
|
||||
extras: {
|
||||
queryParams: {
|
||||
view: 'grid',
|
||||
sort: 'title',
|
||||
direction: 'asc',
|
||||
sidebar: true,
|
||||
filter: 'author:Ursula%20K.%20Le%20Guin',
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
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 {VersionService} from './version.service';
|
||||
|
||||
describe('VersionService', () => {
|
||||
let service: VersionService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
VersionService,
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(VersionService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('fetches the current application version', () => {
|
||||
service.getVersion().subscribe(version => {
|
||||
expect(version).toEqual({current: '1.0.0', latest: '1.0.1'});
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/version`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({current: '1.0.0', latest: '1.0.1'});
|
||||
});
|
||||
|
||||
it('fetches the changelog entries', () => {
|
||||
service.getChangelog().subscribe(entries => {
|
||||
expect(entries).toEqual([{
|
||||
version: '1.0.1',
|
||||
name: 'Patch release',
|
||||
changelog: 'Bug fixes',
|
||||
url: 'https://example.test/release/1.0.1',
|
||||
publishedAt: '2026-03-26T00:00:00Z',
|
||||
}]);
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/version/changelog`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush([{
|
||||
version: '1.0.1',
|
||||
name: 'Patch release',
|
||||
changelog: 'Bug fixes',
|
||||
url: 'https://example.test/release/1.0.1',
|
||||
publishedAt: '2026-03-26T00:00:00Z',
|
||||
}]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
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 {BookCoverService, CoverFetchRequest, CoverImage} from './book-cover.service';
|
||||
|
||||
describe('BookCoverService', () => {
|
||||
let service: BookCoverService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
BookCoverService,
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookCoverService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('posts the cover fetch request and returns the backend response', () => {
|
||||
const requestBody: CoverFetchRequest = {
|
||||
title: 'Dune',
|
||||
author: 'Frank Herbert',
|
||||
coverType: 'ebook',
|
||||
};
|
||||
const response: CoverImage[] = [
|
||||
{url: 'https://example.test/cover-1.jpg', source: 'google', width: 600, height: 900, index: 0},
|
||||
{url: 'https://example.test/cover-2.jpg', source: 'openlibrary', index: 1},
|
||||
];
|
||||
|
||||
let result: CoverImage[] | undefined;
|
||||
service.fetchBookCovers(requestBody).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/1/metadata/covers'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual(requestBody);
|
||||
request.flush(response);
|
||||
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
|
||||
import {DashboardSettingsComponent} from '../../features/dashboard/components/dashboard-settings/dashboard-settings.component';
|
||||
import {LibraryCreatorComponent} from '../../features/library-creator/library-creator.component';
|
||||
import {DialogLauncherService, DialogSize, DialogStyle} from './dialog-launcher.service';
|
||||
|
||||
describe('DialogLauncherService', () => {
|
||||
const dialogRef = {close: vi.fn()};
|
||||
const dialogService = {
|
||||
open: vi.fn(() => dialogRef),
|
||||
};
|
||||
|
||||
let service: DialogLauncherService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
dialogService.open.mockClear();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
DialogLauncherService,
|
||||
{provide: DialogService, useValue: dialogService},
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(DialogLauncherService);
|
||||
});
|
||||
|
||||
it('merges the default dialog options with caller overrides', () => {
|
||||
service.openDialog(LibraryCreatorComponent, {
|
||||
showHeader: false,
|
||||
data: {mode: 'create'},
|
||||
});
|
||||
|
||||
expect(dialogService.open).toHaveBeenCalledWith(
|
||||
LibraryCreatorComponent,
|
||||
expect.objectContaining({
|
||||
baseZIndex: 10,
|
||||
closable: true,
|
||||
dismissableMask: true,
|
||||
draggable: false,
|
||||
modal: true,
|
||||
resizable: false,
|
||||
showHeader: false,
|
||||
maximizable: false,
|
||||
data: {mode: 'create'},
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('opens the dashboard settings dialog with the expected style class', () => {
|
||||
service.openDashboardSettingsDialog();
|
||||
|
||||
expect(dialogService.open).toHaveBeenCalledWith(
|
||||
DashboardSettingsComponent,
|
||||
expect.objectContaining({
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('passes the library id into the library edit dialog', () => {
|
||||
service.openLibraryEditDialog(12);
|
||||
|
||||
expect(dialogService.open).toHaveBeenCalledWith(
|
||||
LibraryCreatorComponent,
|
||||
expect.objectContaining({
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
mode: 'edit',
|
||||
libraryId: 12,
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {IconCacheService} from './icon-cache.service';
|
||||
|
||||
describe('IconCacheService', () => {
|
||||
it('stores, retrieves, removes, and sorts cached icon names', () => {
|
||||
const service = new IconCacheService();
|
||||
const sanitized = {id: 'sanitized'} as never;
|
||||
|
||||
expect(service.getCachedSanitized('missing')).toBeNull();
|
||||
|
||||
service.cacheIcon('beta', '<svg />', sanitized);
|
||||
service.cacheIcon('alpha', '<svg />', sanitized);
|
||||
|
||||
expect(service.getCachedSanitized('alpha')).toBe(sanitized);
|
||||
expect(service.getAllIconNames()).toEqual(['alpha', 'beta']);
|
||||
expect(service.removeIcon('beta')).toBe(true);
|
||||
expect(service.getCachedSanitized('beta')).toBeNull();
|
||||
expect(service.removeIcon('beta')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {IconCacheService} from './icon-cache.service';
|
||||
import {IconService} from './icon.service';
|
||||
|
||||
describe('IconService', () => {
|
||||
let service: IconService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let iconCache: {
|
||||
getCachedSanitized: ReturnType<typeof vi.fn>;
|
||||
cacheIcon: ReturnType<typeof vi.fn>;
|
||||
removeIcon: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let bypassSecurityTrustHtml: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
iconCache = {
|
||||
getCachedSanitized: vi.fn(() => null),
|
||||
cacheIcon: vi.fn(),
|
||||
removeIcon: vi.fn(),
|
||||
};
|
||||
bypassSecurityTrustHtml = vi.fn(value => value as SafeHtml);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
IconService,
|
||||
{
|
||||
provide: IconCacheService,
|
||||
useValue: iconCache,
|
||||
},
|
||||
{
|
||||
provide: DomSanitizer,
|
||||
useValue: {bypassSecurityTrustHtml},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(IconService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('maps icon names from the paged response shape', () => {
|
||||
let result: string[] | undefined;
|
||||
service.getIconNames(2, 25).subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.includes('/api/v1/icons?page=2&size=25'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({content: ['sun', 'moon']});
|
||||
|
||||
expect(result).toEqual(['sun', 'moon']);
|
||||
});
|
||||
|
||||
it('short-circuits svg content requests when the sanitized icon is already cached', () => {
|
||||
iconCache.getCachedSanitized.mockReturnValue('cached-safe-html' as SafeHtml);
|
||||
|
||||
let result: string | undefined;
|
||||
service.getSvgIconContent('sun').subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
httpTestingController.expectNone(req => req.url.includes('/api/v1/icons/sun/content'));
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('fetches svg content, sanitizes it, and caches the result', () => {
|
||||
let result: string | undefined;
|
||||
service.getSvgIconContent('sun').subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/icons/sun/content'));
|
||||
expect(request.request.method).toBe('GET');
|
||||
expect(request.request.responseType).toBe('text');
|
||||
request.flush('<svg><rect /></svg>');
|
||||
|
||||
expect(result).toBe('<svg><rect /></svg>');
|
||||
expect(bypassSecurityTrustHtml).toHaveBeenCalled();
|
||||
expect(iconCache.cacheIcon).toHaveBeenCalledWith(
|
||||
'sun',
|
||||
'<svg><rect /></svg>',
|
||||
expect.stringContaining('<svg>')
|
||||
);
|
||||
});
|
||||
|
||||
it('returns cached sanitized svg content without issuing a request', () => {
|
||||
iconCache.getCachedSanitized.mockReturnValue('cached-safe-html' as SafeHtml);
|
||||
|
||||
let result: SafeHtml | undefined;
|
||||
service.getSanitizedSvgContent('moon').subscribe(value => {
|
||||
result = value;
|
||||
});
|
||||
|
||||
httpTestingController.expectNone(req => req.url.includes('/api/v1/icons/moon/content'));
|
||||
expect(result).toBe('cached-safe-html');
|
||||
});
|
||||
|
||||
it('removes icons from the cache after deletion', () => {
|
||||
service.deleteSvgIcon('sun rise').subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/icons/sun%20rise'));
|
||||
expect(request.request.method).toBe('DELETE');
|
||||
request.flush(null);
|
||||
|
||||
expect(iconCache.removeIcon).toHaveBeenCalledWith('sun rise');
|
||||
});
|
||||
|
||||
it('caches only successfully saved icons from batch saves', () => {
|
||||
const icons = [
|
||||
{svgName: 'sun', svgData: '<svg>sun</svg>'},
|
||||
{svgName: 'moon', svgData: '<svg>moon</svg>'},
|
||||
];
|
||||
|
||||
service.saveBatchSvgIcons(icons).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/icons/batch'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.body).toEqual({icons});
|
||||
request.flush({
|
||||
totalRequested: 2,
|
||||
successCount: 1,
|
||||
failureCount: 1,
|
||||
results: [
|
||||
{iconName: 'sun', success: true, errorMessage: ''},
|
||||
{iconName: 'moon', success: false, errorMessage: 'duplicate'},
|
||||
],
|
||||
});
|
||||
|
||||
expect(iconCache.cacheIcon).toHaveBeenCalledTimes(1);
|
||||
expect(iconCache.cacheIcon).toHaveBeenCalledWith('sun', '<svg>sun</svg>', '<svg>sun</svg>');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {FontFormat} from '../model/custom-font.model';
|
||||
import {addCustomFontsToDropdown} from './custom-font.util';
|
||||
|
||||
describe('custom-font.util', () => {
|
||||
it('does nothing when no custom fonts are supplied', () => {
|
||||
const selectItems = [{label: 'System', value: 'system'}];
|
||||
const preferenceItems = [{name: 'System', displayName: 'System', key: 'system'}];
|
||||
|
||||
addCustomFontsToDropdown([], selectItems, 'select');
|
||||
addCustomFontsToDropdown([], preferenceItems, 'preference');
|
||||
|
||||
expect(selectItems).toEqual([{label: 'System', value: 'system'}]);
|
||||
expect(preferenceItems).toEqual([{name: 'System', displayName: 'System', key: 'system'}]);
|
||||
});
|
||||
|
||||
it('appends custom fonts to a select dropdown and removes stale separators', () => {
|
||||
const selectItems = [
|
||||
{label: 'System', value: 'system'},
|
||||
{label: 'Separator', value: 'separator'},
|
||||
];
|
||||
|
||||
addCustomFontsToDropdown([
|
||||
{id: 7, fontName: 'Bookerly', originalFileName: 'Bookerly.ttf', format: FontFormat.TTF, fileSize: 10, uploadedAt: '2026-03-26T00:00:00Z'},
|
||||
{id: 8, fontName: 'Atkinson Hyperlegible', originalFileName: 'Atkinson.ttf', format: FontFormat.TTF, fileSize: 10, uploadedAt: '2026-03-26T00:00:00Z'},
|
||||
], selectItems, 'select');
|
||||
|
||||
expect(selectItems).toEqual([
|
||||
{label: 'System', value: 'system'},
|
||||
{label: 'Bookerly', value: 'custom:7'},
|
||||
{label: 'Atkinson Hyperlegible', value: 'custom:8'},
|
||||
]);
|
||||
});
|
||||
|
||||
it('appends custom fonts to a preference dropdown with truncated display names', () => {
|
||||
const preferenceItems = [
|
||||
{name: 'System', displayName: 'System', key: 'system'},
|
||||
{name: 'Separator', displayName: 'Separator', key: 'separator'},
|
||||
];
|
||||
|
||||
addCustomFontsToDropdown([
|
||||
{id: 9, fontName: 'Very Long Font Name', originalFileName: 'Font.ttf', format: FontFormat.TTF, fileSize: 10, uploadedAt: '2026-03-26T00:00:00Z'},
|
||||
], preferenceItems, 'preference');
|
||||
|
||||
expect(preferenceItems).toEqual([
|
||||
{name: 'System', displayName: 'System', key: 'system'},
|
||||
{name: 'Very Long Font Name', displayName: 'Very Long Fo', key: 'custom:9'},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {applyModifier, replacePlaceholders} from './pattern-resolver';
|
||||
|
||||
describe('pattern-resolver', () => {
|
||||
it('returns the original value when the modifier is unknown or the value is empty', () => {
|
||||
expect(applyModifier('', 'upper', 'title')).toBe('');
|
||||
expect(applyModifier('Alpha', 'unknown', 'title')).toBe('Alpha');
|
||||
});
|
||||
|
||||
it('applies the supported value modifiers', () => {
|
||||
expect(applyModifier('Ada Lovelace, Grace Hopper', 'first', 'authors')).toBe('Ada Lovelace');
|
||||
expect(applyModifier('Ada Lovelace', 'sort', 'authors')).toBe('Lovelace, Ada');
|
||||
expect(applyModifier('Ada Lovelace', 'initial', 'authors')).toBe('L');
|
||||
expect(applyModifier('Chapter One', 'initial', 'title')).toBe('C');
|
||||
expect(applyModifier('Ada', 'upper', 'title')).toBe('ADA');
|
||||
expect(applyModifier('ADA', 'lower', 'title')).toBe('ada');
|
||||
});
|
||||
|
||||
it('replaces placeholders and respects optional fallback blocks', () => {
|
||||
expect(
|
||||
replacePlaceholders('<{title}|{fallback}> by {authors:first}', {
|
||||
title: 'The Book',
|
||||
authors: 'Ada Lovelace, Grace Hopper',
|
||||
fallback: 'Fallback Title',
|
||||
})
|
||||
).toBe('The Book by Ada Lovelace');
|
||||
|
||||
expect(
|
||||
replacePlaceholders('<{title}|{fallback}> by {authors:first}', {
|
||||
authors: 'Ada Lovelace, Grace Hopper',
|
||||
fallback: 'Fallback Title',
|
||||
})
|
||||
).toBe('Fallback Title by Ada Lovelace');
|
||||
});
|
||||
|
||||
it('handles nested modifier blocks and trims the final pattern', () => {
|
||||
expect(
|
||||
replacePlaceholders(' {authors:sort} - {title:upper} ', {
|
||||
authors: 'Ada Lovelace, Grace Hopper',
|
||||
title: 'calculus notes',
|
||||
})
|
||||
).toBe('Lovelace, Ada - CALCULUS NOTES');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {passwordMatchValidator} from './password-match.validator';
|
||||
|
||||
describe('passwordMatchValidator', () => {
|
||||
it('returns null until both values are present', () => {
|
||||
const validator = passwordMatchValidator('password', 'confirmPassword');
|
||||
const form = {
|
||||
get: (name: string) => ({value: name === 'password' ? '' : ''}),
|
||||
};
|
||||
|
||||
expect(validator(form as never)).toBeNull();
|
||||
|
||||
const withPassword = {
|
||||
get: (name: string) => ({value: name === 'password' ? 'secret' : ''}),
|
||||
};
|
||||
expect(validator(withPassword as never)).toBeNull();
|
||||
});
|
||||
|
||||
it('flags mismatched passwords', () => {
|
||||
const validator = passwordMatchValidator('password', 'confirmPassword');
|
||||
const form = {
|
||||
get: (name: string) => ({value: name === 'password' ? 'secret' : 'other'}),
|
||||
};
|
||||
|
||||
expect(validator(form as never)).toEqual({passwordMismatch: true});
|
||||
});
|
||||
|
||||
it('returns null for matching passwords', () => {
|
||||
const validator = passwordMatchValidator('password', 'confirmPassword');
|
||||
const form = {
|
||||
get: (name: string) => ({value: name === 'password' ? 'secret' : 'secret'}),
|
||||
};
|
||||
|
||||
expect(validator(form as never)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {parseLogNotification, Severity} from './log-notification.model';
|
||||
|
||||
describe('log-notification.model', () => {
|
||||
it('parses message bodies with timestamp and severity', () => {
|
||||
const parsed = parseLogNotification(JSON.stringify({
|
||||
timestamp: '2026-03-26T12:34:56.000Z',
|
||||
message: 'Library scan completed',
|
||||
severity: 'WARN'
|
||||
}));
|
||||
|
||||
expect(parsed.message).toBe('Library scan completed');
|
||||
expect(parsed.severity).toBe(Severity.WARN);
|
||||
expect(parsed.timestamp).toMatch(/\d{1,2}:\d{2}:\d{2}/);
|
||||
});
|
||||
|
||||
it('leaves optional fields undefined when they are not provided', () => {
|
||||
expect(parseLogNotification(JSON.stringify({message: 'hello'}))).toEqual({
|
||||
message: 'hello',
|
||||
severity: undefined,
|
||||
timestamp: undefined
|
||||
});
|
||||
});
|
||||
|
||||
it('throws on invalid JSON payloads', () => {
|
||||
expect(() => parseLogNotification('not-json')).toThrow(SyntaxError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import {beforeEach, afterEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {Severity} from './model/log-notification.model';
|
||||
import {NotificationEventService} from './notification-event.service';
|
||||
|
||||
describe('NotificationEventService', () => {
|
||||
let service: NotificationEventService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
service = new NotificationEventService();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('emits the latest notification and highlights it immediately', () => {
|
||||
const notifications: string[] = [];
|
||||
const highlights: boolean[] = [];
|
||||
|
||||
service.latestNotification$.subscribe(notification => notifications.push(notification.message));
|
||||
service.notificationHighlight$.subscribe(value => highlights.push(value));
|
||||
|
||||
service.handleNewNotification({message: 'Index updated', severity: Severity.INFO});
|
||||
|
||||
expect(notifications).toEqual(['Index updated']);
|
||||
expect(highlights.at(-1)).toBe(true);
|
||||
});
|
||||
|
||||
it('turns off the highlight after the timeout elapses', () => {
|
||||
const highlights: boolean[] = [];
|
||||
|
||||
service.notificationHighlight$.subscribe(value => highlights.push(value));
|
||||
service.handleNewNotification({message: 'Index updated', severity: Severity.INFO});
|
||||
|
||||
vi.advanceTimersByTime(7500);
|
||||
|
||||
expect(highlights).toEqual([false, true, false]);
|
||||
});
|
||||
|
||||
it('restarts the highlight timeout when a new notification arrives', () => {
|
||||
const highlights: boolean[] = [];
|
||||
|
||||
service.notificationHighlight$.subscribe(value => highlights.push(value));
|
||||
service.handleNewNotification({message: 'First', severity: Severity.INFO});
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
service.handleNewNotification({message: 'Second', severity: Severity.WARN});
|
||||
vi.advanceTimersByTime(7499);
|
||||
|
||||
expect(highlights.at(-1)).toBe(true);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
|
||||
expect(highlights.at(-1)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import {Injector, runInInjectionContext} from '@angular/core';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AuthService} from '../service/auth.service';
|
||||
import {rxStompServiceFactory} from './rx-stomp-service-factory';
|
||||
import {RxStompService} from './rx-stomp.service';
|
||||
|
||||
describe('rxStompServiceFactory', () => {
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
});
|
||||
|
||||
it('creates an RxStompService and configures it from the auth service', () => {
|
||||
const configureSpy = vi.spyOn(RxStompService.prototype, 'configure');
|
||||
const injector = Injector.create({
|
||||
providers: [
|
||||
{provide: AuthService, useValue: authService},
|
||||
]
|
||||
});
|
||||
|
||||
const service = runInInjectionContext(
|
||||
injector,
|
||||
() => rxStompServiceFactory(authService as unknown as AuthService)
|
||||
);
|
||||
|
||||
expect(service).toBeInstanceOf(RxStompService);
|
||||
expect(configureSpy).toHaveBeenCalled();
|
||||
|
||||
const lastConfig = configureSpy.mock.calls.at(-1)?.[0];
|
||||
expect(lastConfig?.brokerURL).toBeDefined();
|
||||
expect(lastConfig?.beforeConnect).toBeTypeOf('function');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {AuthService} from '../service/auth.service';
|
||||
import {createRxStompConfig} from './rx-stomp.config';
|
||||
|
||||
type BeforeConnectTarget = Parameters<NonNullable<ReturnType<typeof createRxStompConfig>['beforeConnect']>>[0];
|
||||
|
||||
describe('createRxStompConfig', () => {
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
});
|
||||
|
||||
it('returns the expected connection defaults', () => {
|
||||
const config = createRxStompConfig(authService as unknown as AuthService);
|
||||
|
||||
expect(config.brokerURL).toBe(API_CONFIG.BROKER_URL);
|
||||
expect(config.heartbeatIncoming).toBe(0);
|
||||
expect(config.heartbeatOutgoing).toBe(20000);
|
||||
expect(config.reconnectDelay).toBe(10000);
|
||||
});
|
||||
|
||||
it('injects the bearer token into connect headers when one is available', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('access-token');
|
||||
const config = createRxStompConfig(authService as unknown as AuthService);
|
||||
const stomp = {
|
||||
stompClient: {
|
||||
connectHeaders: {},
|
||||
}
|
||||
};
|
||||
|
||||
config.beforeConnect?.(stomp as unknown as BeforeConnectTarget);
|
||||
|
||||
expect(stomp.stompClient.connectHeaders).toEqual({
|
||||
Authorization: 'Bearer access-token',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not add authorization headers when there is no access token', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
const config = createRxStompConfig(authService as unknown as AuthService);
|
||||
const stomp = {
|
||||
stompClient: {
|
||||
connectHeaders: {},
|
||||
}
|
||||
};
|
||||
|
||||
config.beforeConnect?.(stomp as unknown as BeforeConnectTarget);
|
||||
|
||||
expect(stomp.stompClient.connectHeaders).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {RxStompConfig} from '@stomp/rx-stomp';
|
||||
|
||||
import {AuthService} from '../service/auth.service';
|
||||
import {RxStompService} from './rx-stomp.service';
|
||||
|
||||
describe('RxStompService', () => {
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
RxStompService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('configures the stomp client when it is created', () => {
|
||||
const configureSpy = vi.spyOn(RxStompService.prototype, 'configure');
|
||||
const service = TestBed.inject(RxStompService);
|
||||
|
||||
expect(service).toBeInstanceOf(RxStompService);
|
||||
expect(configureSpy).toHaveBeenCalled();
|
||||
const initialConfig = configureSpy.mock.calls[0]?.[0];
|
||||
expect(initialConfig?.beforeConnect).toBeTypeOf('function');
|
||||
});
|
||||
|
||||
it('delegates updateConfig to configure', () => {
|
||||
const service = TestBed.inject(RxStompService);
|
||||
const configureSpy = vi.spyOn(service, 'configure');
|
||||
const config = {brokerURL: 'ws://example.test'} as RxStompConfig;
|
||||
|
||||
service.updateConfig(config);
|
||||
|
||||
expect(configureSpy).toHaveBeenCalledWith(config);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user