Introduce Vitest as the frontend Angular testing framework for Booklore (#2150)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+7
-4
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.metadata;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
@@ -26,11 +27,13 @@ import org.mockito.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class BookCoverServiceTest {
|
||||
@@ -243,7 +246,7 @@ class BookCoverServiceTest {
|
||||
assertThat(result).isNotNull();
|
||||
}
|
||||
|
||||
private com.adityachandel.booklore.model.dto.settings.AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) {
|
||||
private AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) {
|
||||
MetadataPersistenceSettings settings = new MetadataPersistenceSettings();
|
||||
settings.setSaveToOriginalFile(saveToOriginalFile);
|
||||
settings.setConvertCbrCb7ToCbz(convertCbrCb7ToCbz);
|
||||
|
||||
@@ -106,25 +106,7 @@
|
||||
"builder": "@angular/build:extract-i18n"
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular/build:karma",
|
||||
"options": {
|
||||
"polyfills": [
|
||||
"zone.js",
|
||||
"zone.js/testing"
|
||||
],
|
||||
"tsConfig": "tsconfig.spec.json",
|
||||
"inlineStyleLanguage": "scss",
|
||||
"assets": [
|
||||
{
|
||||
"glob": "**/*",
|
||||
"input": "public"
|
||||
}
|
||||
],
|
||||
"styles": [
|
||||
"src/styles.scss"
|
||||
],
|
||||
"scripts": []
|
||||
}
|
||||
"builder": "@angular/build:unit-test"
|
||||
},
|
||||
"lint": {
|
||||
"builder": "@angular-eslint/builder:lint",
|
||||
|
||||
Generated
+1069
-224
File diff suppressed because it is too large
Load Diff
@@ -53,18 +53,16 @@
|
||||
"@angular/compiler-cli": "^21.0.5",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@types/jasmine": "^5.1.13",
|
||||
"@types/node": "^25.0.3",
|
||||
"@types/showdown": "^2.0.6",
|
||||
"angular-eslint": "^21.1.0",
|
||||
"autoprefixer": "^10.4.23",
|
||||
"eslint": "^9.39.2",
|
||||
"jasmine-core": "^5.13.0",
|
||||
"karma": "^6.4.4",
|
||||
"karma-chrome-launcher": "^3.2.0",
|
||||
"karma-coverage": "^2.2.1",
|
||||
"karma-jasmine": "^5.1.0",
|
||||
"karma-jasmine-html-reporter": "^2.1.0",
|
||||
"jsdom": "^27.4.0",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.50.0"
|
||||
"typescript-eslint": "^8.50.0",
|
||||
"vitest": "^4.0.16"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {BookService} from './book.service';
|
||||
import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {User} from '../../settings/user-management/user.service';
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {HttpErrorResponse} from '@angular/common/http';
|
||||
import {APIException} from '../../../shared/models/api-exception.model';
|
||||
import {BookMenuService} from './book-menu.service';
|
||||
|
||||
describe('BookMenuService', () => {
|
||||
let service: BookMenuService;
|
||||
let confirmationService: any;
|
||||
let messageService: any;
|
||||
let bookService: any;
|
||||
let loadingService: any;
|
||||
|
||||
const mockUser: User = {
|
||||
id: 1,
|
||||
username: 'testuser',
|
||||
email: 'test@example.com',
|
||||
permissions: {
|
||||
canBulkAutoFetchMetadata: true,
|
||||
canBulkCustomFetchMetadata: true,
|
||||
canBulkEditMetadata: true,
|
||||
canBulkRegenerateCover: true,
|
||||
canBulkResetBookReadStatus: true,
|
||||
canBulkResetBookloreReadProgress: true,
|
||||
canBulkResetKoReaderReadProgress: true
|
||||
}
|
||||
} as User;
|
||||
|
||||
const mockUserNoPermissions: User = {
|
||||
id: 2,
|
||||
username: 'limiteduser',
|
||||
email: 'limited@example.com',
|
||||
permissions: {
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canBulkResetBookReadStatus: false,
|
||||
canBulkResetBookloreReadProgress: false,
|
||||
canBulkResetKoReaderReadProgress: false
|
||||
}
|
||||
} as User;
|
||||
|
||||
beforeEach(() => {
|
||||
confirmationService = {
|
||||
confirm: vi.fn()
|
||||
};
|
||||
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
|
||||
bookService = {
|
||||
updateBookReadStatus: vi.fn(),
|
||||
resetProgress: vi.fn()
|
||||
};
|
||||
|
||||
loadingService = {
|
||||
show: vi.fn().mockReturnValue('loader-id'),
|
||||
hide: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookMenuService,
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: LoadingService, useValue: loadingService}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(BookMenuService)
|
||||
);
|
||||
});
|
||||
|
||||
describe('getMetadataMenuItems', () => {
|
||||
it('should return all metadata menu items when user has all permissions', () => {
|
||||
const autoFetch = vi.fn();
|
||||
const fetch = vi.fn();
|
||||
const bulkEdit = vi.fn();
|
||||
const multiEdit = vi.fn();
|
||||
const regenerate = vi.fn();
|
||||
|
||||
const items = service.getMetadataMenuItems(
|
||||
autoFetch,
|
||||
fetch,
|
||||
bulkEdit,
|
||||
multiEdit,
|
||||
regenerate,
|
||||
mockUser
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(5);
|
||||
expect(items[0].label).toBe('Auto Fetch Metadata');
|
||||
expect(items[0].icon).toBe('pi pi-bolt');
|
||||
expect(items[1].label).toBe('Custom Fetch Metadata');
|
||||
expect(items[1].icon).toBe('pi pi-sync');
|
||||
expect(items[2].label).toBe('Bulk Metadata Editor');
|
||||
expect(items[2].icon).toBe('pi pi-table');
|
||||
expect(items[3].label).toBe('Multi-Book Metadata Editor');
|
||||
expect(items[3].icon).toBe('pi pi-clone');
|
||||
expect(items[4].label).toBe('Regenerate Covers');
|
||||
expect(items[4].icon).toBe('pi pi-image');
|
||||
});
|
||||
|
||||
it('should return empty array when user has no permissions', () => {
|
||||
const items = service.getMetadataMenuItems(
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
mockUserNoPermissions
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return empty array when user is null', () => {
|
||||
const items = service.getMetadataMenuItems(
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
null
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should call command functions when menu items are clicked', () => {
|
||||
const autoFetch = vi.fn();
|
||||
const fetch = vi.fn();
|
||||
const bulkEdit = vi.fn();
|
||||
const multiEdit = vi.fn();
|
||||
const regenerate = vi.fn();
|
||||
|
||||
const items = service.getMetadataMenuItems(
|
||||
autoFetch,
|
||||
fetch,
|
||||
bulkEdit,
|
||||
multiEdit,
|
||||
regenerate,
|
||||
mockUser
|
||||
);
|
||||
|
||||
items[0].command!({} as any);
|
||||
expect(autoFetch).toHaveBeenCalledOnce();
|
||||
|
||||
items[1].command!({} as any);
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
|
||||
items[2].command!({} as any);
|
||||
expect(bulkEdit).toHaveBeenCalledOnce();
|
||||
|
||||
items[3].command!({} as any);
|
||||
expect(multiEdit).toHaveBeenCalledOnce();
|
||||
|
||||
items[4].command!({} as any);
|
||||
expect(regenerate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should return only items for granted permissions', () => {
|
||||
const partialUser: User = {
|
||||
...mockUser,
|
||||
permissions: {
|
||||
...mockUser.permissions,
|
||||
canBulkAutoFetchMetadata: true,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: true,
|
||||
canBulkRegenerateCover: false
|
||||
}
|
||||
} as User;
|
||||
|
||||
const items = service.getMetadataMenuItems(
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
partialUser
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items[0].label).toBe('Auto Fetch Metadata');
|
||||
expect(items[1].label).toBe('Bulk Metadata Editor');
|
||||
expect(items[2].label).toBe('Multi-Book Metadata Editor');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBulkReadActionsMenu', () => {
|
||||
it('should return all read action items when user has all permissions', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items[0].label).toBe('Update Read Status');
|
||||
expect(items[0].icon).toBe('pi pi-book');
|
||||
expect(items[0].items).toBeDefined();
|
||||
expect(items[0].items!.length).toBeGreaterThan(0);
|
||||
expect(items[1].label).toBe('Reset Booklore Progress');
|
||||
expect(items[1].icon).toBe('pi pi-undo');
|
||||
expect(items[2].label).toBe('Reset KOReader Progress');
|
||||
expect(items[2].icon).toBe('pi pi-undo');
|
||||
});
|
||||
|
||||
it('should return empty array when user has no permissions', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUserNoPermissions);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return empty array when user is null', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, null);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should show confirmation dialog when updating read status', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
const readStatusItems = items[0].items!;
|
||||
readStatusItems[0].command!({} as any);
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain('3 book(s)');
|
||||
expect(confirmCall.header).toBe('Confirm Read Status Update');
|
||||
});
|
||||
|
||||
it('should update read status on confirmation accept', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(of([]));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
const readStatusItems = items[0].items!;
|
||||
|
||||
const readItem = readStatusItems.find(item => item.label === 'Read');
|
||||
expect(readItem).toBeDefined();
|
||||
|
||||
readItem!.command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(loadingService.show).toHaveBeenCalledWith('Updating read status for 3 book(s)...');
|
||||
expect(bookService.updateBookReadStatus).toHaveBeenCalledWith([1, 2, 3], ReadStatus.READ);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'Read Status Updated',
|
||||
detail: 'Marked as "Read"',
|
||||
life: 2000
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message when read status update fails', () => {
|
||||
const selectedBooks = new Set([1, 2]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {message: 'Update failed'} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
const readStatusItems = items[0].items!;
|
||||
|
||||
readStatusItems[0].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Update failed',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog when resetting Booklore progress', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
items[1].command!({} as any);
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain('3 book(s)');
|
||||
expect(confirmCall.header).toBe('Confirm Reset');
|
||||
});
|
||||
|
||||
it('should reset Booklore progress on confirmation accept', () => {
|
||||
const selectedBooks = new Set([5, 6]);
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(of([]));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[1].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(loadingService.show).toHaveBeenCalledWith('Resetting Booklore progress for 2 book(s)...');
|
||||
expect(bookService.resetProgress).toHaveBeenCalledWith([5, 6], ResetProgressTypes.BOOKLORE);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'Booklore reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message when Booklore progress reset fails', () => {
|
||||
const selectedBooks = new Set([1]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {message: 'Reset failed'} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[1].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Reset failed',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog when resetting KOReader progress', () => {
|
||||
const selectedBooks = new Set([7, 8]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
items[2].command!({} as any);
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain('2 book(s)');
|
||||
expect(confirmCall.message).toContain('KOReader');
|
||||
expect(confirmCall.header).toBe('Confirm Reset');
|
||||
});
|
||||
|
||||
it('should reset KOReader progress on confirmation accept', () => {
|
||||
const selectedBooks = new Set([9]);
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(of([]));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[2].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(loadingService.show).toHaveBeenCalledWith('Resetting KOReader progress for 1 book(s)...');
|
||||
expect(bookService.resetProgress).toHaveBeenCalledWith([9], ResetProgressTypes.KOREADER);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'KOReader reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message when KOReader progress reset fails', () => {
|
||||
const selectedBooks = new Set([10]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {message: 'KOReader reset failed'} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[2].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'KOReader reset failed',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle API error without message gracefully', () => {
|
||||
const selectedBooks = new Set([1]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
const readStatusItems = items[0].items!;
|
||||
|
||||
readStatusItems[0].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Could not update read status.',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should return only items for granted read permissions', () => {
|
||||
const partialUser: User = {
|
||||
...mockUser,
|
||||
permissions: {
|
||||
...mockUser.permissions,
|
||||
canBulkResetBookReadStatus: true,
|
||||
canBulkResetBookloreReadProgress: false,
|
||||
canBulkResetKoReaderReadProgress: true
|
||||
}
|
||||
} as User;
|
||||
|
||||
const selectedBooks = new Set([1, 2]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, partialUser);
|
||||
|
||||
expect(items).toHaveLength(2);
|
||||
expect(items[0].label).toBe('Update Read Status');
|
||||
expect(items[1].label).toBe('Reset KOReader Progress');
|
||||
});
|
||||
|
||||
it('should not call bookService when confirmation is rejected', () => {
|
||||
const selectedBooks = new Set([1, 2]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
items[1].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.reject?.();
|
||||
|
||||
expect(bookService.resetProgress).not.toHaveBeenCalled();
|
||||
expect(loadingService.show).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {BookNavigationService} from './book-navigation.service';
|
||||
|
||||
describe('BookNavigationService', () => {
|
||||
let service: BookNavigationService;
|
||||
const bookIds = [10, 20, 30, 40];
|
||||
|
||||
beforeEach(() => {
|
||||
service = new BookNavigationService();
|
||||
});
|
||||
|
||||
it('should set and get available book ids', () => {
|
||||
service.setAvailableBookIds(bookIds);
|
||||
expect(service.getAvailableBookIds()).toEqual(bookIds);
|
||||
});
|
||||
|
||||
it('should set navigation context and emit state', async () => {
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state).not.toBeNull();
|
||||
expect(state!.bookIds).toEqual(bookIds);
|
||||
expect(state!.currentIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('should emit null if currentBookId not in bookIds', async () => {
|
||||
service.setNavigationContext(bookIds, 99);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state).toBeNull();
|
||||
});
|
||||
|
||||
it('should determine canNavigatePrevious correctly', () => {
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
expect(service.canNavigatePrevious()).toBe(false);
|
||||
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
expect(service.canNavigatePrevious()).toBe(true);
|
||||
});
|
||||
|
||||
it('should determine canNavigateNext correctly', () => {
|
||||
service.setNavigationContext(bookIds, 40);
|
||||
expect(service.canNavigateNext()).toBe(false);
|
||||
|
||||
service.setNavigationContext(bookIds, 20);
|
||||
expect(service.canNavigateNext()).toBe(true);
|
||||
});
|
||||
|
||||
it('should get previous book id', () => {
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
expect(service.getPreviousBookId()).toBe(20);
|
||||
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
expect(service.getPreviousBookId()).toBeNull();
|
||||
});
|
||||
|
||||
it('should get next book id', () => {
|
||||
service.setNavigationContext(bookIds, 20);
|
||||
expect(service.getNextBookId()).toBe(30);
|
||||
|
||||
service.setNavigationContext(bookIds, 40);
|
||||
expect(service.getNextBookId()).toBeNull();
|
||||
});
|
||||
|
||||
it('should update current book and emit new index', async () => {
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
service.updateCurrentBook(30);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state!.currentIndex).toBe(2);
|
||||
expect(state!.bookIds[state!.currentIndex]).toBe(30);
|
||||
});
|
||||
|
||||
it('should not update current book if id not in list', async () => {
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
service.updateCurrentBook(99);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state!.currentIndex).toBe(0);
|
||||
expect(state!.bookIds[state!.currentIndex]).toBe(10);
|
||||
});
|
||||
|
||||
it('should return current position', () => {
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
expect(service.getCurrentPosition()).toEqual({current: 3, total: 4});
|
||||
});
|
||||
|
||||
it('should return null for current position if no state', () => {
|
||||
expect(service.getCurrentPosition()).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle navigation methods gracefully if state is null', () => {
|
||||
expect(service.canNavigatePrevious()).toBe(false);
|
||||
expect(service.canNavigateNext()).toBe(false);
|
||||
expect(service.getPreviousBookId()).toBeNull();
|
||||
expect(service.getNextBookId()).toBeNull();
|
||||
|
||||
service.updateCurrentBook(10);
|
||||
expect(service.getCurrentPosition()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {of, throwError} from 'rxjs';
|
||||
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
import {BookStateService} from './book-state.service';
|
||||
import {Book, ReadStatus} from '../model/book.model';
|
||||
|
||||
describe('BookPatchService', () => {
|
||||
let service: BookPatchService;
|
||||
let httpMock: any;
|
||||
let bookStateServiceMock: any;
|
||||
|
||||
const mockBooks: Book[] = [
|
||||
{id: 1, bookType: 'PDF', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book,
|
||||
{id: 2, bookType: 'EPUB', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book,
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
httpMock = {
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
};
|
||||
bookStateServiceMock = {
|
||||
getCurrentBookState: vi.fn(),
|
||||
updateBookState: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookPatchService,
|
||||
{provide: HttpClient, useValue: httpMock},
|
||||
{provide: BookStateService, useValue: bookStateServiceMock},
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(BookPatchService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should update book shelves and update state', () => {
|
||||
const updatedBooks = [{...mockBooks[0], id: 1, libraryName: 'Updated'}];
|
||||
httpMock.post.mockReturnValue(of(updatedBooks));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])).subscribe(result => {
|
||||
expect(result).toEqual(updatedBooks);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
|
||||
books: expect.arrayContaining([expect.objectContaining({id: 1, libraryName: 'Updated'})])
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
it('should save PDF progress', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
service.savePdfProgress(1, 10, 0.5).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 1,
|
||||
pdfProgress: {page: 10, percentage: 0.5}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should save EPUB progress', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
service.saveEpubProgress(2, 'cfi123', 0.8).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 2,
|
||||
epubProgress: {cfi: 'cfi123', percentage: 0.8}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should save CBX progress', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
service.saveCbxProgress(3, 5, 0.2).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 3,
|
||||
cbxProgress: {page: 5, percentage: 0.2}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should update date finished and update state', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateDateFinished(1, '2023-01-01').subscribe(() => {
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
|
||||
books: expect.arrayContaining([expect.objectContaining({id: 1, dateFinished: '2023-01-01'})])
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset progress and update state', () => {
|
||||
const responses = [{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: 'now', dateFinished: undefined}];
|
||||
httpMock.post.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.resetProgress([1], 'BOOKLORE').subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/reset-progress'),
|
||||
[1],
|
||||
{params: expect.any(HttpParams)}
|
||||
);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should update book read status and update state', () => {
|
||||
const responses = [{bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: 'now', dateFinished: '2023-01-01'}];
|
||||
httpMock.post.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateBookReadStatus([2], ReadStatus.READING).subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/status'),
|
||||
{bookIds: [2], status: ReadStatus.READING}
|
||||
);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset personal rating and update state', () => {
|
||||
const responses = [{bookId: 1, personalRating: null}];
|
||||
httpMock.post.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.resetPersonalRating([1]).subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/reset-personal-rating'), [1]);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should update personal rating and update state', () => {
|
||||
const responses = [{bookId: 2, personalRating: 5}];
|
||||
httpMock.put.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updatePersonalRating([2], 5).subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.put).toHaveBeenCalledWith(expect.stringContaining('/personal-rating'), {ids: [2], rating: 5});
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should update last read time in state', () => {
|
||||
const now = new Date().toISOString();
|
||||
vi.useFakeTimers().setSystemTime(new Date(now));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateLastReadTime(1);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
|
||||
books: expect.arrayContaining([expect.objectContaining({id: 1, lastReadTime: now})])
|
||||
}));
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should handle errors from http.post gracefully', () => {
|
||||
httpMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.savePdfProgress(1, 1, 1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
import {BookState} from '../model/state/book-state.model';
|
||||
|
||||
@Injectable({
|
||||
@@ -22,13 +22,6 @@ export class BookStateService {
|
||||
this.bookStateSubject.next(state);
|
||||
}
|
||||
|
||||
updatePartialBookState(partialState: Partial<BookState>): void {
|
||||
this.bookStateSubject.next({
|
||||
...this.bookStateSubject.value,
|
||||
...partialState
|
||||
});
|
||||
}
|
||||
|
||||
resetBookState(): void {
|
||||
this.bookStateSubject.next({
|
||||
books: null,
|
||||
|
||||
@@ -0,0 +1,537 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {firstValueFrom, of, throwError} from 'rxjs';
|
||||
import {BookService} from './book.service';
|
||||
import {BookStateService} from './book-state.service';
|
||||
import {BookSocketService} from './book-socket.service';
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {AdditionalFileType, Book, BookMetadata, ReadStatus} from '../model/book.model';
|
||||
import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model';
|
||||
|
||||
describe('BookService', () => {
|
||||
let service: BookService;
|
||||
let httpMock: any;
|
||||
let messageServiceMock: any;
|
||||
let authServiceMock: any;
|
||||
let fileDownloadServiceMock: any;
|
||||
let routerMock: any;
|
||||
let bookStateServiceMock: any;
|
||||
let bookSocketServiceMock: any;
|
||||
let bookPatchServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
messageServiceMock = {add: vi.fn()};
|
||||
authServiceMock = {token$: of('token')};
|
||||
fileDownloadServiceMock = {downloadFile: vi.fn()};
|
||||
routerMock = {navigate: vi.fn()};
|
||||
bookStateServiceMock = {
|
||||
bookState$: of({books: [{id: 1, bookType: 'PDF', shelves: [], metadata: {seriesName: 'S'}}], loaded: true, error: null}),
|
||||
getCurrentBookState: vi.fn(),
|
||||
updateBookState: vi.fn(),
|
||||
resetBookState: vi.fn()
|
||||
};
|
||||
bookSocketServiceMock = {
|
||||
handleNewlyCreatedBook: vi.fn(),
|
||||
handleRemovedBookIds: vi.fn(),
|
||||
handleBookUpdate: vi.fn(),
|
||||
handleMultipleBookUpdates: vi.fn(),
|
||||
handleBookMetadataUpdate: vi.fn(),
|
||||
handleMultipleBookCoverPatches: vi.fn()
|
||||
};
|
||||
bookPatchServiceMock = {
|
||||
updateBookShelves: vi.fn(),
|
||||
updateLastReadTime: vi.fn(),
|
||||
savePdfProgress: vi.fn(),
|
||||
saveEpubProgress: vi.fn(),
|
||||
saveCbxProgress: vi.fn(),
|
||||
updateDateFinished: vi.fn(),
|
||||
resetProgress: vi.fn(),
|
||||
updateBookReadStatus: vi.fn(),
|
||||
resetPersonalRating: vi.fn(),
|
||||
updatePersonalRating: vi.fn()
|
||||
};
|
||||
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [
|
||||
{id: 1, bookType: 'PDF', shelves: [{id: 10}], metadata: {seriesName: 'S'}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file.pdf'},
|
||||
{id: 2, bookType: 'EPUB', shelves: [], metadata: {}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file2.epub'}
|
||||
],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookService,
|
||||
{provide: HttpClient, useValue: httpMock},
|
||||
{provide: MessageService, useValue: messageServiceMock},
|
||||
{provide: AuthService, useValue: authServiceMock},
|
||||
{provide: FileDownloadService, useValue: fileDownloadServiceMock},
|
||||
{provide: Router, useValue: routerMock},
|
||||
{provide: BookStateService, useValue: bookStateServiceMock},
|
||||
{provide: BookSocketService, useValue: bookSocketServiceMock},
|
||||
{provide: BookPatchService, useValue: bookPatchServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(BookService));
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
it('should get current book state', () => {
|
||||
expect(service.getCurrentBookState()).toEqual(bookStateServiceMock.getCurrentBookState());
|
||||
});
|
||||
|
||||
it('should fetch books and update state', async () => {
|
||||
const books = [{id: 1}];
|
||||
httpMock.get.mockReturnValue(of(books));
|
||||
await firstValueFrom(service['fetchBooks']());
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books,
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle fetchBooks error', async () => {
|
||||
httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: false, error: null});
|
||||
await expect(firstValueFrom(service['fetchBooks']())).rejects.toBeTruthy();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: [],
|
||||
loaded: true,
|
||||
error: 'fail'
|
||||
});
|
||||
});
|
||||
|
||||
it('should refreshBooks and update state', () => {
|
||||
httpMock.get.mockReturnValue(of([{id: 1}]));
|
||||
service.refreshBooks();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: [{id: 1}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle refreshBooks error', () => {
|
||||
httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
service.refreshBooks();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: null,
|
||||
loaded: true,
|
||||
error: 'fail'
|
||||
});
|
||||
});
|
||||
|
||||
it('should remove books by library id', () => {
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, libraryId: 2}, {id: 2, libraryId: 3}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
service.removeBooksByLibraryId(2);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: [{id: 2, libraryId: 3}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
});
|
||||
|
||||
it('should remove books from shelf', () => {
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, shelves: [{id: 10}, {id: 20}]}, {id: 2, shelves: [{id: 20}]}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
service.removeBooksFromShelf(20);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Book Retrieval', () => {
|
||||
it('should get book by id from state', () => {
|
||||
expect(service.getBookByIdFromState(1)).toEqual(expect.objectContaining({id: 1}));
|
||||
expect(service.getBookByIdFromState(999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get books by ids from state', () => {
|
||||
expect(service.getBooksByIdsFromState([1, 2])).toHaveLength(2);
|
||||
expect(service.getBooksByIdsFromState([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('should get book by id from API', async () => {
|
||||
httpMock.get.mockReturnValue(of({id: 1}));
|
||||
const result = await firstValueFrom(service.getBookByIdFromAPI(1, true));
|
||||
expect(result).toEqual({id: 1});
|
||||
});
|
||||
|
||||
it('should get books in series', async () => {
|
||||
const result = await firstValueFrom(service.getBooksInSeries(1));
|
||||
expect(result).toEqual([expect.objectContaining({id: 1})]);
|
||||
});
|
||||
|
||||
it('should get book recommendations', async () => {
|
||||
httpMock.get.mockReturnValue(of([{id: 1}]));
|
||||
const result = await firstValueFrom(service.getBookRecommendations(1));
|
||||
expect(result).toEqual([{id: 1}]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Book Operations', () => {
|
||||
it('should delete books and update state', async () => {
|
||||
httpMock.delete.mockReturnValue(of({failedFileDeletions: []}));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1}, {id: 2}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
await firstValueFrom(service.deleteBooks(new Set([1])));
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('should show warning if some files could not be deleted', async () => {
|
||||
httpMock.delete.mockReturnValue(of({failedFileDeletions: ['file.pdf']}));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, fileName: 'file.pdf'}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
await firstValueFrom(service.deleteBooks(new Set([1])));
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'warn'}));
|
||||
});
|
||||
|
||||
it('should handle deleteBooks error', async () => {
|
||||
httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||
await expect(firstValueFrom(service.deleteBooks(new Set([1])))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should update book shelves', async () => {
|
||||
bookPatchServiceMock.updateBookShelves.mockReturnValue(of([{id: 1}]));
|
||||
const result = await firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])));
|
||||
expect(result).toEqual([{id: 1}]);
|
||||
});
|
||||
|
||||
it('should handle updateBookShelves error', async () => {
|
||||
bookPatchServiceMock.updateBookShelves.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
await expect(firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])))).rejects.toBeTruthy();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Reading & Viewer Settings', () => {
|
||||
it('should navigate to correct reader and update last read time', () => {
|
||||
service.readBook(1, 'ngx');
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1']);
|
||||
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should not navigate if book not found', () => {
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null});
|
||||
service.readBook(999, 'ngx');
|
||||
expect(routerMock.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should get book setting', async () => {
|
||||
httpMock.get.mockReturnValue(of({fontSize: 12}));
|
||||
const result = await firstValueFrom(service.getBookSetting(1));
|
||||
expect(result).toEqual({fontSize: 12});
|
||||
});
|
||||
|
||||
it('should update viewer setting', async () => {
|
||||
httpMock.put.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.updateViewerSetting({fontSize: 12}, 1));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('File Operations', () => {
|
||||
it('should get file content', async () => {
|
||||
httpMock.get.mockReturnValue(of(new Blob(['abc'])));
|
||||
const result = await firstValueFrom(service.getFileContent(1));
|
||||
expect(result).toBeInstanceOf(Blob);
|
||||
});
|
||||
|
||||
it('should download file', () => {
|
||||
const book = {id: 1, fileName: 'file.pdf'};
|
||||
service.downloadFile(book as Book);
|
||||
expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should delete additional file and update state', async () => {
|
||||
httpMock.delete.mockReturnValue(of(void 0));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, alternativeFormats: [{id: 2}], supplementaryFiles: [{id: 3}]}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
await firstValueFrom(service.deleteAdditionalFile(1, 2));
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('should handle deleteAdditionalFile error', async () => {
|
||||
httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||
await expect(firstValueFrom(service.deleteAdditionalFile(1, 2))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should upload additional file and update state', async () => {
|
||||
httpMock.post.mockReturnValue(of({id: 2}));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, alternativeFormats: [], supplementaryFiles: []}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
const file = new File(['abc'], 'file.txt');
|
||||
await firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT));
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('should handle uploadAdditionalFile error', async () => {
|
||||
httpMock.post.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||
const file = new File(['abc'], 'file.txt');
|
||||
await expect(firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should download additional file', () => {
|
||||
const book = {id: 1, alternativeFormats: [{id: 2, fileName: 'f.txt'}]};
|
||||
service.downloadAdditionalFile(book as Book, 2);
|
||||
expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Progress & Status Tracking', () => {
|
||||
it('should update last read time', () => {
|
||||
service.updateLastReadTime(1);
|
||||
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should save pdf progress', async () => {
|
||||
bookPatchServiceMock.savePdfProgress.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.savePdfProgress(1, 2, 0.5));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should save epub progress', async () => {
|
||||
bookPatchServiceMock.saveEpubProgress.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.saveEpubProgress(1, 'cfi', 0.5));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should save cbx progress', async () => {
|
||||
bookPatchServiceMock.saveCbxProgress.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.saveCbxProgress(1, 2, 0.5));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should update date finished', async () => {
|
||||
bookPatchServiceMock.updateDateFinished.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.updateDateFinished(1, '2020-01-01'));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should reset progress', async () => {
|
||||
bookPatchServiceMock.resetProgress.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]));
|
||||
const result = await firstValueFrom(service.resetProgress([1], 'BOOKLORE'));
|
||||
expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]);
|
||||
});
|
||||
|
||||
it('should update book read status', async () => {
|
||||
bookPatchServiceMock.updateBookReadStatus.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]));
|
||||
const result = await firstValueFrom(service.updateBookReadStatus([1], ReadStatus.READ));
|
||||
expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Personal Rating', () => {
|
||||
it('should reset personal rating', async () => {
|
||||
bookPatchServiceMock.resetPersonalRating.mockReturnValue(of([{bookId: 1}]));
|
||||
const result = await firstValueFrom(service.resetPersonalRating([1]));
|
||||
expect(result).toEqual([{bookId: 1}]);
|
||||
});
|
||||
|
||||
it('should update personal rating', async () => {
|
||||
bookPatchServiceMock.updatePersonalRating.mockReturnValue(of([{bookId: 1, personalRating: 5}]));
|
||||
const result = await firstValueFrom(service.updatePersonalRating([1], 5));
|
||||
expect(result).toEqual([{bookId: 1, personalRating: 5}]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Metadata Operations', () => {
|
||||
it('should fetch book metadata', async () => {
|
||||
httpMock.post.mockReturnValue(of([{bookId: 1}]));
|
||||
const req: FetchMetadataRequest = {
|
||||
bookId: 1,
|
||||
providers: [],
|
||||
title: '',
|
||||
author: '',
|
||||
isbn: ''
|
||||
};
|
||||
const result = await firstValueFrom(service.fetchBookMetadata(1, req));
|
||||
expect(result).toEqual([{bookId: 1}]);
|
||||
});
|
||||
|
||||
it('should update book metadata', async () => {
|
||||
httpMock.put.mockReturnValue(of({bookId: 1}));
|
||||
service.handleBookMetadataUpdate = vi.fn();
|
||||
const result = await firstValueFrom(service.updateBookMetadata(1, {} as any, true));
|
||||
expect(result).toEqual({bookId: 1});
|
||||
expect(service.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1});
|
||||
});
|
||||
|
||||
it('should update books metadata', async () => {
|
||||
httpMock.put.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.updateBooksMetadata({} as any));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should toggle all lock', async () => {
|
||||
httpMock.put.mockReturnValue(of([{bookId: 1}]));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, metadata: {bookId: 1}}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
const result = await firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'));
|
||||
expect(result).toBeUndefined();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle toggle all lock error', async () => {
|
||||
httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
await expect(firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'))).rejects.toBeTruthy();
|
||||
});
|
||||
|
||||
it('should toggle field locks', async () => {
|
||||
httpMock.put.mockReturnValue(of(void 0));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, metadata: {}}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
const result = await firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}));
|
||||
expect(result).toBeUndefined();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle toggle field locks error', async () => {
|
||||
httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
await expect(firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should consolidate metadata', async () => {
|
||||
httpMock.post.mockReturnValue(of({}));
|
||||
service.refreshBooks = vi.fn();
|
||||
await firstValueFrom(service.consolidateMetadata('authors', ['a'], ['b']));
|
||||
expect(service.refreshBooks).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should delete metadata', async () => {
|
||||
httpMock.post.mockReturnValue(of({}));
|
||||
service.refreshBooks = vi.fn();
|
||||
await firstValueFrom(service.deleteMetadata('authors', ['a']));
|
||||
expect(service.refreshBooks).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Cover Operations', () => {
|
||||
it('should get upload cover url', () => {
|
||||
expect(service.getUploadCoverUrl(1)).toContain('/1/metadata/cover/upload');
|
||||
});
|
||||
|
||||
it('should upload cover from url and handleBookMetadataUpdate', async () => {
|
||||
httpMock.post.mockReturnValue(of({bookId: 1}));
|
||||
service.handleBookMetadataUpdate = vi.fn();
|
||||
const result = await firstValueFrom(service.uploadCoverFromUrl(1, 'url'));
|
||||
expect(result).toEqual({bookId: 1});
|
||||
expect(service.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1});
|
||||
});
|
||||
|
||||
it('should regenerate covers', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.regenerateCovers());
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should regenerate cover', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.regenerateCover(1));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should generate custom cover', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.generateCustomCover(1));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should regenerate covers for books', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.regenerateCoversForBooks([1, 2]));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should bulk upload cover', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const file = new File(['abc'], 'cover.jpg');
|
||||
const result = await firstValueFrom(service.bulkUploadCover([1, 2], file));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Websocket Handlers', () => {
|
||||
it('should handle newly created book', () => {
|
||||
const book = {id: 1};
|
||||
service.handleNewlyCreatedBook(book as Book);
|
||||
expect(bookSocketServiceMock.handleNewlyCreatedBook).toHaveBeenCalledWith(book);
|
||||
});
|
||||
|
||||
it('should handle removed book ids', () => {
|
||||
service.handleRemovedBookIds([1, 2]);
|
||||
expect(bookSocketServiceMock.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]);
|
||||
});
|
||||
|
||||
it('should handle book update', () => {
|
||||
const book = {id: 1};
|
||||
service.handleBookUpdate(book as Book);
|
||||
expect(bookSocketServiceMock.handleBookUpdate).toHaveBeenCalledWith(book);
|
||||
});
|
||||
|
||||
it('should handle multiple book updates', () => {
|
||||
const books = [{id: 1}, {id: 2}];
|
||||
service.handleMultipleBookUpdates(books as Book[]);
|
||||
expect(bookSocketServiceMock.handleMultipleBookUpdates).toHaveBeenCalledWith(books);
|
||||
});
|
||||
|
||||
it('should handle book metadata update', () => {
|
||||
service.handleBookMetadataUpdate(1, {bookId: 1} as BookMetadata);
|
||||
expect(bookSocketServiceMock.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1});
|
||||
});
|
||||
|
||||
it('should handle multiple book cover patches', () => {
|
||||
const patches = [{id: 1, coverUpdatedOn: 'now'}];
|
||||
service.handleMultipleBookCoverPatches(patches);
|
||||
expect(bookSocketServiceMock.handleMultipleBookCoverPatches).toHaveBeenCalledWith(patches);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {of, throwError} from 'rxjs';
|
||||
|
||||
import {CbxReaderService} from './cbx-reader.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
describe('CbxReaderService', () => {
|
||||
let service: CbxReaderService;
|
||||
let httpClientMock: any;
|
||||
let authServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn()
|
||||
};
|
||||
|
||||
authServiceMock = {
|
||||
getOidcAccessToken: vi.fn(),
|
||||
getInternalAccessToken: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CbxReaderService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: AuthService, useValue: authServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(CbxReaderService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should get available pages with token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('abc123');
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
httpClientMock.get.mockReturnValue(of([1, 2, 3]));
|
||||
service.getAvailablePages(42).subscribe(pages => {
|
||||
expect(pages).toEqual([1, 2, 3]);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('token=abc123'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should get available pages without token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
httpClientMock.get.mockReturnValue(of([4, 5]));
|
||||
service.getAvailablePages(99).subscribe(pages => {
|
||||
expect(pages).toEqual([4, 5]);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.not.stringContaining('token='));
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle error when getting available pages', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.getAvailablePages(1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should return correct page image url with oidc token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
const url = service.getPageImageUrl(5, 7);
|
||||
expect(url).toContain('/api/v1/media/book/5/cbx/pages/7');
|
||||
expect(url).toContain('token=tok');
|
||||
});
|
||||
|
||||
it('should return correct page image url with internal token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue('inttok');
|
||||
const url = service.getPageImageUrl(8, 2);
|
||||
expect(url).toContain('/api/v1/media/book/8/cbx/pages/2');
|
||||
expect(url).toContain('token=inttok');
|
||||
});
|
||||
|
||||
it('should return correct page image url without token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
const url = service.getPageImageUrl(3, 1);
|
||||
expect(url).toContain('/api/v1/media/book/3/cbx/pages/1');
|
||||
expect(url).not.toContain('token=');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {Router} from '@angular/router';
|
||||
import {LibraryService} from './library.service';
|
||||
import {ShelfService} from './shelf.service';
|
||||
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
|
||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||
import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {UserService} from "../../settings/user-management/user.service";
|
||||
import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {LibraryShelfMenuService} from './library-shelf-menu.service';
|
||||
import {Library} from '../model/library.model';
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
describe('LibraryShelfMenuService', () => {
|
||||
let service: LibraryShelfMenuService;
|
||||
let confirmationService: any;
|
||||
let messageService: any;
|
||||
let libraryService: any;
|
||||
let shelfService: any;
|
||||
let taskHelperService: any;
|
||||
let router: any;
|
||||
let dialogLauncherService: any;
|
||||
let magicShelfService: any;
|
||||
let userService: any;
|
||||
let loadingService: any;
|
||||
|
||||
const mockLibrary: Library = {id: 1, name: 'Lib1'} as Library;
|
||||
const mockShelf: Shelf = {id: 2, name: 'Shelf1'} as Shelf;
|
||||
const mockMagicShelf: MagicShelf = {id: 3, name: 'Magic1', isPublic: false} as MagicShelf;
|
||||
|
||||
beforeEach(() => {
|
||||
confirmationService = {confirm: vi.fn()};
|
||||
messageService = {add: vi.fn()};
|
||||
libraryService = {
|
||||
refreshLibrary: vi.fn(),
|
||||
deleteLibrary: vi.fn()
|
||||
};
|
||||
shelfService = {
|
||||
deleteShelf: vi.fn()
|
||||
};
|
||||
taskHelperService = {
|
||||
refreshMetadataTask: vi.fn()
|
||||
};
|
||||
router = {navigate: vi.fn()};
|
||||
dialogLauncherService = {
|
||||
openLibraryEditDialog: vi.fn(),
|
||||
openLibraryMetadataFetchDialog: vi.fn(),
|
||||
openShelfEditDialog: vi.fn(),
|
||||
openMagicShelfEditDialog: vi.fn()
|
||||
};
|
||||
magicShelfService = {
|
||||
deleteShelf: vi.fn()
|
||||
};
|
||||
userService = {
|
||||
getCurrentUser: vi.fn()
|
||||
};
|
||||
loadingService = {
|
||||
show: vi.fn().mockReturnValue('loader-id'),
|
||||
hide: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
LibraryShelfMenuService,
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: LibraryService, useValue: libraryService},
|
||||
{provide: ShelfService, useValue: shelfService},
|
||||
{provide: TaskHelperService, useValue: taskHelperService},
|
||||
{provide: Router, useValue: router},
|
||||
{provide: DialogLauncherService, useValue: dialogLauncherService},
|
||||
{provide: MagicShelfService, useValue: magicShelfService},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: LoadingService, useValue: loadingService}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(LibraryShelfMenuService));
|
||||
});
|
||||
|
||||
describe('initializeLibraryMenuItems', () => {
|
||||
it('should provide all menu items for a library', () => {
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
expect(items.length).toBe(1);
|
||||
const options = items[0].items!;
|
||||
expect(options.some(i => i.label === 'Edit Library')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Re-scan Library')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Custom Fetch Metadata')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Auto Fetch Metadata')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Delete Library')).toBe(true);
|
||||
});
|
||||
|
||||
it('should call openLibraryEditDialog when Edit Library is clicked', () => {
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Library');
|
||||
edit!.command!({});
|
||||
expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(mockLibrary.id);
|
||||
});
|
||||
|
||||
it('should call openLibraryMetadataFetchDialog when Custom Fetch Metadata is clicked', () => {
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const fetch = items[0].items!.find(i => i.label === 'Custom Fetch Metadata');
|
||||
fetch!.command!({});
|
||||
expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(mockLibrary.id);
|
||||
});
|
||||
|
||||
it('should call refreshMetadataTask when Auto Fetch Metadata is clicked', () => {
|
||||
taskHelperService.refreshMetadataTask.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const auto = items[0].items!.find(i => i.label === 'Auto Fetch Metadata');
|
||||
auto!.command!({});
|
||||
expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({
|
||||
refreshType: MetadataRefreshType.LIBRARY,
|
||||
libraryId: mockLibrary.id
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Re-scan Library', () => {
|
||||
libraryService.refreshLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
|
||||
rescan!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockLibrary.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should refresh library and show success message on accept', () => {
|
||||
libraryService.refreshLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
|
||||
rescan!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(libraryService.refreshLibrary).toHaveBeenCalledWith(mockLibrary.id);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Library refresh scheduled'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message if refreshLibrary fails', () => {
|
||||
libraryService.refreshLibrary.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
|
||||
rescan!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to refresh library'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Delete Library', () => {
|
||||
libraryService.deleteLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Library');
|
||||
del!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockLibrary.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should delete library, navigate, and show success message on accept', () => {
|
||||
libraryService.deleteLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Library');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(loadingService.show).toHaveBeenCalledWith(expect.stringContaining(mockLibrary.name));
|
||||
expect(libraryService.deleteLibrary).toHaveBeenCalledWith(mockLibrary.id);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Library was deleted'
|
||||
});
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
});
|
||||
|
||||
it('should show error message if deleteLibrary fails', () => {
|
||||
libraryService.deleteLibrary.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Library');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete library'
|
||||
});
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeShelfMenuItems', () => {
|
||||
it('should provide all menu items for a shelf', () => {
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
expect(items.length).toBe(1);
|
||||
const options = items[0].items!;
|
||||
expect(options.some(i => i.label === 'Edit Shelf')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Delete Shelf')).toBe(true);
|
||||
});
|
||||
|
||||
it('should call openShelfEditDialog when Edit Shelf is clicked', () => {
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Shelf');
|
||||
edit!.command!({});
|
||||
expect(dialogLauncherService.openShelfEditDialog).toHaveBeenCalledWith(mockShelf.id);
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Delete Shelf', () => {
|
||||
shelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
|
||||
del!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockShelf.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should delete shelf, navigate, and show success message on accept', () => {
|
||||
shelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(shelfService.deleteShelf).toHaveBeenCalledWith(mockShelf.id);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Shelf was deleted'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message if deleteShelf fails', () => {
|
||||
shelfService.deleteShelf.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete shelf'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeMagicShelfMenuItems', () => {
|
||||
it('should provide all menu items for a magic shelf', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
expect(items.length).toBe(1);
|
||||
const options = items[0].items!;
|
||||
expect(options.some(i => i.label === 'Edit Magic Shelf')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Delete Magic Shelf')).toBe(true);
|
||||
});
|
||||
|
||||
it('should call openMagicShelfEditDialog when Edit Magic Shelf is clicked', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
|
||||
edit!.command!({});
|
||||
expect(dialogLauncherService.openMagicShelfEditDialog).toHaveBeenCalledWith(mockMagicShelf.id);
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Delete Magic Shelf', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
magicShelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
del!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockMagicShelf.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should delete magic shelf, navigate, and show success message on accept', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
magicShelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(magicShelfService.deleteShelf).toHaveBeenCalledWith(mockMagicShelf.id);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Magic shelf was deleted'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message if deleteMagicShelf fails', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
magicShelfService.deleteShelf.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete shelf'
|
||||
});
|
||||
});
|
||||
|
||||
it('should disable options for public shelf if not admin', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: false}});
|
||||
const publicMagicShelf = {...mockMagicShelf, isPublic: true};
|
||||
const items = service.initializeMagicShelfMenuItems(publicMagicShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
expect(edit!.disabled).toBe(true);
|
||||
expect(del!.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('should not disable options for public shelf if admin', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
const publicMagicShelf = {...mockMagicShelf, isPublic: true};
|
||||
const items = service.initializeMagicShelfMenuItems(publicMagicShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
expect(edit!.disabled).toBe(false);
|
||||
expect(del!.disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {firstValueFrom, of, throwError} from 'rxjs';
|
||||
|
||||
import {LibraryService} from './library.service';
|
||||
import {BookService} from './book.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {Library} from '../model/library.model';
|
||||
|
||||
describe('LibraryService', () => {
|
||||
let service: LibraryService;
|
||||
let httpClientMock: any;
|
||||
let bookServiceMock: any;
|
||||
let authServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
|
||||
bookServiceMock = {
|
||||
removeBooksByLibraryId: vi.fn(),
|
||||
bookState$: of({
|
||||
books: [
|
||||
{id: 1, libraryId: 10},
|
||||
{id: 2, libraryId: 20},
|
||||
{id: 3, libraryId: 10},
|
||||
{id: 4}
|
||||
]
|
||||
})
|
||||
};
|
||||
|
||||
authServiceMock = {
|
||||
token$: of('token')
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
LibraryService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: BookService, useValue: bookServiceMock},
|
||||
{provide: AuthService, useValue: authServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(LibraryService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should fetch libraries and update state', () => {
|
||||
const libraries: Library[] = [{id: 1, name: 'LibA', icon: 'icon', watch: true, paths: []}];
|
||||
httpClientMock.get.mockReturnValue(of(libraries));
|
||||
service['fetchLibraries']().subscribe(result => {
|
||||
expect(result).toEqual(libraries);
|
||||
expect(service['libraryStateSubject'].value.libraries).toEqual(libraries);
|
||||
expect(service['libraryStateSubject'].value.loaded).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle fetch libraries error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service['libraryStateSubject'].next({libraries: null, loaded: false, error: null});
|
||||
service['fetchLibraries']().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(service['libraryStateSubject'].value.error).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should create a library and update state', () => {
|
||||
const library: Library = {id: 2, name: 'LibB', icon: 'icon', watch: true, paths: []};
|
||||
httpClientMock.post.mockReturnValue(of(library));
|
||||
service['libraryStateSubject'].next({libraries: [], loaded: true, error: null});
|
||||
service.createLibrary(library).subscribe(result => {
|
||||
expect(result).toEqual(library);
|
||||
expect(service['libraryStateSubject'].value.libraries).toContain(library);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update a library and update state', () => {
|
||||
const library: Library = {id: 3, name: 'LibC', icon: 'icon', watch: true, paths: []};
|
||||
httpClientMock.put.mockReturnValue(of({...library, name: 'LibC2'}));
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
service.updateLibrary({...library, name: 'LibC2'}, 3).subscribe(result => {
|
||||
expect(result.name).toBe('LibC2');
|
||||
expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 3)?.name).toBe('LibC2');
|
||||
});
|
||||
});
|
||||
|
||||
it('should delete a library and update state', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
const library: Library = {id: 4, name: 'LibD', icon: 'icon', watch: true, paths: []};
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
service.deleteLibrary(4).subscribe(() => {
|
||||
expect(service['libraryStateSubject'].value.libraries).toEqual([]);
|
||||
expect(bookServiceMock.removeBooksByLibraryId).toHaveBeenCalledWith(4);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle delete library error', () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
|
||||
service['libraryStateSubject'].next({libraries: [{id: 5, name: 'LibE', icon: 'icon', watch: true, paths: []}], loaded: true, error: null});
|
||||
service.deleteLibrary(5).subscribe({
|
||||
error: () => {
|
||||
expect(service['libraryStateSubject'].value.error).toBe('delete error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should refresh a library and handle error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('refresh error')));
|
||||
service['libraryStateSubject'].next({libraries: [{id: 6, name: 'LibF', icon: 'icon', watch: true, paths: []}], loaded: true, error: null});
|
||||
service.refreshLibrary(6).subscribe({
|
||||
error: () => {
|
||||
expect(service['libraryStateSubject'].value.error).toBe('refresh error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should update library file naming pattern', () => {
|
||||
const library: Library = {id: 7, name: 'LibG', icon: 'icon', watch: true, paths: [], fileNamingPattern: 'old'};
|
||||
const updatedLibrary = {...library, fileNamingPattern: 'new'};
|
||||
httpClientMock.patch.mockReturnValue(of(updatedLibrary));
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
service.updateLibraryFileNamingPattern(7, 'new').subscribe(result => {
|
||||
expect(result.fileNamingPattern).toBe('new');
|
||||
expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 7)?.fileNamingPattern).toBe('new');
|
||||
});
|
||||
});
|
||||
|
||||
it('should check if library exists by name', () => {
|
||||
const library: Library = {id: 8, name: 'LibH', icon: 'icon', watch: true, paths: []};
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
expect(service.doesLibraryExistByName('LibH')).toBe(true);
|
||||
expect(service.doesLibraryExistByName('NonExistent')).toBe(false);
|
||||
});
|
||||
|
||||
it('should find library by id', () => {
|
||||
const library: Library = {id: 9, name: 'LibI', icon: 'icon', watch: true, paths: []};
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
expect(service.findLibraryById(9)).toEqual(library);
|
||||
expect(service.findLibraryById(999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get libraries from state', () => {
|
||||
const libraries: Library[] = [
|
||||
{id: 10, name: 'LibJ', icon: 'icon', watch: true, paths: []}
|
||||
];
|
||||
service['libraryStateSubject'].next({libraries, loaded: true, error: null});
|
||||
expect(service.getLibrariesFromState()).toEqual(libraries);
|
||||
});
|
||||
|
||||
it('should get book count for library', async () => {
|
||||
const count = await firstValueFrom(service.getBookCount(10));
|
||||
expect(count).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -133,7 +133,6 @@ export class LibraryService {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
doesLibraryExistByName(name: string): boolean {
|
||||
return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name);
|
||||
}
|
||||
@@ -146,12 +145,6 @@ export class LibraryService {
|
||||
return this.libraryStateSubject.value.libraries || [];
|
||||
}
|
||||
|
||||
getLibraryPathById(pathId: number): string | undefined {
|
||||
return this.libraryStateSubject.value.libraries
|
||||
?.find(lib => lib.paths.some(p => p.id === pathId))
|
||||
?.paths.find(p => p.id === pathId)?.path;
|
||||
}
|
||||
|
||||
getBookCount(libraryId: number): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {firstValueFrom, of, throwError} from 'rxjs';
|
||||
|
||||
import {MetadataFetchTask, MetadataTaskService} from './metadata-task';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../../shared/model/metadata-batch-progress.model';
|
||||
|
||||
describe('MetadataTaskService', () => {
|
||||
let service: MetadataTaskService;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
post: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
MetadataTaskService,
|
||||
{ provide: HttpClient, useValue: httpClientMock }
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(MetadataTaskService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should get task with proposals', async () => {
|
||||
const task: MetadataFetchTask = {
|
||||
id: 'task1',
|
||||
status: 'IN_PROGRESS',
|
||||
completed: 1,
|
||||
totalBooks: 2,
|
||||
startedAt: '2024-01-01T00:00:00Z',
|
||||
completedAt: null,
|
||||
initiatedBy: 'user1',
|
||||
errorMessage: null,
|
||||
proposals: []
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of({ task }));
|
||||
const result = await firstValueFrom(service.getTaskWithProposals('task1'));
|
||||
expect(result).toEqual(task);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task1`);
|
||||
});
|
||||
|
||||
it('should handle error in getTaskWithProposals', async () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
try {
|
||||
await firstValueFrom(service.getTaskWithProposals('task2'));
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
|
||||
it('should delete a task', async () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
await firstValueFrom(service.deleteTask('task3'));
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task3`);
|
||||
});
|
||||
|
||||
it('should handle error in deleteTask', async () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
|
||||
try {
|
||||
await firstValueFrom(service.deleteTask('task4'));
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('delete error');
|
||||
}
|
||||
});
|
||||
|
||||
it('should update proposal status', async () => {
|
||||
httpClientMock.post.mockReturnValue(of(void 0));
|
||||
await firstValueFrom(service.updateProposalStatus('task5', 123, 'ACCEPTED'));
|
||||
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/metadata/tasks/task5/proposals/123/status`,
|
||||
null,
|
||||
{ params: { status: 'ACCEPTED' } }
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle error in updateProposalStatus', async () => {
|
||||
httpClientMock.post.mockReturnValue(throwError(() => new Error('status error')));
|
||||
try {
|
||||
await firstValueFrom(service.updateProposalStatus('task6', 456, 'REJECTED'));
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('status error');
|
||||
}
|
||||
});
|
||||
|
||||
it('should get active tasks', async () => {
|
||||
const notifications: MetadataBatchProgressNotification[] = [
|
||||
{
|
||||
taskId: 't1',
|
||||
completed: 1,
|
||||
total: 2,
|
||||
message: 'Running',
|
||||
status: MetadataBatchStatus.IN_PROGRESS,
|
||||
review: false
|
||||
}
|
||||
];
|
||||
httpClientMock.get.mockReturnValue(of(notifications));
|
||||
const result = await firstValueFrom(service.getActiveTasks());
|
||||
expect(result).toEqual(notifications);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/active`);
|
||||
});
|
||||
|
||||
it('should handle error in getActiveTasks', async () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('active error')));
|
||||
try {
|
||||
await firstValueFrom(service.getActiveTasks());
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('active error');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
|
||||
import {NewPdfReaderService} from './new-pdf-reader.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
|
||||
describe('NewPdfReaderService', () => {
|
||||
let service: NewPdfReaderService;
|
||||
let authServiceMock: any;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
authServiceMock = {
|
||||
getOidcAccessToken: vi.fn(),
|
||||
getInternalAccessToken: vi.fn()
|
||||
};
|
||||
|
||||
httpClientMock = {
|
||||
get: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
NewPdfReaderService,
|
||||
{provide: AuthService, useValue: authServiceMock},
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(NewPdfReaderService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should append token from OIDC access token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token');
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
|
||||
const url = 'http://test.com/resource';
|
||||
const result = (service as any).appendToken(url);
|
||||
|
||||
expect(result).toContain('token=oidc-token');
|
||||
});
|
||||
|
||||
it('should not append token if both tokens are null', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
|
||||
const url = 'http://test.com/resource';
|
||||
const result = (service as any).appendToken(url);
|
||||
|
||||
expect(result).toBe(url);
|
||||
});
|
||||
|
||||
it('should call http.get with correct URL', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('token123');
|
||||
|
||||
service.getAvailablePages(42);
|
||||
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/pdf/42/pages?token=token123`
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {of, throwError, firstValueFrom} from 'rxjs';
|
||||
|
||||
import {ShelfService} from './shelf.service';
|
||||
import {BookService} from './book.service';
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
|
||||
describe('ShelfService', () => {
|
||||
let service: ShelfService;
|
||||
let httpClientMock: any;
|
||||
let bookServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
|
||||
bookServiceMock = {
|
||||
removeBooksFromShelf: vi.fn(),
|
||||
bookState$: of({
|
||||
books: [
|
||||
{id: 1, shelves: [{id: 10}]},
|
||||
{id: 2, shelves: [{id: 20}]},
|
||||
{id: 3, shelves: []},
|
||||
{id: 4}
|
||||
]
|
||||
})
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ShelfService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: BookService, useValue: bookServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(ShelfService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should fetch shelves and update state', () => {
|
||||
const shelves: Shelf[] = [{id: 1, name: 'A', icon: 'icon'}];
|
||||
httpClientMock.get.mockReturnValue(of(shelves));
|
||||
service['fetchShelves']().subscribe(result => {
|
||||
expect(result).toEqual(shelves);
|
||||
expect(service['shelfStateSubject'].value.shelves).toEqual(shelves);
|
||||
expect(service['shelfStateSubject'].value.loaded).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle fetch shelves error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service['shelfStateSubject'].next({shelves: null, loaded: false, error: null});
|
||||
service['fetchShelves']().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(service['shelfStateSubject'].value.error).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should create a shelf and update state', () => {
|
||||
const shelf: Shelf = {id: 2, name: 'B', icon: 'icon'};
|
||||
httpClientMock.post.mockReturnValue(of(shelf));
|
||||
service['shelfStateSubject'].next({shelves: [], loaded: true, error: null});
|
||||
service.createShelf(shelf).subscribe(result => {
|
||||
expect(result).toEqual(shelf);
|
||||
expect(service['shelfStateSubject'].value.shelves).toContain(shelf);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update a shelf and update state', () => {
|
||||
const shelf: Shelf = {id: 3, name: 'C', icon: 'icon'};
|
||||
httpClientMock.put.mockReturnValue(of({...shelf, name: 'C2'}));
|
||||
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
|
||||
service.updateShelf({...shelf, name: 'C2'}, 3).subscribe(result => {
|
||||
expect(result.name).toBe('C2');
|
||||
expect(service['shelfStateSubject'].value.shelves?.find(s => s.id === 3)?.name).toBe('C2');
|
||||
});
|
||||
});
|
||||
|
||||
it('should delete a shelf and update state', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
const shelf: Shelf = {id: 4, name: 'D', icon: 'icon'};
|
||||
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
|
||||
service.deleteShelf(4).subscribe(() => {
|
||||
expect(service['shelfStateSubject'].value.shelves).toEqual([]);
|
||||
expect(bookServiceMock.removeBooksFromShelf).toHaveBeenCalledWith(4);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle delete shelf error', () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
|
||||
service['shelfStateSubject'].next({shelves: [{id: 5, name: 'E', icon: 'icon'}], loaded: true, error: null});
|
||||
service.deleteShelf(5).subscribe({
|
||||
error: () => {
|
||||
expect(service['shelfStateSubject'].value.error).toBe('delete error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should get shelf by id', () => {
|
||||
const shelf: Shelf = {id: 6, name: 'F', icon: 'icon'};
|
||||
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
|
||||
expect(service.getShelfById(6)).toEqual(shelf);
|
||||
expect(service.getShelfById(999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get book count for shelf', async () => {
|
||||
const count = await firstValueFrom(service.getBookCount(10));
|
||||
expect(count).toBe(1);
|
||||
});
|
||||
|
||||
it('should get unshelved book count', async () => {
|
||||
const count = await firstValueFrom(service.getUnshelvedBookCount());
|
||||
expect(count).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {SortService} from './sort.service';
|
||||
import {Book} from '../model/book.model';
|
||||
import {SortDirection} from '../model/sort.model';
|
||||
|
||||
function makeBook(partial: Partial<Book>): Book {
|
||||
return {
|
||||
id: 1,
|
||||
bookType: "PDF",
|
||||
libraryId: 1,
|
||||
libraryName: "Lib",
|
||||
...partial,
|
||||
} as Book;
|
||||
}
|
||||
|
||||
describe('SortService', () => {
|
||||
let service: SortService;
|
||||
let books: Book[];
|
||||
|
||||
beforeEach(() => {
|
||||
service = new SortService();
|
||||
books = [
|
||||
makeBook({
|
||||
id: 1,
|
||||
fileName: 'Book10.pdf',
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'Book 10',
|
||||
authors: ['Alice'],
|
||||
publishedDate: '2020-01-01',
|
||||
seriesName: 'Series A',
|
||||
seriesNumber: 2,
|
||||
rating: 4.5,
|
||||
reviewCount: 10,
|
||||
},
|
||||
personalRating: 3,
|
||||
addedOn: '2021-01-01T00:00:00Z',
|
||||
lastReadTime: '2022-01-01T00:00:00Z',
|
||||
fileSizeKb: 1000,
|
||||
}),
|
||||
makeBook({
|
||||
id: 2,
|
||||
fileName: 'Book2.pdf',
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Book 2',
|
||||
authors: ['Bob'],
|
||||
publishedDate: '2019-01-01',
|
||||
seriesName: 'Series A',
|
||||
seriesNumber: 1,
|
||||
rating: 4.8,
|
||||
reviewCount: 20,
|
||||
},
|
||||
personalRating: 5,
|
||||
addedOn: '2020-01-01T00:00:00Z',
|
||||
lastReadTime: '2023-01-01T00:00:00Z',
|
||||
fileSizeKb: 2000,
|
||||
}),
|
||||
makeBook({
|
||||
id: 3,
|
||||
fileName: 'Book1.pdf',
|
||||
metadata: {
|
||||
bookId: 3,
|
||||
title: 'Book 1',
|
||||
authors: ['Alice'],
|
||||
publishedDate: '2021-01-01',
|
||||
rating: 4.0,
|
||||
reviewCount: 5,
|
||||
},
|
||||
personalRating: 4,
|
||||
addedOn: '2022-01-01T00:00:00Z',
|
||||
lastReadTime: '2021-01-01T00:00:00Z',
|
||||
fileSizeKb: 500,
|
||||
}),
|
||||
];
|
||||
});
|
||||
|
||||
it('should sort by title (natural order)', () => {
|
||||
const sorted = service.applySort(books, {field: 'title', direction: SortDirection.ASCENDING, label: 'Title'});
|
||||
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']);
|
||||
});
|
||||
|
||||
it('should sort by author', () => {
|
||||
const sorted = service.applySort(books, {field: 'author', direction: SortDirection.ASCENDING, label: 'Author'});
|
||||
expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Alice', 'Alice', 'Bob']);
|
||||
});
|
||||
|
||||
it('should sort by publishedDate descending', () => {
|
||||
const sorted = service.applySort(books, {field: 'publishedDate', direction: SortDirection.DESCENDING, label: 'Published Date'});
|
||||
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 10', 'Book 2']);
|
||||
});
|
||||
|
||||
it('should sort by series (titleSeries)', () => {
|
||||
const sorted = service.applySort(books, {field: 'titleSeries', direction: SortDirection.ASCENDING, label: 'Series'});
|
||||
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']);
|
||||
});
|
||||
|
||||
it('should sort by personalRating descending', () => {
|
||||
const sorted = service.applySort(books, {field: 'personalRating', direction: SortDirection.DESCENDING, label: 'Personal Rating'});
|
||||
expect(sorted.map(b => b.personalRating)).toEqual([5, 4, 3]);
|
||||
});
|
||||
|
||||
it('should sort by fileName (natural order)', () => {
|
||||
const sorted = service.applySort(books, {field: 'fileName', direction: SortDirection.ASCENDING, label: 'File Name'});
|
||||
expect(sorted.map(b => b.fileName)).toEqual(['Book1.pdf', 'Book2.pdf', 'Book10.pdf']);
|
||||
});
|
||||
|
||||
it('should sort by fileSizeKb ascending', () => {
|
||||
const sorted = service.applySort(books, {field: 'fileSizeKb', direction: SortDirection.ASCENDING, label: 'File Size'});
|
||||
expect(sorted.map(b => b.fileSizeKb)).toEqual([500, 1000, 2000]);
|
||||
});
|
||||
|
||||
it('should sort by addedOn descending', () => {
|
||||
const sorted = service.applySort(books, {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'});
|
||||
expect(sorted.map(b => b.addedOn)).toEqual([
|
||||
'2022-01-01T00:00:00Z',
|
||||
'2021-01-01T00:00:00Z',
|
||||
'2020-01-01T00:00:00Z',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle missing extractor gracefully', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {
|
||||
});
|
||||
const sorted = service.applySort(books, {field: 'nonexistent', direction: SortDirection.ASCENDING, label: 'Nonexistent'} as any);
|
||||
expect(sorted).toBe(books);
|
||||
expect(spy).toHaveBeenCalled();
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should return original array if no sort option', () => {
|
||||
const sorted = service.applySort(books, null);
|
||||
expect(sorted).toBe(books);
|
||||
});
|
||||
|
||||
it('should sort by random (order is not predictable)', () => {
|
||||
const sorted = service.applySort(books, {field: 'random', direction: SortDirection.ASCENDING, label: 'Random'});
|
||||
expect(sorted.length).toBe(3);
|
||||
// Can't assert order, but should be a permutation of the input
|
||||
expect(sorted.map(b => b.id).sort()).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/spec",
|
||||
"types": [
|
||||
"node",
|
||||
"jasmine"
|
||||
]
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user