import { signal } from "@angular/core"; import { ComponentFixture, TestBed } from "@angular/core/testing"; import { TranslocoTestingModule } from "@jsverse/transloco"; import { BehaviorSubject, Subject } from "rxjs"; import { RxStompState } from "@stomp/rx-stomp"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { AppComponent } from "./app.component"; import { AuthInitializationService } from "./core/security/auth-initialization-service"; import { RxStompService } from "./shared/websocket/rx-stomp.service"; import { BookService } from "./features/book/service/book.service"; import { MetadataRefreshSubmissionService } from "./features/metadata/data/metadata-refresh-submission.service"; import { NotificationEventService } from "./shared/websocket/notification-event.service"; import { AppThemeService } from "./shared/service/app-theme.service"; import { MetadataProgressService } from "./shared/service/metadata-progress.service"; import { BookdropFileService } from "./features/bookdrop/service/bookdrop-file.service"; import { TaskService } from "./features/settings/task-management/task.service"; import { LibraryHealthService } from "./features/book/service/library-health.service"; import { AuthService } from "./shared/service/auth.service"; import { ConfirmationService } from "@openng/optimus-ui/api"; import { MessageService } from "@openng/optimus-ui/api"; import { CommandPaletteService } from "./features/command-palette/command-palette.service"; import { LibraryImportProgressService } from "./shared/service/library-import-progress.service"; import { AuthorService } from "./features/author-browser/service/author.service"; interface StompMessage { body: string; } const DEFAULT_AUTH = { ready: true, authenticated: true }; describe("AppComponent", () => { let fixture: ComponentFixture; let component: AppComponent; let topics: Map>; let connectionState: BehaviorSubject; let rxStompService: { watch: ReturnType; connectionState$: BehaviorSubject; }; let bookService: { handleNewlyCreatedBook: ReturnType; handleBookUpdate: ReturnType; handleMultipleBookCoverPatches: ReturnType; handleRemovedBookIds: ReturnType; handleTaskProgress: ReturnType; handleReconnect: ReturnType; }; let authorService: { handleNewlyCreatedBook: ReturnType; invalidateAuthors: ReturnType; }; let notificationEventService: { handleNewNotification: ReturnType; }; let metadataProgressService: { handleIncomingProgress: ReturnType; }; let bookdropFileService: { handleIncomingFile: ReturnType }; let taskService: { handleTaskProgress: ReturnType }; let metadataRefreshSubmissionService: { handleBatchProgress: ReturnType }; let libraryHealthService: { initWebsocket: ReturnType, fetchHealth: ReturnType }; let authService: { forceLogout: ReturnType, isAuthenticated: ReturnType }; let libraryImportProgressService: { recordBookAdded: ReturnType }; let commandPaletteService: { toggle: ReturnType; open: ReturnType; hide: ReturnType; registerOverlayController: ReturnType; isOpen: ReturnType; query: ReturnType; visibleItems: ReturnType; groups: ReturnType; }; function createTopicStream(topic: string): Subject { const stream = new Subject(); topics.set(topic, stream); return stream; } function configureComponent( auth = DEFAULT_AUTH ): void { topics = new Map(); connectionState = new BehaviorSubject(RxStompState.CLOSED); rxStompService = { watch: vi.fn((topic: string) => (topics.get(topic) ?? createTopicStream(topic)).asObservable(), ), connectionState$: connectionState, }; bookService = { handleNewlyCreatedBook: vi.fn(), handleBookUpdate: vi.fn(), handleMultipleBookCoverPatches: vi.fn(), handleRemovedBookIds: vi.fn(), handleTaskProgress: vi.fn(), handleReconnect: vi.fn(), }; authorService = { handleNewlyCreatedBook: vi.fn(), invalidateAuthors: vi.fn() }; notificationEventService = { handleNewNotification: vi.fn() }; metadataProgressService = { handleIncomingProgress: vi.fn() }; bookdropFileService = { handleIncomingFile: vi.fn() }; taskService = { handleTaskProgress: vi.fn() }; metadataRefreshSubmissionService = { handleBatchProgress: vi.fn() }; libraryHealthService = { initWebsocket: vi.fn(), fetchHealth: vi.fn() }; authService = { forceLogout: vi.fn(), isAuthenticated: signal(auth.authenticated) }; libraryImportProgressService = { recordBookAdded: vi.fn() }; commandPaletteService = { toggle: vi.fn(), open: vi.fn(), hide: vi.fn(), registerOverlayController: vi.fn(() => vi.fn()), isOpen: signal(false), query: signal(''), visibleItems: signal([]), groups: signal([]), }; TestBed.configureTestingModule({ imports: [TranslocoTestingModule.forRoot({ langs: {} })], providers: [ { provide: AuthInitializationService, useValue: { initialized: signal(auth.ready) }, }, { provide: RxStompService, useValue: rxStompService }, { provide: BookService, useValue: bookService }, { provide: AuthorService, useValue: authorService }, { provide: NotificationEventService, useValue: notificationEventService, }, { provide: AppThemeService, useValue: {} }, { provide: MetadataProgressService, useValue: metadataProgressService }, { provide: BookdropFileService, useValue: bookdropFileService }, { provide: TaskService, useValue: taskService }, { provide: MetadataRefreshSubmissionService, useValue: metadataRefreshSubmissionService }, { provide: LibraryHealthService, useValue: libraryHealthService }, { provide: AuthService, useValue: authService }, { provide: LibraryImportProgressService, useValue: libraryImportProgressService }, { provide: CommandPaletteService, useValue: commandPaletteService }, ConfirmationService, MessageService], }); fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; fixture.detectChanges(); } beforeEach(() => { vi.restoreAllMocks(); }); afterEach(() => { fixture?.destroy(); TestBed.resetTestingModule(); vi.restoreAllMocks(); }); it("boots the websocket wiring when auth initialization is ready", () => { configureComponent(); expect(component.loading()).toBe(false); expect(libraryHealthService.initWebsocket).toHaveBeenCalledOnce(); expect(libraryHealthService.fetchHealth).toHaveBeenCalledOnce(); expect(rxStompService.watch).toHaveBeenCalledWith("/user/queue/book-add"); expect(rxStompService.watch).toHaveBeenCalledWith( "/user/queue/session-revoked", ); }); it("boots the websocket wiring but don't fetch library health when not authenticated", () => { configureComponent({ ready: true, authenticated: false }); expect(component.loading()).toBe(false); expect(libraryHealthService.initWebsocket).toHaveBeenCalledOnce(); expect(libraryHealthService.fetchHealth).not.toHaveBeenCalled(); }); it("routes websocket book notifications to bookService", () => { configureComponent(); topics .get("/user/queue/book-add") ?.next({ body: JSON.stringify({ metadata: { title: "First" } }) }); expect(bookService.handleNewlyCreatedBook).toHaveBeenCalledWith({ metadata: { title: "First" } }); expect(authorService.handleNewlyCreatedBook).toHaveBeenCalledWith({ metadata: { title: "First" } }); expect(libraryImportProgressService.recordBookAdded).toHaveBeenCalledWith("First"); }); it("forwards websocket updates to the matching root services", () => { configureComponent(); topics .get("/user/queue/book-update") ?.next({ body: JSON.stringify({ id: 1, libraryId: 1, libraryName: "Library" }) }); topics .get("/user/queue/books-cover-update") ?.next({ body: JSON.stringify([{ id: 1 }]) }); topics .get("/user/queue/books-remove") ?.next({ body: JSON.stringify([1, 2]) }); topics .get("/user/queue/book-metadata-update") ?.next({ body: JSON.stringify({ id: 2, libraryId: 1, libraryName: "Library" }) }); topics .get("/user/queue/book-metadata-batch-progress") ?.next({ body: JSON.stringify({ taskId: "task-1" }) }); topics .get("/user/queue/log") ?.next({ body: JSON.stringify({ message: "info", severity: "INFO" }) }); topics .get("/user/queue/bookdrop-file") ?.next({ body: JSON.stringify({ pendingCount: 1, totalCount: 2 }) }); topics .get("/user/queue/task-progress") ?.next({ body: JSON.stringify({ taskId: "task-2" }) }); expect(bookService.handleBookUpdate).toHaveBeenCalledWith( { id: 1, libraryId: 1, libraryName: "Library" }, ); expect(bookService.handleBookUpdate).toHaveBeenCalledWith( { id: 2, libraryId: 1, libraryName: "Library" }, ); expect(bookService.handleMultipleBookCoverPatches).toHaveBeenCalledWith([ { id: 1 }]); expect(bookService.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]); expect(metadataProgressService.handleIncomingProgress).toHaveBeenCalledWith( { taskId: "task-1" }, ); expect(metadataRefreshSubmissionService.handleBatchProgress).toHaveBeenCalledWith( { taskId: "task-1" }, ); expect(notificationEventService.handleNewNotification).toHaveBeenCalledWith( { message: "info", severity: "INFO", }, ); expect(bookdropFileService.handleIncomingFile).toHaveBeenCalledWith({ pendingCount: 1, totalCount: 2, }); expect(taskService.handleTaskProgress).toHaveBeenCalledWith({ taskId: "task-2", }); expect(bookService.handleTaskProgress).toHaveBeenCalledWith({ taskId: "task-2", }); }); it("reconciles book caches after a websocket reconnect", () => { configureComponent(); connectionState.next(RxStompState.OPEN); expect(bookService.handleReconnect).not.toHaveBeenCalled(); connectionState.next(RxStompState.CLOSED); connectionState.next(RxStompState.OPEN); expect(bookService.handleReconnect).toHaveBeenCalledOnce(); expect(authorService.invalidateAuthors).toHaveBeenCalledOnce(); }); it("forces logout when the session is revoked", () => { configureComponent(); topics.get("/user/queue/session-revoked")?.next({ body: "" }); expect(authService.forceLogout).toHaveBeenCalledWith("session_revoked"); }); it("unsubscribes when destroyed", () => { configureComponent(); component.ngOnDestroy(); topics .get("/user/queue/book-update") ?.next({ body: JSON.stringify({ id: 99 }) }); expect(bookService.handleBookUpdate).not.toHaveBeenCalled(); }); });