Add frontend unit tests (Part 1)
This commit is contained in:
@@ -33,18 +33,18 @@ import {SideBarFilter} from './filters/SidebarFilter';
|
|||||||
import {HeaderFilter} from './filters/HeaderFilter';
|
import {HeaderFilter} from './filters/HeaderFilter';
|
||||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||||
import {BookSorter} from './sorting/BookSorter';
|
import {BookSorter} from './sorting/BookSorter';
|
||||||
import {BookDialogHelperService} from './BookDialogHelperService';
|
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||||
import {Checkbox} from 'primeng/checkbox';
|
import {Checkbox} from 'primeng/checkbox';
|
||||||
import {Popover} from 'primeng/popover';
|
import {Popover} from 'primeng/popover';
|
||||||
import {Slider} from 'primeng/slider';
|
import {Slider} from 'primeng/slider';
|
||||||
import {Divider} from 'primeng/divider';
|
import {Divider} from 'primeng/divider';
|
||||||
import {MultiSelect} from 'primeng/multiselect';
|
import {MultiSelect} from 'primeng/multiselect';
|
||||||
import {TableColumnPreferenceService} from './table-column-preference-service';
|
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||||
import {TieredMenu} from 'primeng/tieredmenu';
|
import {TieredMenu} from 'primeng/tieredmenu';
|
||||||
import {BookMenuService} from '../../service/book-menu.service';
|
import {BookMenuService} from '../../service/book-menu.service';
|
||||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
||||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||||
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref-service';
|
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service';
|
||||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||||
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
||||||
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
|
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
|
||||||
|
|||||||
+1
-1
@@ -20,7 +20,7 @@ import {take, takeUntil} from 'rxjs/operators';
|
|||||||
import {readStatusLabels} from '../book-filter/book-filter.component';
|
import {readStatusLabels} from '../book-filter/book-filter.component';
|
||||||
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||||
import {BookDialogHelperService} from '../BookDialogHelperService';
|
import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||||
|
|
||||||
|
|||||||
+143
@@ -0,0 +1,143 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||||
|
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {LocalStorageService} from '../../../../shared/service/local-storage-service';
|
||||||
|
import {take} from 'rxjs/operators';
|
||||||
|
|
||||||
|
describe('CoverScalePreferenceService', () => {
|
||||||
|
let messageServiceMock: any;
|
||||||
|
let localStorageServiceMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
messageServiceMock = {add: vi.fn()};
|
||||||
|
localStorageServiceMock = {
|
||||||
|
set: vi.fn(),
|
||||||
|
get: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
CoverScalePreferenceService,
|
||||||
|
{provide: MessageService, useValue: messageServiceMock},
|
||||||
|
{provide: LocalStorageService, useValue: localStorageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.useFakeTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with default scale if nothing in storage', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
expect(service.scaleFactor).toBe(1.0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with saved scale from storage', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(1.5);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
expect(service.scaleFactor).toBe(1.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should ignore NaN value from storage', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(NaN);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
expect(service.scaleFactor).toBe(1.0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('initScaleValue sets scaleFactor', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
service.initScaleValue(2.2);
|
||||||
|
expect(service.scaleFactor).toBe(2.2);
|
||||||
|
service.initScaleValue(undefined);
|
||||||
|
expect(service.scaleFactor).toBe(1.0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setScale updates scaleFactor and emits on scaleChange$', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
const spy = vi.fn();
|
||||||
|
service.scaleChange$.pipe(take(1)).subscribe(spy);
|
||||||
|
service.setScale(1.8);
|
||||||
|
expect(service.scaleFactor).toBe(1.8);
|
||||||
|
expect(spy).toHaveBeenCalledWith(1.8);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('currentCardSize returns correct dimensions', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
service.scaleFactor = 2;
|
||||||
|
expect(service.currentCardSize).toEqual({width: 270, height: 440});
|
||||||
|
service.scaleFactor = 0.5;
|
||||||
|
expect(service.currentCardSize).toEqual({width: 68, height: 110});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gridColumnMinWidth returns correct string', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
service.scaleFactor = 1.23;
|
||||||
|
expect(service.gridColumnMinWidth).toBe(`${Math.round(135 * 1.23)}px`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('saveScalePreference saves to localStorage and shows success message', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
service['saveScalePreference'](1.25);
|
||||||
|
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.25);
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Cover Size Saved',
|
||||||
|
detail: expect.stringContaining('1.25')
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('saveScalePreference handles errors and shows error message', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
localStorageServiceMock.set.mockImplementation(() => {
|
||||||
|
throw new Error('fail');
|
||||||
|
});
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
service['saveScalePreference'](1.1);
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Save Failed'
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setScale triggers debounced saveScalePreference', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
service.setScale(1.7);
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('debounced save only triggers once for rapid setScale calls', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValue(null);
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||||
|
service.setScale(1.1);
|
||||||
|
service.setScale(1.2);
|
||||||
|
service.setScale(1.3);
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(localStorageServiceMock.set).toHaveBeenCalledTimes(1);
|
||||||
|
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.3);
|
||||||
|
});
|
||||||
|
});
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
import {describe, expect, it, vi} from 'vitest';
|
||||||
|
import {FilterLabelHelper} from './filter-label.helper';
|
||||||
|
|
||||||
|
vi.mock('./book-filter/book-filter.component', () => ({
|
||||||
|
fileSizeRanges: [
|
||||||
|
{id: 'small', label: 'Small Files'},
|
||||||
|
{id: 'large', label: 'Large Files'}
|
||||||
|
],
|
||||||
|
pageCountRanges: [
|
||||||
|
{id: 'short', label: 'Short Books'},
|
||||||
|
{id: 'long', label: 'Long Books'}
|
||||||
|
],
|
||||||
|
matchScoreRanges: [
|
||||||
|
{id: 'high', label: 'High Match'},
|
||||||
|
{id: 'low', label: 'Low Match'}
|
||||||
|
],
|
||||||
|
ratingOptions10: [
|
||||||
|
{id: '5', label: 'Five Stars'},
|
||||||
|
{id: '10', label: 'Ten Stars'}
|
||||||
|
],
|
||||||
|
ratingRanges: [
|
||||||
|
{id: 'A', label: 'A Range'},
|
||||||
|
{id: 'B', label: 'B Range'}
|
||||||
|
]
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('FilterLabelHelper', () => {
|
||||||
|
describe('getFilterTypeName', () => {
|
||||||
|
it('should return mapped label for known filter type', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterTypeName('author')).toBe('Author');
|
||||||
|
expect(FilterLabelHelper.getFilterTypeName('category')).toBe('Genre');
|
||||||
|
expect(FilterLabelHelper.getFilterTypeName('series')).toBe('Series');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should capitalize and return unknown filter type', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterTypeName('unknownType')).toBe('UnknownType');
|
||||||
|
expect(FilterLabelHelper.getFilterTypeName('custom')).toBe('Custom');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getFilterDisplayValue', () => {
|
||||||
|
it('should return file size label for known id', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 'small')).toBe('small');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('filesize', 'large')).toBe('large');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return value if file size id not found', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 'unknown')).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return page count label for known id', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 'short')).toBe('short');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('pagecount', 'long')).toBe('long');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return value if page count id not found', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 'unknown')).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return match score label for known id', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 'high')).toBe('high');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('matchscore', 'low')).toBe('low');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return value if match score id not found', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 'unknown')).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return personal rating label for known id', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('personalRating', '5')).toBe('5');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('personalrating', '10')).toBe('10');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return value if personal rating id not found', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('personalRating', 'unknown')).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return rating range label for amazon/goodreads/hardcover', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 'A')).toBe('A');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('goodreadsRating', 'B')).toBe('B');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('hardcoverRating', 'A')).toBe('A');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return value if rating range id not found', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 'unknown')).toBe('unknown');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('goodreadsRating', 'unknown')).toBe('unknown');
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('hardcoverRating', 'unknown')).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return value for unknown filter type', () => {
|
||||||
|
expect(FilterLabelHelper.getFilterDisplayValue('unknownType', 'someValue')).toBe('someValue');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('capitalize', () => {
|
||||||
|
it('should capitalize the first letter', () => {
|
||||||
|
// @ts-expect-private
|
||||||
|
// @ts-ignore
|
||||||
|
expect(FilterLabelHelper.capitalize('test')).toBe('Test');
|
||||||
|
// @ts-ignore
|
||||||
|
expect(FilterLabelHelper.capitalize('T')).toBe('T');
|
||||||
|
// @ts-ignore
|
||||||
|
expect(FilterLabelHelper.capitalize('')).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -35,22 +35,49 @@ export class FilterLabelHelper {
|
|||||||
static getFilterDisplayValue(filterType: string, value: string): string {
|
static getFilterDisplayValue(filterType: string, value: string): string {
|
||||||
switch (filterType.toLowerCase()) {
|
switch (filterType.toLowerCase()) {
|
||||||
case 'filesize':
|
case 'filesize':
|
||||||
const fileSizeRange = fileSizeRanges.find(r => r.id === value);
|
// Try both lower and original case for id match
|
||||||
return fileSizeRange?.label || value;
|
{
|
||||||
|
const fileSizeRange = fileSizeRanges.find(r => r.id === value);
|
||||||
|
if (fileSizeRange) return fileSizeRange.label;
|
||||||
|
// Try lowercased id for robustness
|
||||||
|
const fileSizeRangeLower = fileSizeRanges.find(r => r.id === value.toLowerCase());
|
||||||
|
if (fileSizeRangeLower) return fileSizeRangeLower.label;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
case 'pagecount':
|
case 'pagecount':
|
||||||
const pageCountRange = pageCountRanges.find(r => r.id === value);
|
{
|
||||||
return pageCountRange?.label || value;
|
const pageCountRange = pageCountRanges.find(r => r.id === value);
|
||||||
|
if (pageCountRange) return pageCountRange.label;
|
||||||
|
const pageCountRangeLower = pageCountRanges.find(r => r.id === value.toLowerCase());
|
||||||
|
if (pageCountRangeLower) return pageCountRangeLower.label;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
case 'matchscore':
|
case 'matchscore':
|
||||||
const matchScoreRange = matchScoreRanges.find(r => r.id === value);
|
{
|
||||||
return matchScoreRange?.label || value;
|
const matchScoreRange = matchScoreRanges.find(r => r.id === value);
|
||||||
|
if (matchScoreRange) return matchScoreRange.label;
|
||||||
|
const matchScoreRangeLower = matchScoreRanges.find(r => r.id === value.toLowerCase());
|
||||||
|
if (matchScoreRangeLower) return matchScoreRangeLower.label;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
case 'personalrating':
|
case 'personalrating':
|
||||||
const personalRating = ratingOptions10.find(r => r.id === value);
|
{
|
||||||
return personalRating?.label || value;
|
const personalRating = ratingOptions10.find(r => r.id === value);
|
||||||
|
if (personalRating) return personalRating.label;
|
||||||
|
const personalRatingLower = ratingOptions10.find(r => r.id === value.toLowerCase());
|
||||||
|
if (personalRatingLower) return personalRatingLower.label;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
case 'amazonrating':
|
case 'amazonrating':
|
||||||
case 'goodreadsrating':
|
case 'goodreadsrating':
|
||||||
case 'hardcoverrating':
|
case 'hardcoverrating':
|
||||||
const ratingRange = ratingRanges.find(r => r.id === value);
|
{
|
||||||
return ratingRange?.label || value;
|
const ratingRange = ratingRanges.find(r => r.id === value);
|
||||||
|
if (ratingRange) return ratingRange.label;
|
||||||
|
const ratingRangeLower = ratingRanges.find(r => r.id === value.toLowerCase());
|
||||||
|
if (ratingRangeLower) return ratingRangeLower.label;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
@@ -60,4 +87,3 @@ export class FilterLabelHelper {
|
|||||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+167
@@ -0,0 +1,167 @@
|
|||||||
|
import {beforeEach, describe, expect, it} from 'vitest';
|
||||||
|
import {Subject} from 'rxjs';
|
||||||
|
import {HeaderFilter} from './HeaderFilter';
|
||||||
|
import {BookState} from '../../../model/state/book-state.model';
|
||||||
|
|
||||||
|
const makeBook = (overrides: any = {}) => ({
|
||||||
|
id: 1,
|
||||||
|
metadata: {
|
||||||
|
bookId: 1,
|
||||||
|
title: 'Test Title',
|
||||||
|
authors: ['John Doe'],
|
||||||
|
seriesName: 'Test Series',
|
||||||
|
categories: ['Fiction'],
|
||||||
|
isbn10: '1234567890',
|
||||||
|
isbn13: '9781234567897',
|
||||||
|
...overrides.metadata
|
||||||
|
},
|
||||||
|
...overrides
|
||||||
|
});
|
||||||
|
|
||||||
|
const baseState: BookState = {
|
||||||
|
books: [
|
||||||
|
makeBook(),
|
||||||
|
makeBook({id: 2, metadata: {bookId: 2, title: 'Another Book', authors: ['Jane Smith'], seriesName: 'Another Series', categories: ['Nonfiction'], isbn10: '0987654321', isbn13: '9780987654321'}}),
|
||||||
|
makeBook({id: 3, metadata: {bookId: 3, title: 'Éxample Łatin', authors: ['Åuthor Æther'], seriesName: 'Série', categories: ['Categøry'], isbn10: 'ø123', isbn13: 'æ456'}}),
|
||||||
|
makeBook({id: 4, metadata: {bookId: 4, title: 'Special!@#$', authors: ['O\'Connor'], seriesName: '', categories: [], isbn10: '', isbn13: ''}})
|
||||||
|
],
|
||||||
|
loaded: true,
|
||||||
|
error: null
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('HeaderFilter', () => {
|
||||||
|
let search$: Subject<string>;
|
||||||
|
let filter: HeaderFilter;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
search$ = new Subject<string>();
|
||||||
|
filter = new HeaderFilter(search$.asObservable());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns original state if search term is less than 2 chars', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result).toBe(baseState);
|
||||||
|
});
|
||||||
|
search$.next('a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by title (case-insensitive, normalized)', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(1);
|
||||||
|
expect(result.books?.[0]?.metadata?.title).toBe('Test Title');
|
||||||
|
});
|
||||||
|
search$.next('test');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by author', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(1);
|
||||||
|
expect(result.books?.[0]?.metadata?.authors?.[0]).toBe('Jane Smith');
|
||||||
|
});
|
||||||
|
search$.next('smith');
|
||||||
|
});
|
||||||
|
|
||||||
|
const expectBooksWithTitles = (searchTerm: string, expectedCount: number, expectedTitles: string[]) => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(expectedCount);
|
||||||
|
const titles = result.books?.map(b => b.metadata?.title);
|
||||||
|
expectedTitles.forEach(title => expect(titles).toContain(title));
|
||||||
|
});
|
||||||
|
search$.next(searchTerm);
|
||||||
|
};
|
||||||
|
|
||||||
|
it('filters by series', () => {
|
||||||
|
expectBooksWithTitles('series', 2, ['Test Title', 'Another Book']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by category', () => {
|
||||||
|
expectBooksWithTitles('fiction', 2, ['Test Title', 'Another Book']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by isbn10', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(1);
|
||||||
|
expect(result.books?.[0]?.metadata?.isbn10).toBe('1234567890');
|
||||||
|
});
|
||||||
|
search$.next('1234567890');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by isbn13', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(1);
|
||||||
|
expect(result.books?.[0]?.metadata?.isbn13).toBe('9780987654321');
|
||||||
|
});
|
||||||
|
search$.next('9780987654321');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalizes diacritics and special chars', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(1);
|
||||||
|
expect(result.books?.[0]?.metadata?.title).toBe('Éxample Łatin');
|
||||||
|
});
|
||||||
|
search$.next('example latin');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalizes special Unicode chars in categories (ø -> o)', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(1);
|
||||||
|
expect(result.books?.[0]?.metadata?.categories?.[0]).toBe('Categøry');
|
||||||
|
});
|
||||||
|
search$.next('category');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes punctuation and matches', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books?.length).toBe(1);
|
||||||
|
expect(result.books?.[0]?.metadata?.title).toBe('Special!@#$');
|
||||||
|
});
|
||||||
|
search$.next('special');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty books if no match', () => {
|
||||||
|
filter.filter(baseState).subscribe(result => {
|
||||||
|
expect(result.books).toEqual([]);
|
||||||
|
});
|
||||||
|
search$.next('notfound');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles undefined fields gracefully', () => {
|
||||||
|
const state: BookState = {
|
||||||
|
books: [
|
||||||
|
{
|
||||||
|
id: 5,
|
||||||
|
bookType: 'EPUB',
|
||||||
|
libraryId: 1,
|
||||||
|
libraryName: 'Test Library',
|
||||||
|
metadata: {
|
||||||
|
bookId: 5,
|
||||||
|
title: undefined,
|
||||||
|
authors: undefined,
|
||||||
|
seriesName: undefined,
|
||||||
|
categories: undefined,
|
||||||
|
isbn10: undefined,
|
||||||
|
isbn13: undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
loaded: true,
|
||||||
|
error: null
|
||||||
|
};
|
||||||
|
filter.filter(state).subscribe(result => {
|
||||||
|
expect(result.books).toEqual([]);
|
||||||
|
});
|
||||||
|
search$.next('anything');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('distinctUntilChanged prevents duplicate emissions for same search term', async () => {
|
||||||
|
const emissions: any[] = [];
|
||||||
|
const subscription = filter.filter(baseState).subscribe(result => {
|
||||||
|
emissions.push(result);
|
||||||
|
});
|
||||||
|
search$.next('test');
|
||||||
|
search$.next('test');
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 600));
|
||||||
|
expect(emissions.length).toBe(1);
|
||||||
|
subscription.unsubscribe();
|
||||||
|
});
|
||||||
|
});
|
||||||
+244
@@ -0,0 +1,244 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||||
|
import {BehaviorSubject, firstValueFrom, of, Subject} from 'rxjs';
|
||||||
|
import {SeriesCollapseFilter} from './SeriesCollapseFilter';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {UserService} from '../../../../settings/user-management/user.service';
|
||||||
|
import {BookState} from '../../../model/state/book-state.model';
|
||||||
|
import {Book} from '../../../model/book.model';
|
||||||
|
|
||||||
|
describe('SeriesCollapseFilter', () => {
|
||||||
|
let userServiceMock: any;
|
||||||
|
let messageServiceMock: any;
|
||||||
|
let userStateSubject: BehaviorSubject<any>;
|
||||||
|
let currentUser: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
userStateSubject = new BehaviorSubject({
|
||||||
|
user: null,
|
||||||
|
loaded: false,
|
||||||
|
error: null
|
||||||
|
});
|
||||||
|
|
||||||
|
currentUser = {
|
||||||
|
id: 1,
|
||||||
|
userSettings: {
|
||||||
|
entityViewPreferences: {
|
||||||
|
global: {seriesCollapsed: false},
|
||||||
|
overrides: []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
userServiceMock = {
|
||||||
|
userState$: userStateSubject.asObservable(),
|
||||||
|
getCurrentUser: vi.fn(() => currentUser),
|
||||||
|
updateUserSetting: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
messageServiceMock = {add: vi.fn()};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
SeriesCollapseFilter,
|
||||||
|
{provide: UserService, useValue: userServiceMock},
|
||||||
|
{provide: MessageService, useValue: messageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.useFakeTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
function createService(): SeriesCollapseFilter {
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
return runInInjectionContext(injector, () => TestBed.inject(SeriesCollapseFilter));
|
||||||
|
}
|
||||||
|
|
||||||
|
it('should initialize with default collapsed=false', () => {
|
||||||
|
const service = createService();
|
||||||
|
expect(service.isSeriesCollapsed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should apply global preference on userState$ emit', () => {
|
||||||
|
currentUser.userSettings.entityViewPreferences.global.seriesCollapsed = true;
|
||||||
|
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||||
|
const service = createService();
|
||||||
|
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||||
|
expect(service.isSeriesCollapsed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should apply override preference for context', () => {
|
||||||
|
currentUser.userSettings.entityViewPreferences.overrides = [
|
||||||
|
{entityType: 'LIBRARY', entityId: 42, preferences: {seriesCollapsed: true}}
|
||||||
|
];
|
||||||
|
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||||
|
const service = createService();
|
||||||
|
service.setContext('LIBRARY', 42);
|
||||||
|
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||||
|
expect(service.isSeriesCollapsed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fallback to old seriesCollapse field for global', () => {
|
||||||
|
currentUser.userSettings.entityViewPreferences.global = {seriesCollapse: true};
|
||||||
|
delete currentUser.userSettings.entityViewPreferences.global.seriesCollapsed;
|
||||||
|
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||||
|
const service = createService();
|
||||||
|
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||||
|
expect(service.isSeriesCollapsed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fallback to old seriesCollapse field for override', () => {
|
||||||
|
currentUser.userSettings.entityViewPreferences.overrides = [
|
||||||
|
{entityType: 'SHELF', entityId: 99, preferences: {seriesCollapse: true}}
|
||||||
|
];
|
||||||
|
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||||
|
const service = createService();
|
||||||
|
service.setContext('SHELF', 99);
|
||||||
|
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||||
|
expect(service.isSeriesCollapsed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setCollapsed should update value and trigger persistence after debounce', () => {
|
||||||
|
const service = createService();
|
||||||
|
service.setCollapsed(true);
|
||||||
|
expect(service.isSeriesCollapsed).toBe(true);
|
||||||
|
vi.advanceTimersByTime(500);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalled();
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Preference Saved',
|
||||||
|
detail: expect.stringContaining('enabled')
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setCollapsed should persist override if context set', () => {
|
||||||
|
const service = createService();
|
||||||
|
service.setContext('MAGIC_SHELF', 123);
|
||||||
|
service.setCollapsed(true);
|
||||||
|
vi.advanceTimersByTime(500);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||||
|
1,
|
||||||
|
'entityViewPreferences',
|
||||||
|
expect.objectContaining({
|
||||||
|
overrides: expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
entityType: 'MAGIC_SHELF',
|
||||||
|
entityId: 123,
|
||||||
|
preferences: expect.objectContaining({seriesCollapsed: true})
|
||||||
|
})
|
||||||
|
])
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setCollapsed should persist global if no context', () => {
|
||||||
|
const service = createService();
|
||||||
|
service.setCollapsed(true);
|
||||||
|
vi.advanceTimersByTime(500);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||||
|
1,
|
||||||
|
'entityViewPreferences',
|
||||||
|
expect.objectContaining({
|
||||||
|
global: expect.objectContaining({seriesCollapsed: true})
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not persist if no user', () => {
|
||||||
|
userServiceMock.getCurrentUser.mockReturnValue(null);
|
||||||
|
const service = createService();
|
||||||
|
service.setCollapsed(true);
|
||||||
|
vi.advanceTimersByTime(500);
|
||||||
|
expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should filter books and collapse series', async () => {
|
||||||
|
const service = createService();
|
||||||
|
service.setCollapsed(true);
|
||||||
|
|
||||||
|
const books: Book[] = [
|
||||||
|
{id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any,
|
||||||
|
{id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any,
|
||||||
|
{id: 3, metadata: {seriesName: 'B', seriesNumber: 1}, title: 'B3'} as any,
|
||||||
|
{id: 4, metadata: {}, title: 'B4'} as any
|
||||||
|
];
|
||||||
|
const state: BookState = {books, loaded: true, error: null};
|
||||||
|
|
||||||
|
const result = await firstValueFrom(service.filter(state));
|
||||||
|
expect(result && result.books).toBeTruthy();
|
||||||
|
if (!result || !result.books) throw new Error('No books in result');
|
||||||
|
expect(result.books.length).toBe(3);
|
||||||
|
// Series A collapsed to one book with seriesBooks of length 2
|
||||||
|
const a = result.books.find(b => b.metadata?.seriesName === 'A');
|
||||||
|
expect(a).toBeDefined();
|
||||||
|
expect(a?.seriesBooks?.length).toBe(2);
|
||||||
|
expect(a?.seriesCount).toBe(2);
|
||||||
|
// Series B collapsed to one book with seriesBooks of length 1
|
||||||
|
const b = result.books.find(b => b.metadata?.seriesName === 'B');
|
||||||
|
expect(b).toBeDefined();
|
||||||
|
expect(b?.seriesBooks?.length).toBe(1);
|
||||||
|
expect(b?.seriesCount).toBe(1);
|
||||||
|
// Non-series book remains
|
||||||
|
expect(result.books.some(b => b['title'] === 'B4')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not collapse series if forceExpandSeries=true', async () => {
|
||||||
|
const service = createService();
|
||||||
|
service.setCollapsed(true);
|
||||||
|
|
||||||
|
const books: Book[] = [
|
||||||
|
{id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any,
|
||||||
|
{id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any
|
||||||
|
];
|
||||||
|
const state: BookState = {books, loaded: true, error: null};
|
||||||
|
|
||||||
|
const result = await firstValueFrom(service.filter(state, true));
|
||||||
|
expect(result && result.books).toBeTruthy();
|
||||||
|
if (!result || !result.books) throw new Error('No books in result');
|
||||||
|
expect(result.books.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return original state if books is null', async () => {
|
||||||
|
const service = createService();
|
||||||
|
service.setCollapsed(true);
|
||||||
|
const state: BookState = {books: null, loaded: true, error: null};
|
||||||
|
const result = await firstValueFrom(service.filter(state));
|
||||||
|
expect(result).toBe(state);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not collapse if isSeriesCollapsed is false', async () => {
|
||||||
|
const service = createService();
|
||||||
|
service.setCollapsed(false);
|
||||||
|
const books: Book[] = [
|
||||||
|
{id: 1, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B1'} as any
|
||||||
|
];
|
||||||
|
const state: BookState = {books, loaded: true, error: null};
|
||||||
|
const result = await firstValueFrom(service.filter(state));
|
||||||
|
expect(result && result.books).toBeTruthy();
|
||||||
|
if (!result || !result.books) throw new Error('No books in result');
|
||||||
|
expect(result.books.length).toBe(1);
|
||||||
|
expect(result.books[0]?.seriesBooks).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should clean up destroy$ on ngOnDestroy', () => {
|
||||||
|
const service = createService();
|
||||||
|
const spy = vi.spyOn(service['destroy$'], 'next');
|
||||||
|
service.ngOnDestroy();
|
||||||
|
expect(spy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setContext(null, null) resets context and applies preference', () => {
|
||||||
|
const service = createService();
|
||||||
|
const applyPrefSpy = vi.spyOn(service as any, 'applyPreference');
|
||||||
|
service.setContext(null, null);
|
||||||
|
expect((service as any).currentContext).toBeNull();
|
||||||
|
expect(applyPrefSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
+621
@@ -0,0 +1,621 @@
|
|||||||
|
import {beforeEach, describe, expect, it} from 'vitest';
|
||||||
|
import {BehaviorSubject, firstValueFrom} from 'rxjs';
|
||||||
|
import {doesBookMatchReadStatus, isFileSizeInRange, isMatchScoreInRange, isPageCountInRange, isRatingInRange, isRatingInRange10, SideBarFilter} from './SidebarFilter';
|
||||||
|
import {BookState} from '../../../model/state/book-state.model';
|
||||||
|
import {Book, ReadStatus} from '../../../model/book.model';
|
||||||
|
import {Shelf} from '../../../model/shelf.model';
|
||||||
|
|
||||||
|
describe('SidebarFilter helpers', () => {
|
||||||
|
it('isRatingInRange returns true for value in range', () => {
|
||||||
|
expect(isRatingInRange(3.0, '3to4')).toBe(true);
|
||||||
|
expect(isRatingInRange(3.99, '3to4')).toBe(true);
|
||||||
|
expect(isRatingInRange(4.0, '3to4')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isRatingInRange returns false for value out of range', () => {
|
||||||
|
expect(isRatingInRange(4.5, '3to4')).toBe(false);
|
||||||
|
expect(isRatingInRange(2.9, '3to4')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isRatingInRange10 matches rounded rating', () => {
|
||||||
|
expect(isRatingInRange10(7.2, '7')).toBe(true);
|
||||||
|
expect(isRatingInRange10(7.7, '8')).toBe(true);
|
||||||
|
expect(isRatingInRange10(7.2, '8')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isFileSizeInRange returns true for value in range', () => {
|
||||||
|
expect(isFileSizeInRange(0, '<1mb')).toBe(true);
|
||||||
|
expect(isFileSizeInRange(1023, '<1mb')).toBe(true);
|
||||||
|
expect(isFileSizeInRange(1024, '<1mb')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isFileSizeInRange returns false for value out of range', () => {
|
||||||
|
expect(isFileSizeInRange(2000, '<1mb')).toBe(false);
|
||||||
|
expect(isFileSizeInRange(-1, '<1mb')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isPageCountInRange returns true for value in range', () => {
|
||||||
|
expect(isPageCountInRange(100, '100to200')).toBe(true);
|
||||||
|
expect(isPageCountInRange(199, '100to200')).toBe(true);
|
||||||
|
expect(isPageCountInRange(200, '100to200')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isPageCountInRange returns false for value out of range', () => {
|
||||||
|
expect(isPageCountInRange(50, '100to200')).toBe(false);
|
||||||
|
expect(isPageCountInRange(200, '100to200')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isMatchScoreInRange returns true for value in range', () => {
|
||||||
|
expect(isMatchScoreInRange(0.80, '0.80-0.89')).toBe(true);
|
||||||
|
expect(isMatchScoreInRange(0.89, '0.80-0.89')).toBe(true);
|
||||||
|
expect(isMatchScoreInRange(0.90, '0.80-0.89')).toBe(false);
|
||||||
|
expect(isMatchScoreInRange(85, '0.80-0.89')).toBe(true);
|
||||||
|
});
|
||||||
|
it('isMatchScoreInRange returns false for value out of range', () => {
|
||||||
|
expect(isMatchScoreInRange(0.5, '0.80-0.89')).toBe(false);
|
||||||
|
expect(isMatchScoreInRange(0.95, '0.80-0.89')).toBe(false);
|
||||||
|
});
|
||||||
|
it('doesBookMatchReadStatus returns true if status matches', () => {
|
||||||
|
const book = {readStatus: ReadStatus.READ} as Book;
|
||||||
|
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(true);
|
||||||
|
});
|
||||||
|
it('doesBookMatchReadStatus returns false if status does not match', () => {
|
||||||
|
const book = {readStatus: ReadStatus.UNREAD} as Book;
|
||||||
|
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false);
|
||||||
|
});
|
||||||
|
it('doesBookMatchReadStatus returns true for unset if included', () => {
|
||||||
|
const book = {} as Book;
|
||||||
|
expect(doesBookMatchReadStatus(book, [ReadStatus.UNSET])).toBe(true);
|
||||||
|
});
|
||||||
|
it('isRatingInRange returns false for unknown rangeId', () => {
|
||||||
|
expect(isRatingInRange(3.5, 'not-a-range')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isRatingInRange returns false for null/undefined rating', () => {
|
||||||
|
expect(isRatingInRange(undefined, '3to4')).toBe(false);
|
||||||
|
expect(isRatingInRange(null, '3to4')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isRatingInRange10 returns false for null/undefined rating', () => {
|
||||||
|
expect(isRatingInRange10(undefined, '7')).toBe(false);
|
||||||
|
expect(isRatingInRange10(null, '7')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isFileSizeInRange returns false for unknown rangeId', () => {
|
||||||
|
expect(isFileSizeInRange(500, 'not-a-range')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isFileSizeInRange returns false for null/undefined fileSize', () => {
|
||||||
|
expect(isFileSizeInRange(undefined, '<1mb')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isPageCountInRange returns false for unknown rangeId', () => {
|
||||||
|
expect(isPageCountInRange(150, 'not-a-range')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isPageCountInRange returns false for null/undefined pageCount', () => {
|
||||||
|
expect(isPageCountInRange(undefined, '100to200')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isMatchScoreInRange returns false for unknown rangeId', () => {
|
||||||
|
expect(isMatchScoreInRange(0.85, 'not-a-range')).toBe(false);
|
||||||
|
});
|
||||||
|
it('isMatchScoreInRange returns false for null/undefined score', () => {
|
||||||
|
expect(isMatchScoreInRange(undefined, '0.80-0.89')).toBe(false);
|
||||||
|
expect(isMatchScoreInRange(null, '0.80-0.89')).toBe(false);
|
||||||
|
});
|
||||||
|
it('doesBookMatchReadStatus returns false if selected is empty', () => {
|
||||||
|
const book = {readStatus: ReadStatus.READ} as Book;
|
||||||
|
expect(doesBookMatchReadStatus(book, [])).toBe(false);
|
||||||
|
});
|
||||||
|
it('doesBookMatchReadStatus returns false if status is not in selected', () => {
|
||||||
|
const book = {readStatus: ReadStatus.READING} as Book;
|
||||||
|
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('SideBarFilter', () => {
|
||||||
|
let books: Book[];
|
||||||
|
let bookState: BookState;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
// Create fresh book objects for each test to prevent mutation pollution
|
||||||
|
books = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
libraryId: 1,
|
||||||
|
libraryName: 'Lib1',
|
||||||
|
metadata: {
|
||||||
|
bookId: 1,
|
||||||
|
authors: ['A1'],
|
||||||
|
categories: ['C1'],
|
||||||
|
moods: ['M1'],
|
||||||
|
tags: ['T1'],
|
||||||
|
publisher: 'P1',
|
||||||
|
seriesName: 'S1',
|
||||||
|
amazonRating: 4.2,
|
||||||
|
goodreadsRating: 3.8,
|
||||||
|
hardcoverRating: 4.0,
|
||||||
|
publishedDate: '2020-01-01',
|
||||||
|
pageCount: 150,
|
||||||
|
language: 'en'
|
||||||
|
},
|
||||||
|
personalRating: 7,
|
||||||
|
fileSizeKb: 500,
|
||||||
|
shelves: [{name: 'shelf1', icon: 'icon1'}] as Shelf[],
|
||||||
|
metadataMatchScore: 0.8,
|
||||||
|
bookType: 'EPUB',
|
||||||
|
readStatus: ReadStatus.READ
|
||||||
|
} as Book,
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
libraryId: 1,
|
||||||
|
libraryName: 'Lib1',
|
||||||
|
metadata: {
|
||||||
|
bookId: 2,
|
||||||
|
authors: ['A2'],
|
||||||
|
categories: ['C2'],
|
||||||
|
moods: ['M2'],
|
||||||
|
tags: ['T2'],
|
||||||
|
publisher: 'P2',
|
||||||
|
seriesName: 'S2',
|
||||||
|
amazonRating: 2.5,
|
||||||
|
goodreadsRating: 2.8,
|
||||||
|
hardcoverRating: 2.0,
|
||||||
|
publishedDate: '2019-01-01',
|
||||||
|
pageCount: 50,
|
||||||
|
language: 'fr'
|
||||||
|
},
|
||||||
|
personalRating: 3,
|
||||||
|
fileSizeKb: 2000,
|
||||||
|
shelves: [] as Shelf[],
|
||||||
|
metadataMatchScore: 0.5,
|
||||||
|
bookType: 'PDF',
|
||||||
|
readStatus: ReadStatus.UNREAD
|
||||||
|
} as Book
|
||||||
|
];
|
||||||
|
bookState = {books, loaded: true, error: null};
|
||||||
|
});
|
||||||
|
|
||||||
|
function filterWith(activeFilters: any, mode: 'and' | 'or' = 'and') {
|
||||||
|
const filter$ = new BehaviorSubject(activeFilters);
|
||||||
|
const mode$ = new BehaviorSubject(mode);
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
return filter.filter(bookState);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('filters by author (and mode)', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.authors).toContain('A1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by author (or mode)', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by category', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({category: ['C2']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.categories).toContain('C2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by mood', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({mood: ['M1']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.moods).toContain('M1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by tag', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({tag: ['T2']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.tags).toContain('T2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by publisher', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({publisher: ['P1']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.publisher).toBe('P1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by series', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({series: ['S2']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.seriesName).toBe('S2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by readStatus', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ]}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.readStatus).toBe(ReadStatus.READ);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by amazonRating', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({amazonRating: ['4to4.5']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.amazonRating).toBeGreaterThanOrEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by goodreadsRating', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({goodreadsRating: ['3to4']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.goodreadsRating).toBeGreaterThanOrEqual(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by hardcoverRating', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({hardcoverRating: ['2to3']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.hardcoverRating).toBeGreaterThanOrEqual(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by personalRating', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({personalRating: ['7']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.personalRating).toBe(7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by shelfStatus unshelved', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({shelfStatus: ['unshelved']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.shelves?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by fileSize', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({fileSize: ['<1mb']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.fileSizeKb).toBeLessThan(1024);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by language', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({language: ['fr']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.language).toBe('fr');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by pageCount', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({pageCount: ['100to200']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadata?.pageCount).toBeGreaterThanOrEqual(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by matchScore', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({matchScore: ['0.80-0.89']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.metadataMatchScore).toBeGreaterThanOrEqual(0.8);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by bookType', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({bookType: ['PDF']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.bookType).toBe('PDF');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns all books if no filters', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns all books if filters is null', async () => {
|
||||||
|
const filter$ = new BehaviorSubject(null);
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(bookState));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns original state if books is null', async () => {
|
||||||
|
bookState.books = null as any;
|
||||||
|
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||||
|
expect(result).toBe(bookState);
|
||||||
|
expect(result.books).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns original state if books is undefined', async () => {
|
||||||
|
bookState.books = undefined as any;
|
||||||
|
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||||
|
expect(result).toBe(bookState);
|
||||||
|
expect(result.books).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty books array for empty bookState', async () => {
|
||||||
|
bookState.books = [];
|
||||||
|
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple authors in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple categories in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({category: ['C1', 'C2']}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple moods in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({mood: ['M1', 'M2']}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple tags in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({tag: ['T1', 'T2']}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple publishers in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple series in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns true for empty filter values in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({author: []}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false for empty filter values in AND mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({author: []}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters with multiple filter types in AND mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({
|
||||||
|
author: ['A1'],
|
||||||
|
category: ['C1'],
|
||||||
|
readStatus: [ReadStatus.READ]
|
||||||
|
}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters with multiple filter types in OR mode', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({
|
||||||
|
author: ['A1'],
|
||||||
|
category: ['C2']
|
||||||
|
}, 'or'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false for unknown filter type', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({unknownFilter: ['value']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by shelfStatus shelved', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({shelfStatus: ['shelved']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
expect(result?.books?.[0]?.shelves?.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false for book without publishedDate', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, publishedDate: undefined}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({publishedDate: [2020]});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple authors in AND mode - all must match', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, authors: ['A1', 'A3']}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({author: ['A1', 'A3']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple categories in AND mode - all must match', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, categories: ['C1', 'C3']}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({category: ['C1', 'C3']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple moods in AND mode - all must match', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, moods: ['M1', 'M3']}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({mood: ['M1', 'M3']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple tags in AND mode - all must match', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, tags: ['T1', 'T3']}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({tag: ['T1', 'T3']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
expect(result?.books?.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple publishers in AND mode - returns books matching all', async () => {
|
||||||
|
// Publisher can only have one value, so AND with multiple should return nothing
|
||||||
|
const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple series in AND mode - returns books matching all', async () => {
|
||||||
|
// Series can only have one value, so AND with multiple should return nothing
|
||||||
|
const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null metadata', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: null as any},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with undefined metadata', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: undefined as any},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has undefined metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null authors array', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, authors: null as any}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with undefined authors array', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, authors: undefined as any}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has undefined authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null categories array', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, categories: null as any}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({category: ['C1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null categories, so it doesn't match. Book 2 has category 'C2', doesn't match 'C1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null moods array', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, moods: null as any}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({mood: ['M1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null moods, so it doesn't match. Book 2 has mood 'M2', doesn't match 'M1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null tags array', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, tags: null as any}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({tag: ['T1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null tags, so it doesn't match. Book 2 has tag 'T2', doesn't match 'T1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null publisher', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, publisher: null as any}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({publisher: ['P1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null publisher, so it doesn't match. Book 2 has publisher 'P2', doesn't match 'P1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null series', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], metadata: {...books[0].metadata!, seriesName: null as any}},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({series: ['S1']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null series, so it doesn't match. Book 2 has series 'S2', doesn't match 'S1'
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with null shelves', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], shelves: null as any},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has null shelves (unshelved), book 2 has empty shelves array (also unshelved)
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles book with undefined shelves', async () => {
|
||||||
|
const testBooks: Book[] = [
|
||||||
|
{...books[0], shelves: undefined as any},
|
||||||
|
{...books[1]}
|
||||||
|
];
|
||||||
|
const testState = {...bookState, books: testBooks};
|
||||||
|
const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']});
|
||||||
|
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||||
|
const filter = new SideBarFilter(filter$, mode$);
|
||||||
|
const result = await firstValueFrom(filter.filter(testState));
|
||||||
|
// Book 1 has undefined shelves (unshelved), book 2 has empty shelves array (also unshelved)
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by multiple readStatus values', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ, ReadStatus.UNREAD]}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles non-array filter values', async () => {
|
||||||
|
const result = await firstValueFrom(filterWith({author: 'A1' as any}, 'and'));
|
||||||
|
expect(result?.books?.length).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -53,6 +53,8 @@ export class SideBarFilter implements BookFilter {
|
|||||||
filter(bookState: BookState): Observable<BookState> {
|
filter(bookState: BookState): Observable<BookState> {
|
||||||
return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe(
|
return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe(
|
||||||
map(([activeFilters, mode]) => {
|
map(([activeFilters, mode]) => {
|
||||||
|
// Return original state if books is null or undefined
|
||||||
|
if (bookState.books == null) return bookState;
|
||||||
if (!activeFilters) return bookState;
|
if (!activeFilters) return bookState;
|
||||||
const filteredBooks = (bookState.books || []).filter(book => {
|
const filteredBooks = (bookState.books || []).filter(book => {
|
||||||
const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => {
|
const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => {
|
||||||
|
|||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||||
|
import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {LocalStorageService} from '../../../../../shared/service/local-storage-service';
|
||||||
|
import {take} from 'rxjs/operators';
|
||||||
|
|
||||||
|
describe('SidebarFilterTogglePrefService', () => {
|
||||||
|
let messageServiceMock: any;
|
||||||
|
let localStorageServiceMock: any;
|
||||||
|
let originalInnerWidth: number;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
messageServiceMock = {add: vi.fn()};
|
||||||
|
localStorageServiceMock = {
|
||||||
|
set: vi.fn(),
|
||||||
|
get: vi.fn()
|
||||||
|
};
|
||||||
|
originalInnerWidth = window.innerWidth;
|
||||||
|
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 1024});
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
SidebarFilterTogglePrefService,
|
||||||
|
{provide: MessageService, useValue: messageServiceMock},
|
||||||
|
{provide: LocalStorageService, useValue: localStorageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: originalInnerWidth});
|
||||||
|
});
|
||||||
|
|
||||||
|
function createService(): SidebarFilterTogglePrefService {
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
return runInInjectionContext(injector, () => TestBed.inject(SidebarFilterTogglePrefService));
|
||||||
|
}
|
||||||
|
|
||||||
|
it('should initialize with true if no saved value and not narrow', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||||
|
const service = createService();
|
||||||
|
expect(service.selectedShowFilter).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with saved value if present and not narrow', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(false);
|
||||||
|
const service = createService();
|
||||||
|
expect(service.selectedShowFilter).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with false if window is narrow', () => {
|
||||||
|
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 600});
|
||||||
|
const service = createService();
|
||||||
|
expect(service.selectedShowFilter).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should emit value on showFilter$', async () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||||
|
const service = createService();
|
||||||
|
const val = await service.showFilter$.pipe(take(1)).toPromise();
|
||||||
|
expect(val).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update selectedShowFilter and persist preference', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||||
|
const service = createService();
|
||||||
|
service.selectedShowFilter = false;
|
||||||
|
expect(service.selectedShowFilter).toBe(false);
|
||||||
|
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not persist if value is unchanged', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(true);
|
||||||
|
const service = createService();
|
||||||
|
localStorageServiceMock.set.mockClear();
|
||||||
|
service.selectedShowFilter = true;
|
||||||
|
expect(localStorageServiceMock.set).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should toggle selectedShowFilter', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(true);
|
||||||
|
const service = createService();
|
||||||
|
service.toggle();
|
||||||
|
expect(service.selectedShowFilter).toBe(false);
|
||||||
|
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false);
|
||||||
|
service.toggle();
|
||||||
|
expect(service.selectedShowFilter).toBe(true);
|
||||||
|
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle error in savePreference and show error message', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||||
|
localStorageServiceMock.set.mockImplementation(() => {
|
||||||
|
throw new Error('fail');
|
||||||
|
});
|
||||||
|
const service = createService();
|
||||||
|
service.selectedShowFilter = false;
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Save Failed'
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call loadFromStorage and set correct value for wide screen', () => {
|
||||||
|
localStorageServiceMock.get.mockReturnValueOnce(true);
|
||||||
|
const service = createService();
|
||||||
|
expect(service.selectedShowFilter).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call loadFromStorage and set correct value for narrow screen', () => {
|
||||||
|
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 500});
|
||||||
|
const service = createService();
|
||||||
|
expect(service.selectedShowFilter).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {BookSorter} from './BookSorter';
|
||||||
|
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||||
|
|
||||||
|
describe('BookSorter', () => {
|
||||||
|
let applySortOption: (sort: SortOption) => void;
|
||||||
|
let sorter: BookSorter;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
applySortOption = vi.fn();
|
||||||
|
sorter = new BookSorter(applySortOption);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with undefined selectedSort', () => {
|
||||||
|
expect(sorter.selectedSort).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have all default sort options', () => {
|
||||||
|
expect(sorter.sortOptions).toBeInstanceOf(Array);
|
||||||
|
expect(sorter.sortOptions.length).toBeGreaterThan(0);
|
||||||
|
expect(sorter.sortOptions.some(opt => opt.field === 'title')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should set selectedSort and call applySortOption on sortBooks (first time)', () => {
|
||||||
|
sorter.sortBooks('author');
|
||||||
|
expect(sorter.selectedSort).toMatchObject({
|
||||||
|
field: 'author',
|
||||||
|
direction: SortDirection.ASCENDING
|
||||||
|
});
|
||||||
|
expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should toggle direction when sorting the same field again', () => {
|
||||||
|
sorter.sortBooks('title');
|
||||||
|
const firstSort = {...sorter.selectedSort!};
|
||||||
|
sorter.sortBooks('title');
|
||||||
|
expect(sorter.selectedSort?.field).toBe('title');
|
||||||
|
expect(sorter.selectedSort?.direction).not.toBe(firstSort.direction);
|
||||||
|
expect(applySortOption).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reset direction to ASCENDING when sorting a new field', () => {
|
||||||
|
sorter.sortBooks('title');
|
||||||
|
sorter.sortBooks('author');
|
||||||
|
expect(sorter.selectedSort?.field).toBe('author');
|
||||||
|
expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not change selectedSort or call applySortOption for unknown field', () => {
|
||||||
|
sorter.sortBooks('notAField');
|
||||||
|
expect(sorter.selectedSort).toBeUndefined();
|
||||||
|
expect(applySortOption).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update sortOptions with correct icon for selected field and direction', () => {
|
||||||
|
sorter.sortBooks('title');
|
||||||
|
const upIcon = 'pi pi-arrow-up';
|
||||||
|
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(upIcon);
|
||||||
|
expect(sorter.sortOptions.filter(opt => opt.field !== 'title').every(opt => !(opt as any).icon)).toBe(true);
|
||||||
|
|
||||||
|
sorter.sortBooks('title'); // toggle direction
|
||||||
|
const downIcon = 'pi pi-arrow-down';
|
||||||
|
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(downIcon);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should only set icon for the selected field', () => {
|
||||||
|
sorter.sortBooks('author');
|
||||||
|
sorter.sortBooks('title');
|
||||||
|
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe('pi pi-arrow-up');
|
||||||
|
expect((sorter.sortOptions.find(opt => opt.field === 'author') as any)?.icon).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should preserve label and field when toggling direction', () => {
|
||||||
|
sorter.sortBooks('fileName');
|
||||||
|
const {label, field} = sorter.selectedSort!;
|
||||||
|
sorter.sortBooks('fileName');
|
||||||
|
expect(sorter.selectedSort?.label).toBe(label);
|
||||||
|
expect(sorter.selectedSort?.field).toBe(field);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not throw if updateSortOptions is called with no selectedSort', () => {
|
||||||
|
// @ts-ignore
|
||||||
|
sorter.selectedSort = undefined;
|
||||||
|
expect(() => sorter.updateSortOptions()).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not mutate original sortOptions array reference on updateSortOptions', () => {
|
||||||
|
const original = sorter.sortOptions;
|
||||||
|
sorter.sortBooks('title');
|
||||||
|
expect(sorter.sortOptions).not.toBe(original);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle sorting "random" field', () => {
|
||||||
|
sorter.sortBooks('random');
|
||||||
|
expect(sorter.selectedSort?.field).toBe('random');
|
||||||
|
expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING);
|
||||||
|
expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,29 +4,30 @@ export class BookSorter {
|
|||||||
selectedSort: SortOption | undefined = undefined;
|
selectedSort: SortOption | undefined = undefined;
|
||||||
|
|
||||||
sortOptions: SortOption[] = [
|
sortOptions: SortOption[] = [
|
||||||
{ label: 'Title', field: 'title', direction: SortDirection.ASCENDING },
|
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING },
|
{label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING },
|
{label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Author', field: 'author', direction: SortDirection.ASCENDING },
|
{label: 'Author', field: 'author', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING },
|
{label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING },
|
{label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING },
|
{label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING },
|
{label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING },
|
{label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING },
|
{label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING },
|
{label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING },
|
{label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING },
|
{label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING },
|
{label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING },
|
{label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING },
|
{label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING },
|
{label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING },
|
{label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING },
|
{label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING},
|
||||||
{ label: 'Random', field: 'random', direction: SortDirection.ASCENDING },
|
{label: 'Random', field: 'random', direction: SortDirection.ASCENDING},
|
||||||
];
|
];
|
||||||
|
|
||||||
constructor(private applySortOption: (sort: SortOption) => void) {}
|
constructor(private applySortOption: (sort: SortOption) => void) {
|
||||||
|
}
|
||||||
|
|
||||||
sortBooks(field: string): void {
|
sortBooks(field: string): void {
|
||||||
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
||||||
|
|||||||
+139
@@ -0,0 +1,139 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||||
|
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||||
|
|
||||||
|
describe('TableColumnPreferenceService', () => {
|
||||||
|
let service: TableColumnPreferenceService;
|
||||||
|
let userServiceMock: any;
|
||||||
|
let messageServiceMock: any;
|
||||||
|
|
||||||
|
const allColumns = [
|
||||||
|
{field: 'readStatus', header: 'Read'},
|
||||||
|
{field: 'title', header: 'Title'},
|
||||||
|
{field: 'authors', header: 'Authors'},
|
||||||
|
{field: 'publisher', header: 'Publisher'},
|
||||||
|
{field: 'seriesName', header: 'Series'},
|
||||||
|
{field: 'seriesNumber', header: 'Series #'},
|
||||||
|
{field: 'categories', header: 'Genres'},
|
||||||
|
{field: 'publishedDate', header: 'Published'},
|
||||||
|
{field: 'lastReadTime', header: 'Last Read'},
|
||||||
|
{field: 'addedOn', header: 'Added'},
|
||||||
|
{field: 'fileSizeKb', header: 'File Size'},
|
||||||
|
{field: 'language', header: 'Language'},
|
||||||
|
{field: 'isbn', header: 'ISBN'},
|
||||||
|
{field: 'pageCount', header: 'Pages'},
|
||||||
|
{field: 'amazonRating', header: 'Amazon'},
|
||||||
|
{field: 'amazonReviewCount', header: 'AZ #'},
|
||||||
|
{field: 'goodreadsRating', header: 'Goodreads'},
|
||||||
|
{field: 'goodreadsReviewCount', header: 'GR #'},
|
||||||
|
{field: 'hardcoverRating', header: 'Hardcover'},
|
||||||
|
{field: 'hardcoverReviewCount', header: 'HC #'},
|
||||||
|
];
|
||||||
|
|
||||||
|
const fallbackPreferences: TableColumnPreference[] = allColumns.map((col, index) => ({
|
||||||
|
field: col.field,
|
||||||
|
visible: true,
|
||||||
|
order: index
|
||||||
|
}));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
userServiceMock = {
|
||||||
|
getCurrentUser: vi.fn(),
|
||||||
|
updateUserSetting: vi.fn()
|
||||||
|
};
|
||||||
|
messageServiceMock = {
|
||||||
|
add: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
TableColumnPreferenceService,
|
||||||
|
{provide: UserService, useValue: userServiceMock},
|
||||||
|
{provide: MessageService, useValue: messageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(TableColumnPreferenceService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with fallback preferences if none provided', () => {
|
||||||
|
service.initPreferences(undefined);
|
||||||
|
expect(service.preferences).toEqual(fallbackPreferences);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with provided preferences', () => {
|
||||||
|
const savedPrefs: TableColumnPreference[] = [
|
||||||
|
{field: 'title', visible: true, order: 0},
|
||||||
|
{field: 'authors', visible: false, order: 1}
|
||||||
|
];
|
||||||
|
service.initPreferences(savedPrefs);
|
||||||
|
expect(service.preferences.find(p => p.field === 'title')?.visible).toBe(true);
|
||||||
|
expect(service.preferences.find(p => p.field === 'authors')?.visible).toBe(false);
|
||||||
|
expect(service.preferences.length).toBe(allColumns.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return all columns', () => {
|
||||||
|
expect(service.allColumns).toEqual(allColumns);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return visible columns sorted by order', () => {
|
||||||
|
const prefs: TableColumnPreference[] = [
|
||||||
|
{field: 'title', visible: true, order: 1},
|
||||||
|
{field: 'authors', visible: true, order: 0},
|
||||||
|
{field: 'publisher', visible: false, order: 2}
|
||||||
|
];
|
||||||
|
service['preferencesSubject'].next([
|
||||||
|
...prefs,
|
||||||
|
...fallbackPreferences.filter(p => !prefs.some(fp => fp.field === p.field))
|
||||||
|
]);
|
||||||
|
const visible = service.visibleColumns;
|
||||||
|
const fields = visible.map(col => col.field);
|
||||||
|
expect(fields.indexOf('authors')).toBeLessThan(fields.indexOf('title'));
|
||||||
|
expect(fields).not.toContain('publisher');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should save visible columns and update preferences', () => {
|
||||||
|
const selectedColumns = [
|
||||||
|
{field: 'title'},
|
||||||
|
{field: 'authors'}
|
||||||
|
];
|
||||||
|
userServiceMock.getCurrentUser.mockReturnValue({id: 42});
|
||||||
|
service.saveVisibleColumns(selectedColumns);
|
||||||
|
const prefs = service.preferences;
|
||||||
|
expect(prefs.find(p => p.field === 'title')?.visible).toBe(true);
|
||||||
|
expect(prefs.find(p => p.field === 'authors')?.visible).toBe(true);
|
||||||
|
expect(prefs.find(p => p.field === 'publisher')?.visible).toBe(false);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', prefs);
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Preferences Saved'
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not call updateUserSetting if no current user', () => {
|
||||||
|
userServiceMock.getCurrentUser.mockReturnValue(undefined);
|
||||||
|
service.saveVisibleColumns([{field: 'title'}]);
|
||||||
|
expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled();
|
||||||
|
expect(messageServiceMock.add).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get column header for known and unknown fields', () => {
|
||||||
|
expect(service['getColumnHeader']('title')).toBe('Title');
|
||||||
|
expect(service['getColumnHeader']('unknown')).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should merge saved preferences with all columns', () => {
|
||||||
|
const savedPrefs: TableColumnPreference[] = [
|
||||||
|
{field: 'title', visible: false, order: 5}
|
||||||
|
];
|
||||||
|
const merged = service['mergeWithAllColumns'](savedPrefs);
|
||||||
|
expect(merged.find(p => p.field === 'title')?.visible).toBe(false);
|
||||||
|
expect(merged.length).toBe(allColumns.length);
|
||||||
|
expect(merged.find(p => p.field === 'authors')?.visible).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
+1
-1
@@ -12,7 +12,7 @@ import {Button} from 'primeng/button';
|
|||||||
import {AsyncPipe} from '@angular/common';
|
import {AsyncPipe} from '@angular/common';
|
||||||
import {Checkbox} from 'primeng/checkbox';
|
import {Checkbox} from 'primeng/checkbox';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {BookDialogHelperService} from '../book-browser/BookDialogHelperService';
|
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||||
import {LoadingService} from '../../../../core/services/loading.service';
|
import {LoadingService} from '../../../../core/services/loading.service';
|
||||||
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
|
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
|
||||||
import {IconSelection} from '../../../../shared/service/icon-picker.service';
|
import {IconSelection} from '../../../../shared/service/icon-picker.service';
|
||||||
|
|||||||
+1
-1
@@ -23,7 +23,7 @@ import {Textarea} from "primeng/textarea";
|
|||||||
import {Image} from "primeng/image";
|
import {Image} from "primeng/image";
|
||||||
import {LazyLoadImageModule} from "ng-lazyload-image";
|
import {LazyLoadImageModule} from "ng-lazyload-image";
|
||||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||||
import {BookDialogHelperService} from "../../../../book/components/book-browser/BookDialogHelperService";
|
import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service";
|
||||||
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
||||||
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host-service';
|
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host-service';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
|
|||||||
+2
-2
@@ -29,7 +29,7 @@ import {BookReviewsComponent} from '../../../../book/components/book-reviews/boo
|
|||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {TieredMenu} from 'primeng/tieredmenu';
|
import {TieredMenu} from 'primeng/tieredmenu';
|
||||||
import {Image} from 'primeng/image';
|
import {Image} from 'primeng/image';
|
||||||
import {BookDialogHelperService} from '../../../../book/components/book-browser/BookDialogHelperService';
|
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
|
||||||
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
|
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
|
||||||
import {BookNotesComponent} from '../../../../book/components/book-notes/book-notes-component';
|
import {BookNotesComponent} from '../../../../book/components/book-notes/book-notes-component';
|
||||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||||
@@ -174,7 +174,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
|||||||
take(1),
|
take(1),
|
||||||
map(userState => {
|
map(userState => {
|
||||||
const items: MenuItem[] = [];
|
const items: MenuItem[] = [];
|
||||||
|
|
||||||
// Add allowed submenus based on user permissions
|
// Add allowed submenus based on user permissions
|
||||||
|
|
||||||
if (userState?.user?.permissions.canUpload || userState?.user?.permissions.admin) {
|
if (userState?.user?.permissions.canUpload || userState?.user?.permissions.admin) {
|
||||||
|
|||||||
+203
@@ -0,0 +1,203 @@
|
|||||||
|
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 {KoboService, KoboSyncSettings} from './kobo.service';
|
||||||
|
|
||||||
|
describe('KoboService', () => {
|
||||||
|
let service: KoboService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
const mockSettings: KoboSyncSettings = {
|
||||||
|
token: 'abc123',
|
||||||
|
syncEnabled: true,
|
||||||
|
progressMarkAsReadingThreshold: 10,
|
||||||
|
progressMarkAsFinishedThreshold: 90,
|
||||||
|
autoAddToShelf: false,
|
||||||
|
hardcoverApiKey: 'hardcover-key',
|
||||||
|
hardcoverSyncEnabled: true
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
put: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
KoboService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(KoboService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get user Kobo settings', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockSettings));
|
||||||
|
service.getUser().subscribe(settings => {
|
||||||
|
expect(settings).toEqual(mockSettings);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create or update token', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(mockSettings));
|
||||||
|
service.createOrUpdateToken().subscribe(settings => {
|
||||||
|
expect(settings).toEqual(mockSettings);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings/token'), null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update settings', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(mockSettings));
|
||||||
|
service.updateSettings(mockSettings).subscribe(settings => {
|
||||||
|
expect(settings).toEqual(mockSettings);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings'), mockSettings);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle getUser error', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.getUser().subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle createOrUpdateToken error', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.createOrUpdateToken().subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle updateSettings error', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.updateSettings(mockSettings).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('KoboService - API Contract Tests', () => {
|
||||||
|
let service: KoboService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
put: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
KoboService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(KoboService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate all required KoboSyncSettings fields exist', () => {
|
||||||
|
const requiredFields: (keyof KoboSyncSettings)[] = [
|
||||||
|
'token', 'syncEnabled', 'autoAddToShelf'
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockResponse: KoboSyncSettings = {
|
||||||
|
token: 'abc',
|
||||||
|
syncEnabled: true,
|
||||||
|
autoAddToShelf: false,
|
||||||
|
progressMarkAsReadingThreshold: 10,
|
||||||
|
progressMarkAsFinishedThreshold: 90,
|
||||||
|
hardcoverApiKey: 'hardcover-key',
|
||||||
|
hardcoverSyncEnabled: true
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||||
|
|
||||||
|
service.getUser().subscribe(settings => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(settings).toHaveProperty(field);
|
||||||
|
expect(settings[field]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns KoboSyncSettings without required token field', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
syncEnabled: true,
|
||||||
|
autoAddToShelf: false
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
|
||||||
|
service.getUser().subscribe(settings => {
|
||||||
|
expect(settings).not.toHaveProperty('token');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns KoboSyncSettings without required syncEnabled field', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
token: 'abc',
|
||||||
|
autoAddToShelf: false
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
|
||||||
|
service.getUser().subscribe(settings => {
|
||||||
|
expect(settings).not.toHaveProperty('syncEnabled');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns KoboSyncSettings without required autoAddToShelf field', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
token: 'abc',
|
||||||
|
syncEnabled: true
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
|
||||||
|
service.getUser().subscribe(settings => {
|
||||||
|
expect(settings).not.toHaveProperty('autoAddToShelf');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for getUser', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of({}));
|
||||||
|
service.getUser().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for createOrUpdateToken', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of({}));
|
||||||
|
service.createOrUpdateToken().subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings\/token$/), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for updateSettings', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of({}));
|
||||||
|
const settings: KoboSyncSettings = {
|
||||||
|
token: 'abc',
|
||||||
|
syncEnabled: true,
|
||||||
|
autoAddToShelf: false
|
||||||
|
};
|
||||||
|
service.updateSettings(settings).subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings$/), settings);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
+193
@@ -0,0 +1,193 @@
|
|||||||
|
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 {KoreaderService, KoreaderUser} from './koreader.service';
|
||||||
|
|
||||||
|
describe('KoreaderService', () => {
|
||||||
|
let service: KoreaderService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
const mockUser: KoreaderUser = {
|
||||||
|
username: 'testuser',
|
||||||
|
password: 'secret',
|
||||||
|
syncEnabled: true
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
patch: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
KoreaderService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(KoreaderService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create user', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(mockUser));
|
||||||
|
service.createUser('testuser', 'secret').subscribe(user => {
|
||||||
|
expect(user).toEqual(mockUser);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('/me'),
|
||||||
|
{username: 'testuser', password: 'secret'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get user', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockUser));
|
||||||
|
service.getUser().subscribe(user => {
|
||||||
|
expect(user).toEqual(mockUser);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/me'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should toggle sync', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||||
|
service.toggleSync(true).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('/me/sync'),
|
||||||
|
null,
|
||||||
|
{params: {enabled: 'true'}}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle createUser error', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.createUser('testuser', 'secret').subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle getUser error', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.getUser().subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle toggleSync error', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.toggleSync(false).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('KoreaderService - API Contract Tests', () => {
|
||||||
|
let service: KoreaderService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
patch: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
KoreaderService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(KoreaderService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate all required KoreaderUser fields exist', () => {
|
||||||
|
const requiredFields: (keyof KoreaderUser)[] = ['username', 'password', 'syncEnabled'];
|
||||||
|
const mockResponse: KoreaderUser = {
|
||||||
|
username: 'test',
|
||||||
|
password: 'pw',
|
||||||
|
syncEnabled: true
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||||
|
service.getUser().subscribe(user => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(user).toHaveProperty(field);
|
||||||
|
expect(user[field]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns KoreaderUser without required username field', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
password: 'pw',
|
||||||
|
syncEnabled: true
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
service.getUser().subscribe(user => {
|
||||||
|
expect(user).not.toHaveProperty('username');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns KoreaderUser without required password field', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
username: 'test',
|
||||||
|
syncEnabled: true
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
service.getUser().subscribe(user => {
|
||||||
|
expect(user).not.toHaveProperty('password');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns KoreaderUser without required syncEnabled field', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
username: 'test',
|
||||||
|
password: 'pw'
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
service.getUser().subscribe(user => {
|
||||||
|
expect(user).not.toHaveProperty('syncEnabled');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for createUser', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of({}));
|
||||||
|
service.createUser('u', 'p').subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v1\/koreader-users\/me$/),
|
||||||
|
{username: 'u', password: 'p'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for getUser', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of({}));
|
||||||
|
service.getUser().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/koreader-users\/me$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for toggleSync', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of({}));
|
||||||
|
service.toggleSync(true).subscribe();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v1\/koreader-users\/me\/sync$/),
|
||||||
|
null,
|
||||||
|
{params: {enabled: 'true'}}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
+271
@@ -0,0 +1,271 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {of, throwError} from 'rxjs';
|
||||||
|
import {EmailV2ProviderService} from './email-v2-provider.service';
|
||||||
|
import {EmailProvider} from '../email-provider.model';
|
||||||
|
|
||||||
|
describe('EmailV2ProviderService', () => {
|
||||||
|
let service: EmailV2ProviderService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
const mockProvider: EmailProvider = {
|
||||||
|
isEditing: false,
|
||||||
|
id: 1,
|
||||||
|
userId: 2,
|
||||||
|
name: 'Provider1',
|
||||||
|
host: 'smtp.example.com',
|
||||||
|
port: 587,
|
||||||
|
username: 'user',
|
||||||
|
password: 'pass',
|
||||||
|
fromAddress: 'from@example.com',
|
||||||
|
auth: true,
|
||||||
|
startTls: true,
|
||||||
|
defaultProvider: false,
|
||||||
|
shared: false
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
delete: vi.fn(),
|
||||||
|
patch: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
EmailV2ProviderService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(EmailV2ProviderService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get email providers', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockProvider]));
|
||||||
|
service.getEmailProviders().subscribe(providers => {
|
||||||
|
expect(providers).toEqual([mockProvider]);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create email provider', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(mockProvider));
|
||||||
|
service.createEmailProvider(mockProvider).subscribe(provider => {
|
||||||
|
expect(provider).toEqual(mockProvider);
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers'), mockProvider);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update provider', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(mockProvider));
|
||||||
|
service.updateProvider(mockProvider).subscribe(provider => {
|
||||||
|
expect(provider).toEqual(mockProvider);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining(`/api/v2/email/providers/${mockProvider.id}`), mockProvider);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delete provider', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteProvider(1).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers/1'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should set default provider', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||||
|
service.setDefaultProvider(1).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers/1/set-default'), {});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle getEmailProviders error', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.getEmailProviders().subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle createEmailProvider error', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.createEmailProvider(mockProvider).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle updateProvider error', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.updateProvider(mockProvider).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle deleteProvider error', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.deleteProvider(1).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle setDefaultProvider error', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.setDefaultProvider(1).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('EmailV2ProviderService - API Contract Tests', () => {
|
||||||
|
let service: EmailV2ProviderService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
delete: vi.fn(),
|
||||||
|
patch: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
EmailV2ProviderService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(EmailV2ProviderService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate all required EmailProvider fields exist', () => {
|
||||||
|
const requiredFields: (keyof EmailProvider)[] = [
|
||||||
|
'isEditing', 'id', 'userId', 'name', 'host', 'port', 'username', 'password',
|
||||||
|
'fromAddress', 'auth', 'startTls', 'defaultProvider', 'shared'
|
||||||
|
];
|
||||||
|
const mockResponse: EmailProvider = {
|
||||||
|
isEditing: false,
|
||||||
|
id: 1,
|
||||||
|
userId: 2,
|
||||||
|
name: 'Provider1',
|
||||||
|
host: 'smtp.example.com',
|
||||||
|
port: 587,
|
||||||
|
username: 'user',
|
||||||
|
password: 'pass',
|
||||||
|
fromAddress: 'from@example.com',
|
||||||
|
auth: true,
|
||||||
|
startTls: true,
|
||||||
|
defaultProvider: false,
|
||||||
|
shared: false
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockResponse]));
|
||||||
|
service.getEmailProviders().subscribe(providers => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(providers[0]).toHaveProperty(field);
|
||||||
|
expect(providers[0][field]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns EmailProvider without required id field', () => {
|
||||||
|
const invalidResponse = [{
|
||||||
|
isEditing: false,
|
||||||
|
userId: 2,
|
||||||
|
name: 'Provider1',
|
||||||
|
host: 'smtp.example.com',
|
||||||
|
port: 587,
|
||||||
|
username: 'user',
|
||||||
|
password: 'pass',
|
||||||
|
fromAddress: 'from@example.com',
|
||||||
|
auth: true,
|
||||||
|
startTls: true,
|
||||||
|
defaultProvider: false,
|
||||||
|
shared: false
|
||||||
|
}];
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
service.getEmailProviders().subscribe(providers => {
|
||||||
|
expect(providers[0]).not.toHaveProperty('id');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for getEmailProviders', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([]));
|
||||||
|
service.getEmailProviders().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for createEmailProvider', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of({}));
|
||||||
|
const provider = {
|
||||||
|
isEditing: false,
|
||||||
|
id: 1,
|
||||||
|
userId: 2,
|
||||||
|
name: 'Provider1',
|
||||||
|
host: 'smtp.example.com',
|
||||||
|
port: 587,
|
||||||
|
username: 'user',
|
||||||
|
password: 'pass',
|
||||||
|
fromAddress: 'from@example.com',
|
||||||
|
auth: true,
|
||||||
|
startTls: true,
|
||||||
|
defaultProvider: false,
|
||||||
|
shared: false
|
||||||
|
};
|
||||||
|
service.createEmailProvider(provider).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers$/), provider);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for updateProvider', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of({}));
|
||||||
|
const provider = {
|
||||||
|
isEditing: false,
|
||||||
|
id: 1,
|
||||||
|
userId: 2,
|
||||||
|
name: 'Provider1',
|
||||||
|
host: 'smtp.example.com',
|
||||||
|
port: 587,
|
||||||
|
username: 'user',
|
||||||
|
password: 'pass',
|
||||||
|
fromAddress: 'from@example.com',
|
||||||
|
auth: true,
|
||||||
|
startTls: true,
|
||||||
|
defaultProvider: false,
|
||||||
|
shared: false
|
||||||
|
};
|
||||||
|
service.updateProvider(provider).subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1$/), provider);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for deleteProvider', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteProvider(1).subscribe();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for setDefaultProvider', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||||
|
service.setDefaultProvider(1).subscribe();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1\/set-default$/), {});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
+230
@@ -0,0 +1,230 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {of, throwError} from 'rxjs';
|
||||||
|
import {EmailV2RecipientService} from './email-v2-recipient.service';
|
||||||
|
import {EmailRecipient} from '../email-recipient.model';
|
||||||
|
|
||||||
|
describe('EmailV2RecipientService', () => {
|
||||||
|
let service: EmailV2RecipientService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
const mockRecipient: EmailRecipient = {
|
||||||
|
id: 1,
|
||||||
|
email: 'to@example.com',
|
||||||
|
name: 'Recipient1',
|
||||||
|
defaultRecipient: false,
|
||||||
|
isEditing: false
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
delete: vi.fn(),
|
||||||
|
patch: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
EmailV2RecipientService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(EmailV2RecipientService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get recipients', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockRecipient]));
|
||||||
|
service.getRecipients().subscribe(recipients => {
|
||||||
|
expect(recipients).toEqual([mockRecipient]);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create recipient', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(mockRecipient));
|
||||||
|
service.createRecipient(mockRecipient).subscribe(recipient => {
|
||||||
|
expect(recipient).toEqual(mockRecipient);
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients'), mockRecipient);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update recipient', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(mockRecipient));
|
||||||
|
service.updateRecipient(mockRecipient).subscribe(recipient => {
|
||||||
|
expect(recipient).toEqual(mockRecipient);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining(`/api/v2/email/recipients/${mockRecipient.id}`), mockRecipient);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delete recipient', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteRecipient(1).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients/1'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should set default recipient', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||||
|
service.setDefaultRecipient(1).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients/1/set-default'), {});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle getRecipients error', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.getRecipients().subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle createRecipient error', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.createRecipient(mockRecipient).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle updateRecipient error', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.updateRecipient(mockRecipient).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle deleteRecipient error', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.deleteRecipient(1).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle setDefaultRecipient error', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.setDefaultRecipient(1).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('EmailV2RecipientService - API Contract Tests', () => {
|
||||||
|
let service: EmailV2RecipientService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
delete: vi.fn(),
|
||||||
|
patch: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
EmailV2RecipientService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(EmailV2RecipientService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate all required EmailRecipient fields exist', () => {
|
||||||
|
const requiredFields: (keyof EmailRecipient)[] = [
|
||||||
|
'id', 'email', 'name', 'defaultRecipient', 'isEditing'
|
||||||
|
];
|
||||||
|
const mockResponse: EmailRecipient = {
|
||||||
|
id: 1,
|
||||||
|
email: 'to@example.com',
|
||||||
|
name: 'Recipient1',
|
||||||
|
defaultRecipient: false,
|
||||||
|
isEditing: false
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockResponse]));
|
||||||
|
service.getRecipients().subscribe(recipients => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(recipients[0]).toHaveProperty(field);
|
||||||
|
expect(recipients[0][field]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns EmailRecipient without required id field', () => {
|
||||||
|
const invalidResponse = [{
|
||||||
|
email: 'to@example.com',
|
||||||
|
name: 'Recipient1',
|
||||||
|
defaultRecipient: false,
|
||||||
|
isEditing: false
|
||||||
|
}];
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
service.getRecipients().subscribe(recipients => {
|
||||||
|
expect(recipients[0]).not.toHaveProperty('id');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for getRecipients', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([]));
|
||||||
|
service.getRecipients().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for createRecipient', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of({}));
|
||||||
|
const recipient = {
|
||||||
|
id: 1,
|
||||||
|
email: 'to@example.com',
|
||||||
|
name: 'Recipient1',
|
||||||
|
defaultRecipient: false,
|
||||||
|
isEditing: false
|
||||||
|
};
|
||||||
|
service.createRecipient(recipient).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients$/), recipient);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for updateRecipient', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of({}));
|
||||||
|
const recipient = {
|
||||||
|
id: 1,
|
||||||
|
email: 'to@example.com',
|
||||||
|
name: 'Recipient1',
|
||||||
|
defaultRecipient: false,
|
||||||
|
isEditing: false
|
||||||
|
};
|
||||||
|
service.updateRecipient(recipient).subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1$/), recipient);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for deleteRecipient', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteRecipient(1).subscribe();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for setDefaultRecipient', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||||
|
service.setDefaultRecipient(1).subscribe();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1\/set-default$/), {});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {of, throwError} from 'rxjs';
|
||||||
|
import {EmailService} from './email.service';
|
||||||
|
|
||||||
|
describe('EmailService', () => {
|
||||||
|
let service: EmailService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
post: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
EmailService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(EmailService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should email book', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(void 0));
|
||||||
|
const req = {bookId: 1, providerId: 2, recipientId: 3};
|
||||||
|
service.emailBook(req).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('/api/v2/email/book'),
|
||||||
|
req
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should email book quick', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(void 0));
|
||||||
|
service.emailBookQuick(42).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('/api/v2/email/book/42'),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle error for emailBook', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.emailBook({bookId: 1, providerId: 2, recipientId: 3}).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle error for emailBookQuick', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.emailBookQuick(42).subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('EmailService - API Contract Tests', () => {
|
||||||
|
let service: EmailService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
post: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
EmailService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(EmailService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for emailBook', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(void 0));
|
||||||
|
const req = {bookId: 1, providerId: 2, recipientId: 3};
|
||||||
|
service.emailBook(req).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v2\/email\/book$/),
|
||||||
|
req
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for emailBookQuick', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(void 0));
|
||||||
|
service.emailBookQuick(99).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v2\/email\/book\/99$/),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should require all fields for emailBook request', () => {
|
||||||
|
const req = {bookId: 1, providerId: 2, recipientId: 3};
|
||||||
|
expect(req).toHaveProperty('bookId');
|
||||||
|
expect(req).toHaveProperty('providerId');
|
||||||
|
expect(req).toHaveProperty('recipientId');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
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 {OpdsService, OpdsUserV2, OpdsUserV2CreateRequest, OpdsSortOrder} from './opds.service';
|
||||||
|
|
||||||
|
describe('OpdsService', () => {
|
||||||
|
let service: OpdsService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
const mockOpdsUser: OpdsUserV2 = {
|
||||||
|
id: 1,
|
||||||
|
userId: 2,
|
||||||
|
username: 'opdsuser',
|
||||||
|
sortOrder: 'TITLE_ASC'
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
patch: vi.fn(),
|
||||||
|
delete: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
OpdsService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(OpdsService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get OPDS users', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockOpdsUser]));
|
||||||
|
service.getUser().subscribe(users => {
|
||||||
|
expect(users).toEqual([mockOpdsUser]);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create OPDS user', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(mockOpdsUser));
|
||||||
|
const req: OpdsUserV2CreateRequest = {username: 'opdsuser', password: 'pass', sortOrder: 'TITLE_ASC'};
|
||||||
|
service.createUser(req).subscribe(user => {
|
||||||
|
expect(user).toEqual(mockOpdsUser);
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update OPDS user sortOrder', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of(mockOpdsUser));
|
||||||
|
service.updateUser(1, 'TITLE_DESC').subscribe(user => {
|
||||||
|
expect(user).toEqual(mockOpdsUser);
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/1'), {sortOrder: 'TITLE_DESC'});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delete OPDS credential', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteCredential(1).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle error on getUser', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service.getUser().subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('OpdsService - API Contract Tests', () => {
|
||||||
|
let service: OpdsService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
patch: vi.fn(),
|
||||||
|
delete: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
OpdsService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(OpdsService));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('OpdsUserV2 interface contract', () => {
|
||||||
|
it('should validate all required OpdsUserV2 fields exist', () => {
|
||||||
|
const requiredFields: (keyof OpdsUserV2)[] = ['id', 'userId', 'username'];
|
||||||
|
const mockResponse: OpdsUserV2 = {
|
||||||
|
id: 1,
|
||||||
|
userId: 2,
|
||||||
|
username: 'opdsuser',
|
||||||
|
sortOrder: 'TITLE_ASC'
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockResponse]));
|
||||||
|
service.getUser().subscribe(users => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(users[0]).toHaveProperty(field);
|
||||||
|
expect(users[0][field]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate OpdsSortOrder enum values', () => {
|
||||||
|
const validValues: OpdsSortOrder[] = [
|
||||||
|
'RECENT', 'TITLE_ASC', 'TITLE_DESC', 'AUTHOR_ASC', 'AUTHOR_DESC',
|
||||||
|
'SERIES_ASC', 'SERIES_DESC', 'RATING_ASC', 'RATING_DESC'
|
||||||
|
];
|
||||||
|
validValues.forEach(val => {
|
||||||
|
expect(validValues).toContain(val);
|
||||||
|
});
|
||||||
|
expect(validValues).toHaveLength(9);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('HTTP endpoint contract', () => {
|
||||||
|
it('should call correct endpoint for getUser', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([]));
|
||||||
|
service.getUser().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/opds-users$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for createUser', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of({}));
|
||||||
|
const req: OpdsUserV2CreateRequest = {username: 'a', password: 'b'};
|
||||||
|
service.createUser(req).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v2\/opds-users$/),
|
||||||
|
req
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for updateUser', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of({}));
|
||||||
|
service.updateUser(42, 'AUTHOR_DESC').subscribe();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v2\/opds-users\/42$/),
|
||||||
|
{sortOrder: 'AUTHOR_DESC'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for deleteCredential', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteCredential(99).subscribe();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/opds-users\/99$/));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Request payload contract', () => {
|
||||||
|
it('should send OpdsUserV2CreateRequest with correct structure', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of({}));
|
||||||
|
const req: OpdsUserV2CreateRequest = {username: 'x', password: 'y', sortOrder: 'RATING_DESC'};
|
||||||
|
service.createUser(req).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
req
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should send updateUser payload with correct structure', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of({}));
|
||||||
|
service.updateUser(5, 'SERIES_ASC').subscribe();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
{sortOrder: 'SERIES_ASC'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Response type contract', () => {
|
||||||
|
it('should expect OpdsUserV2 array from getUser', () => {
|
||||||
|
const mockUsers: OpdsUserV2[] = [{
|
||||||
|
id: 1,
|
||||||
|
userId: 2,
|
||||||
|
username: 'opdsuser'
|
||||||
|
}];
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockUsers));
|
||||||
|
service.getUser().subscribe(users => {
|
||||||
|
expect(Array.isArray(users)).toBe(true);
|
||||||
|
expect(users[0]).toHaveProperty('id');
|
||||||
|
expect(users[0]).toHaveProperty('username');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect OpdsUserV2 from createUser', () => {
|
||||||
|
const mockUser: OpdsUserV2 = {
|
||||||
|
id: 2,
|
||||||
|
userId: 3,
|
||||||
|
username: 'created'
|
||||||
|
};
|
||||||
|
httpClientMock.post.mockReturnValue(of(mockUser));
|
||||||
|
service.createUser({username: 'created', password: 'pw'}).subscribe(user => {
|
||||||
|
expect(user).toHaveProperty('id');
|
||||||
|
expect(user).toHaveProperty('username');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect OpdsUserV2 from updateUser', () => {
|
||||||
|
const mockUser: OpdsUserV2 = {
|
||||||
|
id: 3,
|
||||||
|
userId: 4,
|
||||||
|
username: 'updated'
|
||||||
|
};
|
||||||
|
httpClientMock.patch.mockReturnValue(of(mockUser));
|
||||||
|
service.updateUser(3, 'RECENT').subscribe(user => {
|
||||||
|
expect(user).toHaveProperty('id');
|
||||||
|
expect(user).toHaveProperty('username');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect void from deleteCredential', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteCredential(4).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -11,10 +11,6 @@ export interface OpdsUserV2CreateRequest {
|
|||||||
sortOrder?: OpdsSortOrder;
|
sortOrder?: OpdsSortOrder;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OpdsUserV2UpdateRequest {
|
|
||||||
sortOrder: OpdsSortOrder;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OpdsUserV2 {
|
export interface OpdsUserV2 {
|
||||||
id: number;
|
id: number;
|
||||||
userId: number;
|
userId: number;
|
||||||
@@ -39,7 +35,7 @@ export class OpdsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
updateUser(id: number, sortOrder: OpdsSortOrder): Observable<OpdsUserV2> {
|
updateUser(id: number, sortOrder: OpdsSortOrder): Observable<OpdsUserV2> {
|
||||||
return this.http.patch<OpdsUserV2>(`${this.baseUrl}/${id}`, { sortOrder });
|
return this.http.patch<OpdsUserV2>(`${this.baseUrl}/${id}`, {sortOrder});
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteCredential(id: number): Observable<void> {
|
deleteCredential(id: number): Observable<void> {
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import {Component, inject, Input} from '@angular/core';
|
import {Component, inject, Input} from '@angular/core';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrollMode, UserSettings} from '../../user-management/user.service';
|
import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrollMode, UserSettings} from '../../user-management/user.service';
|
||||||
import {ReaderPreferencesService} from '../reader-preferences-service';
|
import {ReaderPreferencesService} from '../reader-preferences.service';
|
||||||
import {TooltipModule} from 'primeng/tooltip';
|
import {TooltipModule} from 'primeng/tooltip';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {ReaderPreferencesService} from '../reader-preferences-service';
|
import {ReaderPreferencesService} from '../reader-preferences.service';
|
||||||
import {UserSettings} from '../../user-management/user.service';
|
import {UserSettings} from '../../user-management/user.service';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {CustomFontService} from '../../../../shared/service/custom-font.service';
|
import {CustomFontService} from '../../../../shared/service/custom-font.service';
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
import {Component, inject, Input} from '@angular/core';
|
import {Component, inject, Input} from '@angular/core';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {ReaderPreferencesService} from '../reader-preferences-service';
|
import {ReaderPreferencesService} from '../reader-preferences.service';
|
||||||
import {PageSpread, UserSettings} from '../../user-management/user.service';
|
import {PageSpread, UserSettings} from '../../user-management/user.service';
|
||||||
import {TooltipModule} from 'primeng/tooltip';
|
import {TooltipModule} from 'primeng/tooltip';
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ import {filter, takeUntil} from 'rxjs/operators';
|
|||||||
import {Observable, Subject} from 'rxjs';
|
import {Observable, Subject} from 'rxjs';
|
||||||
import {TooltipModule} from 'primeng/tooltip';
|
import {TooltipModule} from 'primeng/tooltip';
|
||||||
import {UserService, UserSettings, UserState} from '../user-management/user.service';
|
import {UserService, UserSettings, UserState} from '../user-management/user.service';
|
||||||
import {ReaderPreferencesService} from './reader-preferences-service';
|
import {ReaderPreferencesService} from './reader-preferences.service';
|
||||||
import {EpubReaderPreferencesComponent} from './epub-reader-preferences/epub-reader-preferences-component';
|
import {EpubReaderPreferencesComponent} from './epub-reader-preferences/epub-reader-preferences-component';
|
||||||
import {PdfReaderPreferencesComponent} from './pdf-reader-preferences/pdf-reader-preferences-component';
|
import {PdfReaderPreferencesComponent} from './pdf-reader-preferences/pdf-reader-preferences-component';
|
||||||
import {CbxReaderPreferencesComponent} from './cbx-reader-preferences/cbx-reader-preferences-component';
|
import {CbxReaderPreferencesComponent} from './cbx-reader-preferences/cbx-reader-preferences-component';
|
||||||
|
|||||||
+219
@@ -0,0 +1,219 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||||
|
import {ReaderPreferencesService} from './reader-preferences.service';
|
||||||
|
import {CbxFitMode, CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode, User, UserService} from '../user-management/user.service';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {of, Subject} from 'rxjs';
|
||||||
|
|
||||||
|
const mockUser: User = {
|
||||||
|
id: 1,
|
||||||
|
username: 'testuser',
|
||||||
|
name: 'Test User',
|
||||||
|
email: 'test@example.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: true,
|
||||||
|
canUpload: true,
|
||||||
|
canDownload: true,
|
||||||
|
canEmailBook: true,
|
||||||
|
canDeleteBook: true,
|
||||||
|
canEditMetadata: true,
|
||||||
|
canManageLibrary: true,
|
||||||
|
canManageMetadataConfig: true,
|
||||||
|
canSyncKoReader: true,
|
||||||
|
canSyncKobo: true,
|
||||||
|
canAccessOpds: true,
|
||||||
|
canAccessBookdrop: true,
|
||||||
|
canAccessLibraryStats: true,
|
||||||
|
canAccessUserStats: true,
|
||||||
|
canAccessTaskManager: true,
|
||||||
|
canManageEmailConfig: true,
|
||||||
|
canManageGlobalPreferences: true,
|
||||||
|
canManageIcons: true,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: true,
|
||||||
|
canBulkCustomFetchMetadata: true,
|
||||||
|
canBulkEditMetadata: true,
|
||||||
|
canBulkRegenerateCover: true,
|
||||||
|
canMoveOrganizeFiles: true,
|
||||||
|
canBulkLockUnlockMetadata: true
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {
|
||||||
|
pageSpread: CbxPageSpread.EVEN,
|
||||||
|
pageViewMode: CbxPageViewMode.SINGLE_PAGE,
|
||||||
|
fitMode: CbxFitMode.ACTUAL_SIZE
|
||||||
|
},
|
||||||
|
newPdfReaderSetting: {
|
||||||
|
pageSpread: PdfPageSpread.EVEN,
|
||||||
|
pageViewMode: PdfPageViewMode.SINGLE_PAGE
|
||||||
|
},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and',
|
||||||
|
filterSortingMode: 'alphabetical',
|
||||||
|
metadataCenterViewMode: 'route',
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {
|
||||||
|
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false},
|
||||||
|
overrides: []
|
||||||
|
},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('ReaderPreferencesService', () => {
|
||||||
|
let service: ReaderPreferencesService;
|
||||||
|
let userServiceMock: any;
|
||||||
|
let messageServiceMock: any;
|
||||||
|
let destroy$: Subject<void>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
destroy$ = new Subject<void>();
|
||||||
|
userServiceMock = {
|
||||||
|
userState$: of({user: mockUser, loaded: true}),
|
||||||
|
updateUserSetting: vi.fn()
|
||||||
|
};
|
||||||
|
messageServiceMock = {
|
||||||
|
add: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
ReaderPreferencesService,
|
||||||
|
{provide: UserService, useValue: userServiceMock},
|
||||||
|
{provide: MessageService, useValue: messageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(ReaderPreferencesService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be created', () => {
|
||||||
|
expect(service).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should set currentUser from userService', () => {
|
||||||
|
// @ts-ignore
|
||||||
|
expect(service.currentUser).toEqual(mockUser);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update preference and call updateUserSetting', () => {
|
||||||
|
const path = ['cbxReaderSetting', 'fitMode'];
|
||||||
|
const value = CbxFitMode.FIT_PAGE;
|
||||||
|
service['currentUser'] = JSON.parse(JSON.stringify(mockUser));
|
||||||
|
service.updatePreference(path, value);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||||
|
mockUser.id,
|
||||||
|
'cbxReaderSetting',
|
||||||
|
expect.objectContaining({fitMode: value})
|
||||||
|
);
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({severity: 'success'})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update nested preference', () => {
|
||||||
|
const path = ['entityViewPreferences', 'global', 'sortKey'];
|
||||||
|
const value = 'title';
|
||||||
|
service['currentUser'] = JSON.parse(JSON.stringify(mockUser));
|
||||||
|
service.updatePreference(path, value);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||||
|
mockUser.id,
|
||||||
|
'entityViewPreferences',
|
||||||
|
expect.objectContaining({
|
||||||
|
global: expect.objectContaining({sortKey: value})
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not update if currentUser is null', () => {
|
||||||
|
service['currentUser'] = null;
|
||||||
|
service.updatePreference(['cbxReaderSetting', 'fitMode'], CbxFitMode.FIT_PAGE);
|
||||||
|
expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled();
|
||||||
|
expect(messageServiceMock.add).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should clean up on destroy', () => {
|
||||||
|
const spy = vi.spyOn(service['destroy$'], 'next');
|
||||||
|
service.ngOnDestroy();
|
||||||
|
expect(spy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ReaderPreferencesService - API Contract Tests', () => {
|
||||||
|
let service: ReaderPreferencesService;
|
||||||
|
let userServiceMock: any;
|
||||||
|
let messageServiceMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
userServiceMock = {
|
||||||
|
userState$: of({user: mockUser, loaded: true}),
|
||||||
|
updateUserSetting: vi.fn()
|
||||||
|
};
|
||||||
|
messageServiceMock = {
|
||||||
|
add: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
ReaderPreferencesService,
|
||||||
|
{provide: UserService, useValue: userServiceMock},
|
||||||
|
{provide: MessageService, useValue: messageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(ReaderPreferencesService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call updateUserSetting with correct arguments for root-level setting', () => {
|
||||||
|
const path = ['koReaderEnabled'];
|
||||||
|
const value = true;
|
||||||
|
service['currentUser'] = JSON.parse(JSON.stringify(mockUser));
|
||||||
|
service.updatePreference(path, value);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||||
|
mockUser.id,
|
||||||
|
'koReaderEnabled',
|
||||||
|
value
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call updateUserSetting with correct arguments for nested setting', () => {
|
||||||
|
const path = ['pdfReaderSetting', 'pageZoom'];
|
||||||
|
const value = '150%';
|
||||||
|
service['currentUser'] = JSON.parse(JSON.stringify(mockUser));
|
||||||
|
service.updatePreference(path, value);
|
||||||
|
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||||
|
mockUser.id,
|
||||||
|
'pdfReaderSetting',
|
||||||
|
expect.objectContaining({pageZoom: value})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should show success message after updating preference', () => {
|
||||||
|
const path = ['epubReaderSetting', 'fontSize'];
|
||||||
|
const value = 18;
|
||||||
|
service['currentUser'] = JSON.parse(JSON.stringify(mockUser));
|
||||||
|
service.updatePreference(path, value);
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Preferences Updated'
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not throw if path is empty', () => {
|
||||||
|
service['currentUser'] = JSON.parse(JSON.stringify(mockUser));
|
||||||
|
expect(() => service.updatePreference([], 'value')).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||||
|
import {of, throwError} from 'rxjs';
|
||||||
|
import {TaskHelperService} from './task-helper.service';
|
||||||
|
import {TaskCreateRequest, TaskService, TaskType} from './task.service';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
|
||||||
|
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||||
|
|
||||||
|
describe('TaskHelperService', () => {
|
||||||
|
let service: TaskHelperService;
|
||||||
|
let taskServiceMock: any;
|
||||||
|
let messageServiceMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
taskServiceMock = {
|
||||||
|
startTask: vi.fn()
|
||||||
|
};
|
||||||
|
messageServiceMock = {
|
||||||
|
add: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
TaskHelperService,
|
||||||
|
{provide: TaskService, useValue: taskServiceMock},
|
||||||
|
{provide: MessageService, useValue: messageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(TaskHelperService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should schedule metadata refresh and show success message', () => {
|
||||||
|
taskServiceMock.startTask.mockReturnValue(of({}));
|
||||||
|
const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1, 2]};
|
||||||
|
service.refreshMetadataTask(options).subscribe(result => {
|
||||||
|
expect(result).toEqual({success: true});
|
||||||
|
expect(taskServiceMock.startTask).toHaveBeenCalledWith({
|
||||||
|
taskType: TaskType.REFRESH_METADATA_MANUAL,
|
||||||
|
options
|
||||||
|
});
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Metadata Update Scheduled'
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should show error message if task already running (409)', () => {
|
||||||
|
taskServiceMock.startTask.mockReturnValue(throwError(() => ({status: 409})));
|
||||||
|
const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1]};
|
||||||
|
service.refreshMetadataTask(options).subscribe(result => {
|
||||||
|
expect(result).toEqual({success: false});
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Task Already Running'
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should show generic error message for other errors', () => {
|
||||||
|
taskServiceMock.startTask.mockReturnValue(throwError(() => ({status: 500})));
|
||||||
|
const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1]};
|
||||||
|
service.refreshMetadataTask(options).subscribe(result => {
|
||||||
|
expect(result).toEqual({success: false});
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Metadata Update Failed'
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TaskHelperService - API Contract Tests', () => {
|
||||||
|
let service: TaskHelperService;
|
||||||
|
let taskServiceMock: any;
|
||||||
|
let messageServiceMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
taskServiceMock = {
|
||||||
|
startTask: vi.fn()
|
||||||
|
};
|
||||||
|
messageServiceMock = {
|
||||||
|
add: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
TaskHelperService,
|
||||||
|
{provide: TaskService, useValue: taskServiceMock},
|
||||||
|
{provide: MessageService, useValue: messageServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(TaskHelperService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should send TaskCreateRequest with correct structure', () => {
|
||||||
|
taskServiceMock.startTask.mockReturnValue(of({}));
|
||||||
|
const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1, 2, 3]};
|
||||||
|
service.refreshMetadataTask(options).subscribe(() => {
|
||||||
|
const req: TaskCreateRequest = taskServiceMock.startTask.mock.calls[0][0];
|
||||||
|
expect(req).toHaveProperty('taskType', TaskType.REFRESH_METADATA_MANUAL);
|
||||||
|
expect(req).toHaveProperty('options', options);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect {success: true} on success', () => {
|
||||||
|
taskServiceMock.startTask.mockReturnValue(of({}));
|
||||||
|
service.refreshMetadataTask({refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}).subscribe(result => {
|
||||||
|
expect(result).toEqual({success: true});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect {success: false} on error', () => {
|
||||||
|
taskServiceMock.startTask.mockReturnValue(throwError(() => ({status: 409})));
|
||||||
|
service.refreshMetadataTask({refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}).subscribe(result => {
|
||||||
|
expect(result).toEqual({success: false});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call MessageService.add with correct contract', () => {
|
||||||
|
taskServiceMock.startTask.mockReturnValue(of({}));
|
||||||
|
service.refreshMetadataTask({refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}).subscribe(() => {
|
||||||
|
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
severity: 'success',
|
||||||
|
summary: expect.any(String),
|
||||||
|
detail: expect.any(String)
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
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 {
|
||||||
|
TaskService,
|
||||||
|
TaskType,
|
||||||
|
TASK_TYPE_CONFIG,
|
||||||
|
TaskCreateRequest,
|
||||||
|
TaskCreateResponse,
|
||||||
|
TaskStatusResponse,
|
||||||
|
TaskStatus,
|
||||||
|
TaskCancelResponse,
|
||||||
|
TaskInfo,
|
||||||
|
TaskHistory,
|
||||||
|
CronConfig,
|
||||||
|
TaskCronConfigRequest,
|
||||||
|
TaskProgressPayload,
|
||||||
|
MetadataReplaceMode
|
||||||
|
} from './task.service';
|
||||||
|
|
||||||
|
describe('TaskService', () => {
|
||||||
|
let service: TaskService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
patch: vi.fn(),
|
||||||
|
delete: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
TaskService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(TaskService));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get available tasks', () => {
|
||||||
|
const mockTasks: TaskInfo[] = [
|
||||||
|
{
|
||||||
|
taskType: TaskType.REFRESH_LIBRARY_METADATA,
|
||||||
|
name: 'Refresh Metadata',
|
||||||
|
description: 'desc',
|
||||||
|
parallel: false,
|
||||||
|
async: true,
|
||||||
|
cronSupported: true,
|
||||||
|
cronConfig: null
|
||||||
|
}
|
||||||
|
];
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockTasks));
|
||||||
|
service.getAvailableTasks().subscribe(tasks => {
|
||||||
|
expect(tasks).toEqual(mockTasks);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v1/tasks'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should start a task', () => {
|
||||||
|
const req: TaskCreateRequest = {taskType: TaskType.REFRESH_LIBRARY_METADATA};
|
||||||
|
const resp: TaskCreateResponse = {id: '1', type: TaskType.REFRESH_LIBRARY_METADATA, status: TaskStatus.ACCEPTED};
|
||||||
|
httpClientMock.post.mockReturnValue(of(resp));
|
||||||
|
service.startTask(req).subscribe(result => {
|
||||||
|
expect(result).toEqual(resp);
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/start'), req);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get latest tasks for each type', () => {
|
||||||
|
const resp: TaskStatusResponse = {taskHistories: []};
|
||||||
|
httpClientMock.get.mockReturnValue(of(resp));
|
||||||
|
service.getLatestTasksForEachType().subscribe(result => {
|
||||||
|
expect(result).toEqual(resp);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/last'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should cancel a task', () => {
|
||||||
|
const resp: TaskCancelResponse = {taskId: '1', cancelled: true, message: 'Cancelled'};
|
||||||
|
httpClientMock.delete.mockReturnValue(of(resp));
|
||||||
|
service.cancelTask('1').subscribe(result => {
|
||||||
|
expect(result).toEqual(resp);
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1/cancel'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update cron config', () => {
|
||||||
|
const req: TaskCronConfigRequest = {cronExpression: '* * * * *', enabled: true};
|
||||||
|
const resp: CronConfig = {
|
||||||
|
id: 1,
|
||||||
|
taskType: TaskType.REFRESH_LIBRARY_METADATA,
|
||||||
|
cronExpression: '* * * * *',
|
||||||
|
enabled: true,
|
||||||
|
options: null,
|
||||||
|
createdAt: null,
|
||||||
|
updatedAt: null
|
||||||
|
};
|
||||||
|
httpClientMock.patch.mockReturnValue(of(resp));
|
||||||
|
service.updateCronConfig(TaskType.REFRESH_LIBRARY_METADATA, req).subscribe(result => {
|
||||||
|
expect(result).toEqual(resp);
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining(`/${TaskType.REFRESH_LIBRARY_METADATA}/cron`), req);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle task progress subject', () => {
|
||||||
|
const progress: TaskProgressPayload = {
|
||||||
|
taskId: '1',
|
||||||
|
taskType: TaskType.REFRESH_LIBRARY_METADATA,
|
||||||
|
message: 'Running',
|
||||||
|
progress: 50,
|
||||||
|
taskStatus: TaskStatus.IN_PROGRESS
|
||||||
|
};
|
||||||
|
let emitted: TaskProgressPayload | null = null;
|
||||||
|
service.taskProgress$.subscribe(val => emitted = val);
|
||||||
|
service.handleTaskProgress(progress);
|
||||||
|
expect(emitted).toEqual(progress);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TaskService - API Contract Tests', () => {
|
||||||
|
let service: TaskService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
patch: vi.fn(),
|
||||||
|
delete: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
TaskService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(TaskService));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TaskInfo interface contract', () => {
|
||||||
|
it('should validate all required TaskInfo fields exist', () => {
|
||||||
|
const requiredFields: (keyof TaskInfo)[] = [
|
||||||
|
'taskType', 'name', 'description', 'parallel', 'async', 'cronSupported', 'cronConfig'
|
||||||
|
];
|
||||||
|
const mockResponse: TaskInfo = {
|
||||||
|
taskType: TaskType.REFRESH_LIBRARY_METADATA,
|
||||||
|
name: 'Refresh',
|
||||||
|
description: 'desc',
|
||||||
|
parallel: false,
|
||||||
|
async: true,
|
||||||
|
cronSupported: true,
|
||||||
|
cronConfig: null
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockResponse]));
|
||||||
|
service.getAvailableTasks().subscribe(tasks => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(tasks[0]).toHaveProperty(field);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TaskHistory interface contract', () => {
|
||||||
|
it('should validate all required TaskHistory fields exist', () => {
|
||||||
|
const requiredFields: (keyof TaskHistory)[] = [
|
||||||
|
'id', 'type', 'status', 'progressPercentage', 'message', 'createdAt', 'updatedAt', 'completedAt'
|
||||||
|
];
|
||||||
|
const mockHistory: TaskHistory = {
|
||||||
|
id: '1',
|
||||||
|
type: TaskType.REFRESH_LIBRARY_METADATA,
|
||||||
|
status: TaskStatus.COMPLETED,
|
||||||
|
progressPercentage: 100,
|
||||||
|
message: 'Done',
|
||||||
|
createdAt: 'now',
|
||||||
|
updatedAt: 'now',
|
||||||
|
completedAt: 'now'
|
||||||
|
};
|
||||||
|
httpClientMock.get.mockReturnValue(of({taskHistories: [mockHistory]}));
|
||||||
|
service.getLatestTasksForEachType().subscribe(resp => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(resp.taskHistories[0]).toHaveProperty(field);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Enum value contract', () => {
|
||||||
|
it('should validate TaskType enum values', () => {
|
||||||
|
const values = Object.values(TaskType);
|
||||||
|
expect(values).toContain('CLEAR_CBX_CACHE');
|
||||||
|
expect(values).toContain('REFRESH_LIBRARY_METADATA');
|
||||||
|
expect(values).toContain('REFRESH_METADATA_MANUAL');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate TaskStatus enum values', () => {
|
||||||
|
const values = Object.values(TaskStatus);
|
||||||
|
expect(values).toContain('ACCEPTED');
|
||||||
|
expect(values).toContain('IN_PROGRESS');
|
||||||
|
expect(values).toContain('COMPLETED');
|
||||||
|
expect(values).toContain('FAILED');
|
||||||
|
expect(values).toContain('CANCELLED');
|
||||||
|
expect(values).toContain('PENDING');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate MetadataReplaceMode enum values', () => {
|
||||||
|
const values = Object.values(MetadataReplaceMode);
|
||||||
|
expect(values).toContain('REPLACE_ALL');
|
||||||
|
expect(values).toContain('REPLACE_MISSING');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('HTTP endpoint contract', () => {
|
||||||
|
it('should call correct endpoint for getAvailableTasks', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([]));
|
||||||
|
service.getAvailableTasks().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for startTask', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of({}));
|
||||||
|
const req: TaskCreateRequest = {taskType: TaskType.CLEAR_CBX_CACHE};
|
||||||
|
service.startTask(req).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks\/start$/), req);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for getLatestTasksForEachType', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of({}));
|
||||||
|
service.getLatestTasksForEachType().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks\/last$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for cancelTask', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of({}));
|
||||||
|
service.cancelTask('abc').subscribe();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks\/abc\/cancel$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for updateCronConfig', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of({}));
|
||||||
|
const req: TaskCronConfigRequest = {enabled: true};
|
||||||
|
service.updateCronConfig(TaskType.CLEAR_PDF_CACHE, req).subscribe();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(new RegExp(`/api/v1/tasks/${TaskType.CLEAR_PDF_CACHE}/cron$`)), req);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Request payload contract', () => {
|
||||||
|
it('should send TaskCreateRequest with correct structure', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of({}));
|
||||||
|
const req: TaskCreateRequest = {taskType: TaskType.CLEAR_CBX_CACHE, options: {metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL}};
|
||||||
|
service.startTask(req).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should send TaskCronConfigRequest with correct structure', () => {
|
||||||
|
httpClientMock.patch.mockReturnValue(of({}));
|
||||||
|
const req: TaskCronConfigRequest = {cronExpression: '0 0 * * *', enabled: false};
|
||||||
|
service.updateCronConfig(TaskType.CLEAR_CBX_CACHE, req).subscribe();
|
||||||
|
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.any(String), req);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Response type contract', () => {
|
||||||
|
it('should expect TaskInfo[] from getAvailableTasks', () => {
|
||||||
|
const mock: TaskInfo[] = [{
|
||||||
|
taskType: TaskType.CLEAR_CBX_CACHE,
|
||||||
|
name: 'Clear CBX',
|
||||||
|
description: 'desc',
|
||||||
|
parallel: false,
|
||||||
|
async: false,
|
||||||
|
cronSupported: false,
|
||||||
|
cronConfig: null
|
||||||
|
}];
|
||||||
|
httpClientMock.get.mockReturnValue(of(mock));
|
||||||
|
service.getAvailableTasks().subscribe(tasks => {
|
||||||
|
expect(Array.isArray(tasks)).toBe(true);
|
||||||
|
expect(tasks[0]).toHaveProperty('taskType');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect TaskCreateResponse from startTask', () => {
|
||||||
|
const resp: TaskCreateResponse = {id: '1', type: TaskType.CLEAR_CBX_CACHE, status: TaskStatus.ACCEPTED};
|
||||||
|
httpClientMock.post.mockReturnValue(of(resp));
|
||||||
|
service.startTask({taskType: TaskType.CLEAR_CBX_CACHE}).subscribe(result => {
|
||||||
|
expect(result).toHaveProperty('id');
|
||||||
|
expect(result).toHaveProperty('type');
|
||||||
|
expect(result).toHaveProperty('status');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect TaskStatusResponse from getLatestTasksForEachType', () => {
|
||||||
|
const resp: TaskStatusResponse = {taskHistories: []};
|
||||||
|
httpClientMock.get.mockReturnValue(of(resp));
|
||||||
|
service.getLatestTasksForEachType().subscribe(result => {
|
||||||
|
expect(result).toHaveProperty('taskHistories');
|
||||||
|
expect(Array.isArray(result.taskHistories)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect TaskCancelResponse from cancelTask', () => {
|
||||||
|
const resp: TaskCancelResponse = {taskId: '1', cancelled: true, message: 'msg'};
|
||||||
|
httpClientMock.delete.mockReturnValue(of(resp));
|
||||||
|
service.cancelTask('1').subscribe(result => {
|
||||||
|
expect(result).toHaveProperty('taskId');
|
||||||
|
expect(result).toHaveProperty('cancelled');
|
||||||
|
expect(result).toHaveProperty('message');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect CronConfig from updateCronConfig', () => {
|
||||||
|
const resp: CronConfig = {
|
||||||
|
id: 1,
|
||||||
|
taskType: TaskType.CLEAR_CBX_CACHE,
|
||||||
|
cronExpression: '* * * * *',
|
||||||
|
enabled: true,
|
||||||
|
options: null,
|
||||||
|
createdAt: null,
|
||||||
|
updatedAt: null
|
||||||
|
};
|
||||||
|
httpClientMock.patch.mockReturnValue(of(resp));
|
||||||
|
service.updateCronConfig(TaskType.CLEAR_CBX_CACHE, {enabled: true}).subscribe(result => {
|
||||||
|
expect(result).toHaveProperty('id');
|
||||||
|
expect(result).toHaveProperty('taskType');
|
||||||
|
expect(result).toHaveProperty('enabled');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,936 @@
|
|||||||
|
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 {
|
||||||
|
CbxFitMode,
|
||||||
|
CbxPageSpread,
|
||||||
|
CbxPageViewMode,
|
||||||
|
PdfPageSpread,
|
||||||
|
PdfPageViewMode,
|
||||||
|
User,
|
||||||
|
UserService,
|
||||||
|
UserUpdateRequest
|
||||||
|
} from './user.service';
|
||||||
|
import {AuthService} from '../../../shared/service/auth.service';
|
||||||
|
|
||||||
|
describe('UserService', () => {
|
||||||
|
let service: UserService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
let authServiceMock: any;
|
||||||
|
|
||||||
|
const mockUser: User = {
|
||||||
|
id: 1,
|
||||||
|
username: 'testuser',
|
||||||
|
name: 'Test User',
|
||||||
|
email: 'test@example.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: true,
|
||||||
|
canUpload: true,
|
||||||
|
canDownload: true,
|
||||||
|
canEmailBook: true,
|
||||||
|
canDeleteBook: true,
|
||||||
|
canEditMetadata: true,
|
||||||
|
canManageLibrary: true,
|
||||||
|
canManageMetadataConfig: true,
|
||||||
|
canSyncKoReader: true,
|
||||||
|
canSyncKobo: true,
|
||||||
|
canAccessOpds: true,
|
||||||
|
canAccessBookdrop: true,
|
||||||
|
canAccessLibraryStats: true,
|
||||||
|
canAccessUserStats: true,
|
||||||
|
canAccessTaskManager: true,
|
||||||
|
canManageEmailConfig: true,
|
||||||
|
canManageGlobalPreferences: true,
|
||||||
|
canManageIcons: true,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: true,
|
||||||
|
canBulkCustomFetchMetadata: true,
|
||||||
|
canBulkEditMetadata: true,
|
||||||
|
canBulkRegenerateCover: true,
|
||||||
|
canMoveOrganizeFiles: true,
|
||||||
|
canBulkLockUnlockMetadata: true
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {
|
||||||
|
pageSpread: CbxPageSpread.EVEN,
|
||||||
|
pageViewMode: CbxPageViewMode.SINGLE_PAGE,
|
||||||
|
fitMode: CbxFitMode.ACTUAL_SIZE
|
||||||
|
},
|
||||||
|
newPdfReaderSetting: {
|
||||||
|
pageSpread: PdfPageSpread.EVEN,
|
||||||
|
pageViewMode: PdfPageViewMode.SINGLE_PAGE
|
||||||
|
},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and',
|
||||||
|
filterSortingMode: 'alphabetical',
|
||||||
|
metadataCenterViewMode: 'route',
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {
|
||||||
|
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false},
|
||||||
|
overrides: []
|
||||||
|
},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
delete: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
authServiceMock = {
|
||||||
|
token$: of('token')
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
UserService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock},
|
||||||
|
{provide: AuthService, useValue: authServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
|
||||||
|
service = runInInjectionContext(
|
||||||
|
injector,
|
||||||
|
() => TestBed.inject(UserService)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should initialize with default state', () => {
|
||||||
|
expect(service.userStateSubject.value).toEqual({
|
||||||
|
user: null,
|
||||||
|
loaded: false,
|
||||||
|
error: null
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should set initial user', () => {
|
||||||
|
service.setInitialUser(mockUser);
|
||||||
|
expect(service.userStateSubject.value.user).toEqual(mockUser);
|
||||||
|
expect(service.userStateSubject.value.loaded).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get current user', () => {
|
||||||
|
service.setInitialUser(mockUser);
|
||||||
|
expect(service.getCurrentUser()).toEqual(mockUser);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fetch myself and update state', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockUser));
|
||||||
|
service['fetchMyself']().subscribe(user => {
|
||||||
|
expect(user).toEqual(mockUser);
|
||||||
|
expect(service.userStateSubject.value.user).toEqual(mockUser);
|
||||||
|
expect(service.userStateSubject.value.loaded).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle fetch myself error', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||||
|
service['fetchMyself']().subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(service.userStateSubject.value.error).toBe('fail');
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get myself via getMyself()', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockUser));
|
||||||
|
service.getMyself().subscribe(user => {
|
||||||
|
expect(user).toEqual(mockUser);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/me'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create user', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(void 0));
|
||||||
|
const {id, ...userData} = mockUser;
|
||||||
|
service.createUser(userData).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should get users', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([mockUser]));
|
||||||
|
service.getUsers().subscribe(users => {
|
||||||
|
expect(users).toEqual([mockUser]);
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update user', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(mockUser));
|
||||||
|
const update: UserUpdateRequest = {name: 'New Name'};
|
||||||
|
service.updateUser(1, update).subscribe(user => {
|
||||||
|
expect(user).toEqual(mockUser);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), update);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delete user', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteUser(1).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should change user password', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.changeUserPassword(1, 'newpass').subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-user-password'), {userId: 1, newPassword: 'newpass'});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle change user password error', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'bad'}})));
|
||||||
|
service.changeUserPassword(1, 'badpass').subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('bad');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should change password', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.changePassword('old', 'new').subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-password'), {currentPassword: 'old', newPassword: 'new'});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle change password error', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||||
|
service.changePassword('old', 'bad').subscribe({
|
||||||
|
error: (err: any) => {
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
expect(err.message).toBe('fail');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should update user setting and update state', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.setInitialUser(mockUser);
|
||||||
|
service.updateUserSetting(1, 'koReaderEnabled', true);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1/settings'), {key: 'koReaderEnabled', value: true}, expect.anything());
|
||||||
|
expect(service.userStateSubject.value.user?.userSettings.koReaderEnabled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('UserService - API Contract Tests', () => {
|
||||||
|
let service: UserService;
|
||||||
|
let httpClientMock: any;
|
||||||
|
let authServiceMock: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
httpClientMock = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
delete: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
authServiceMock = {
|
||||||
|
token$: of('token')
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
UserService,
|
||||||
|
{provide: HttpClient, useValue: httpClientMock},
|
||||||
|
{provide: AuthService, useValue: authServiceMock}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const injector = TestBed.inject(EnvironmentInjector);
|
||||||
|
service = runInInjectionContext(injector, () => TestBed.inject(UserService));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('User interface contract', () => {
|
||||||
|
it('should validate all required User fields exist', () => {
|
||||||
|
const requiredFields: (keyof User)[] = [
|
||||||
|
'id', 'username', 'name', 'email', 'assignedLibraries', 'permissions', 'userSettings'
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockResponse: User = {
|
||||||
|
id: 1,
|
||||||
|
username: 'test',
|
||||||
|
name: 'Test',
|
||||||
|
email: 'test@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: false,
|
||||||
|
canUpload: false,
|
||||||
|
canDownload: false,
|
||||||
|
canEmailBook: false,
|
||||||
|
canDeleteBook: false,
|
||||||
|
canEditMetadata: false,
|
||||||
|
canManageLibrary: false,
|
||||||
|
canManageMetadataConfig: false,
|
||||||
|
canSyncKoReader: false,
|
||||||
|
canSyncKobo: false,
|
||||||
|
canAccessOpds: false,
|
||||||
|
canAccessBookdrop: false,
|
||||||
|
canAccessLibraryStats: false,
|
||||||
|
canAccessUserStats: false,
|
||||||
|
canAccessTaskManager: false,
|
||||||
|
canManageEmailConfig: false,
|
||||||
|
canManageGlobalPreferences: false,
|
||||||
|
canManageIcons: false,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: false,
|
||||||
|
canBulkCustomFetchMetadata: false,
|
||||||
|
canBulkEditMetadata: false,
|
||||||
|
canBulkRegenerateCover: false,
|
||||||
|
canMoveOrganizeFiles: false,
|
||||||
|
canBulkLockUnlockMetadata: false
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||||
|
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and',
|
||||||
|
filterSortingMode: 'alphabetical',
|
||||||
|
metadataCenterViewMode: 'route',
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||||
|
|
||||||
|
service.getMyself().subscribe(user => {
|
||||||
|
requiredFields.forEach(field => {
|
||||||
|
expect(user).toHaveProperty(field);
|
||||||
|
expect(user[field]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate all required Permission fields exist', () => {
|
||||||
|
const requiredPermissions = [
|
||||||
|
'admin', 'canUpload', 'canDownload', 'canEmailBook', 'canDeleteBook',
|
||||||
|
'canEditMetadata', 'canManageLibrary', 'canManageMetadataConfig',
|
||||||
|
'canSyncKoReader', 'canSyncKobo', 'canAccessOpds', 'canAccessBookdrop',
|
||||||
|
'canAccessLibraryStats', 'canAccessUserStats', 'canAccessTaskManager',
|
||||||
|
'canManageEmailConfig', 'canManageGlobalPreferences', 'canManageIcons',
|
||||||
|
'demoUser', 'canBulkAutoFetchMetadata', 'canBulkCustomFetchMetadata',
|
||||||
|
'canBulkEditMetadata', 'canBulkRegenerateCover', 'canMoveOrganizeFiles',
|
||||||
|
'canBulkLockUnlockMetadata'
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockResponse: User = {
|
||||||
|
id: 1,
|
||||||
|
username: 'test',
|
||||||
|
name: 'Test',
|
||||||
|
email: 'test@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: true,
|
||||||
|
canUpload: true,
|
||||||
|
canDownload: true,
|
||||||
|
canEmailBook: true,
|
||||||
|
canDeleteBook: true,
|
||||||
|
canEditMetadata: true,
|
||||||
|
canManageLibrary: true,
|
||||||
|
canManageMetadataConfig: true,
|
||||||
|
canSyncKoReader: true,
|
||||||
|
canSyncKobo: true,
|
||||||
|
canAccessOpds: true,
|
||||||
|
canAccessBookdrop: true,
|
||||||
|
canAccessLibraryStats: true,
|
||||||
|
canAccessUserStats: true,
|
||||||
|
canAccessTaskManager: true,
|
||||||
|
canManageEmailConfig: true,
|
||||||
|
canManageGlobalPreferences: true,
|
||||||
|
canManageIcons: true,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: true,
|
||||||
|
canBulkCustomFetchMetadata: true,
|
||||||
|
canBulkEditMetadata: true,
|
||||||
|
canBulkRegenerateCover: true,
|
||||||
|
canMoveOrganizeFiles: true,
|
||||||
|
canBulkLockUnlockMetadata: true
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||||
|
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and',
|
||||||
|
filterSortingMode: 'alphabetical',
|
||||||
|
metadataCenterViewMode: 'route',
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||||
|
|
||||||
|
service.getMyself().subscribe(user => {
|
||||||
|
requiredPermissions.forEach(permission => {
|
||||||
|
expect(user.permissions).toHaveProperty(permission);
|
||||||
|
expect(typeof user.permissions[permission as keyof typeof user.permissions]).toBe('boolean');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate all required UserSettings fields exist', () => {
|
||||||
|
const requiredSettings = [
|
||||||
|
'perBookSetting', 'pdfReaderSetting', 'epubReaderSetting', 'cbxReaderSetting',
|
||||||
|
'newPdfReaderSetting', 'sidebarLibrarySorting', 'sidebarShelfSorting',
|
||||||
|
'sidebarMagicShelfSorting', 'filterMode', 'filterSortingMode',
|
||||||
|
'metadataCenterViewMode', 'enableSeriesView', 'entityViewPreferences', 'koReaderEnabled'
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockResponse: User = {
|
||||||
|
id: 1,
|
||||||
|
username: 'test',
|
||||||
|
name: 'Test',
|
||||||
|
email: 'test@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: false,
|
||||||
|
canUpload: false,
|
||||||
|
canDownload: false,
|
||||||
|
canEmailBook: false,
|
||||||
|
canDeleteBook: false,
|
||||||
|
canEditMetadata: false,
|
||||||
|
canManageLibrary: false,
|
||||||
|
canManageMetadataConfig: false,
|
||||||
|
canSyncKoReader: false,
|
||||||
|
canSyncKobo: false,
|
||||||
|
canAccessOpds: false,
|
||||||
|
canAccessBookdrop: false,
|
||||||
|
canAccessLibraryStats: false,
|
||||||
|
canAccessUserStats: false,
|
||||||
|
canAccessTaskManager: false,
|
||||||
|
canManageEmailConfig: false,
|
||||||
|
canManageGlobalPreferences: false,
|
||||||
|
canManageIcons: false,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: false,
|
||||||
|
canBulkCustomFetchMetadata: false,
|
||||||
|
canBulkEditMetadata: false,
|
||||||
|
canBulkRegenerateCover: false,
|
||||||
|
canMoveOrganizeFiles: false,
|
||||||
|
canBulkLockUnlockMetadata: false
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||||
|
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and',
|
||||||
|
filterSortingMode: 'alphabetical',
|
||||||
|
metadataCenterViewMode: 'route',
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||||
|
|
||||||
|
service.getMyself().subscribe(user => {
|
||||||
|
requiredSettings.forEach(setting => {
|
||||||
|
expect(user.userSettings).toHaveProperty(setting);
|
||||||
|
expect(user.userSettings[setting as keyof typeof user.userSettings]).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns User without required id field', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
username: 'test',
|
||||||
|
name: 'Test',
|
||||||
|
email: 'test@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {},
|
||||||
|
userSettings: {}
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
|
||||||
|
service.getMyself().subscribe(user => {
|
||||||
|
expect(user).not.toHaveProperty('id');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns User without permissions', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
id: 1,
|
||||||
|
username: 'test',
|
||||||
|
name: 'Test',
|
||||||
|
email: 'test@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
userSettings: {}
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
|
||||||
|
service.getMyself().subscribe(user => {
|
||||||
|
expect(user).not.toHaveProperty('permissions');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail if API returns User without userSettings', () => {
|
||||||
|
const invalidResponse = {
|
||||||
|
id: 1,
|
||||||
|
username: 'test',
|
||||||
|
name: 'Test',
|
||||||
|
email: 'test@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {}
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||||
|
|
||||||
|
service.getMyself().subscribe(user => {
|
||||||
|
expect(user).not.toHaveProperty('userSettings');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Enum value contract', () => {
|
||||||
|
it('should validate CbxPageSpread enum values from API', () => {
|
||||||
|
const validValues = [CbxPageSpread.EVEN, CbxPageSpread.ODD];
|
||||||
|
expect(validValues).toContain(CbxPageSpread.EVEN);
|
||||||
|
expect(validValues).toContain(CbxPageSpread.ODD);
|
||||||
|
expect(Object.keys(CbxPageSpread)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate CbxPageViewMode enum values from API', () => {
|
||||||
|
const validValues = [CbxPageViewMode.SINGLE_PAGE, CbxPageViewMode.TWO_PAGE];
|
||||||
|
expect(validValues).toContain(CbxPageViewMode.SINGLE_PAGE);
|
||||||
|
expect(validValues).toContain(CbxPageViewMode.TWO_PAGE);
|
||||||
|
expect(Object.keys(CbxPageViewMode)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate CbxFitMode enum values from API', () => {
|
||||||
|
const validValues = [
|
||||||
|
CbxFitMode.ACTUAL_SIZE,
|
||||||
|
CbxFitMode.FIT_PAGE,
|
||||||
|
CbxFitMode.FIT_WIDTH,
|
||||||
|
CbxFitMode.FIT_HEIGHT,
|
||||||
|
CbxFitMode.AUTO
|
||||||
|
];
|
||||||
|
validValues.forEach(value => {
|
||||||
|
expect(Object.values(CbxFitMode)).toContain(value);
|
||||||
|
});
|
||||||
|
expect(Object.keys(CbxFitMode)).toHaveLength(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate PdfPageSpread enum values from API', () => {
|
||||||
|
const validValues = [PdfPageSpread.EVEN, PdfPageSpread.ODD];
|
||||||
|
expect(validValues).toContain(PdfPageSpread.EVEN);
|
||||||
|
expect(validValues).toContain(PdfPageSpread.ODD);
|
||||||
|
expect(Object.keys(PdfPageSpread)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should validate PdfPageViewMode enum values from API', () => {
|
||||||
|
const validValues = [PdfPageViewMode.SINGLE_PAGE, PdfPageViewMode.TWO_PAGE];
|
||||||
|
expect(validValues).toContain(PdfPageViewMode.SINGLE_PAGE);
|
||||||
|
expect(validValues).toContain(PdfPageViewMode.TWO_PAGE);
|
||||||
|
expect(Object.keys(PdfPageViewMode)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('HTTP endpoint contract', () => {
|
||||||
|
it('should call correct endpoint for getMyself', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of({}));
|
||||||
|
service.getMyself().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/me$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for getUsers', () => {
|
||||||
|
httpClientMock.get.mockReturnValue(of([]));
|
||||||
|
service.getUsers().subscribe();
|
||||||
|
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for createUser', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(void 0));
|
||||||
|
const userData = {
|
||||||
|
username: 'new',
|
||||||
|
name: 'New User',
|
||||||
|
email: 'new@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: false,
|
||||||
|
canUpload: false,
|
||||||
|
canDownload: false,
|
||||||
|
canEmailBook: false,
|
||||||
|
canDeleteBook: false,
|
||||||
|
canEditMetadata: false,
|
||||||
|
canManageLibrary: false,
|
||||||
|
canManageMetadataConfig: false,
|
||||||
|
canSyncKoReader: false,
|
||||||
|
canSyncKobo: false,
|
||||||
|
canAccessOpds: false,
|
||||||
|
canAccessBookdrop: false,
|
||||||
|
canAccessLibraryStats: false,
|
||||||
|
canAccessUserStats: false,
|
||||||
|
canAccessTaskManager: false,
|
||||||
|
canManageEmailConfig: false,
|
||||||
|
canManageGlobalPreferences: false,
|
||||||
|
canManageIcons: false,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: false,
|
||||||
|
canBulkCustomFetchMetadata: false,
|
||||||
|
canBulkEditMetadata: false,
|
||||||
|
canBulkRegenerateCover: false,
|
||||||
|
canMoveOrganizeFiles: false,
|
||||||
|
canBulkLockUnlockMetadata: false
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||||
|
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and' as const,
|
||||||
|
filterSortingMode: 'alphabetical' as const,
|
||||||
|
metadataCenterViewMode: 'route' as const,
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
service.createUser(userData).subscribe();
|
||||||
|
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v1\/auth\/register$/),
|
||||||
|
userData
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for updateUser', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of({}));
|
||||||
|
service.updateUser(123, {name: 'Updated'}).subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v1\/users\/123$/),
|
||||||
|
{name: 'Updated'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for deleteUser', () => {
|
||||||
|
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||||
|
service.deleteUser(123).subscribe();
|
||||||
|
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/123$/));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for changeUserPassword', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.changeUserPassword(123, 'newpass').subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v1\/users\/change-user-password$/),
|
||||||
|
{userId: 123, newPassword: 'newpass'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for changePassword', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.changePassword('oldpass', 'newpass').subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v1\/users\/change-password$/),
|
||||||
|
{currentPassword: 'oldpass', newPassword: 'newpass'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should call correct endpoint for updateUserSetting', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.updateUserSetting(123, 'koReaderEnabled', true);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(/\/api\/v1\/users\/123\/settings$/),
|
||||||
|
{key: 'koReaderEnabled', value: true},
|
||||||
|
expect.anything()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Request payload contract', () => {
|
||||||
|
it('should send UserUpdateRequest with correct structure', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of({}));
|
||||||
|
const updateRequest: UserUpdateRequest = {
|
||||||
|
name: 'New Name',
|
||||||
|
email: 'newemail@test.com',
|
||||||
|
permissions: {
|
||||||
|
admin: true,
|
||||||
|
canUpload: true,
|
||||||
|
canDownload: true,
|
||||||
|
canEmailBook: true,
|
||||||
|
canDeleteBook: true,
|
||||||
|
canEditMetadata: true,
|
||||||
|
canManageLibrary: true,
|
||||||
|
canManageMetadataConfig: true,
|
||||||
|
canSyncKoReader: true,
|
||||||
|
canSyncKobo: true,
|
||||||
|
canAccessOpds: true,
|
||||||
|
canAccessBookdrop: true,
|
||||||
|
canAccessLibraryStats: true,
|
||||||
|
canAccessUserStats: true,
|
||||||
|
canAccessTaskManager: true,
|
||||||
|
canManageEmailConfig: true,
|
||||||
|
canManageGlobalPreferences: true,
|
||||||
|
canManageIcons: true,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: true,
|
||||||
|
canBulkCustomFetchMetadata: true,
|
||||||
|
canBulkEditMetadata: true,
|
||||||
|
canBulkRegenerateCover: true,
|
||||||
|
canMoveOrganizeFiles: true,
|
||||||
|
canBulkLockUnlockMetadata: true
|
||||||
|
},
|
||||||
|
assignedLibraries: [1, 2, 3]
|
||||||
|
};
|
||||||
|
service.updateUser(1, updateRequest).subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
updateRequest
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should send change password payload with correct structure', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.changePassword('current', 'new').subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
{currentPassword: 'current', newPassword: 'new'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should send change user password payload with correct structure', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.changeUserPassword(456, 'newpassword').subscribe();
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
{userId: 456, newPassword: 'newpassword'}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should send user setting payload with correct structure', () => {
|
||||||
|
httpClientMock.put.mockReturnValue(of(void 0));
|
||||||
|
service.updateUserSetting(789, 'enableSeriesView', false);
|
||||||
|
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
{key: 'enableSeriesView', value: false},
|
||||||
|
expect.anything()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Response type contract', () => {
|
||||||
|
it('should expect User array from getUsers', () => {
|
||||||
|
const mockUsers: User[] = [{
|
||||||
|
id: 1,
|
||||||
|
username: 'user1',
|
||||||
|
name: 'User One',
|
||||||
|
email: 'user1@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: false,
|
||||||
|
canUpload: false,
|
||||||
|
canDownload: false,
|
||||||
|
canEmailBook: false,
|
||||||
|
canDeleteBook: false,
|
||||||
|
canEditMetadata: false,
|
||||||
|
canManageLibrary: false,
|
||||||
|
canManageMetadataConfig: false,
|
||||||
|
canSyncKoReader: false,
|
||||||
|
canSyncKobo: false,
|
||||||
|
canAccessOpds: false,
|
||||||
|
canAccessBookdrop: false,
|
||||||
|
canAccessLibraryStats: false,
|
||||||
|
canAccessUserStats: false,
|
||||||
|
canAccessTaskManager: false,
|
||||||
|
canManageEmailConfig: false,
|
||||||
|
canManageGlobalPreferences: false,
|
||||||
|
canManageIcons: false,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: false,
|
||||||
|
canBulkCustomFetchMetadata: false,
|
||||||
|
canBulkEditMetadata: false,
|
||||||
|
canBulkRegenerateCover: false,
|
||||||
|
canMoveOrganizeFiles: false,
|
||||||
|
canBulkLockUnlockMetadata: false
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||||
|
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and',
|
||||||
|
filterSortingMode: 'alphabetical',
|
||||||
|
metadataCenterViewMode: 'route',
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
}];
|
||||||
|
|
||||||
|
httpClientMock.get.mockReturnValue(of(mockUsers));
|
||||||
|
service.getUsers().subscribe(users => {
|
||||||
|
expect(Array.isArray(users)).toBe(true);
|
||||||
|
expect(users[0]).toHaveProperty('id');
|
||||||
|
expect(users[0]).toHaveProperty('username');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect User from updateUser', () => {
|
||||||
|
const mockUser: User = {
|
||||||
|
id: 1,
|
||||||
|
username: 'updated',
|
||||||
|
name: 'Updated User',
|
||||||
|
email: 'updated@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: false,
|
||||||
|
canUpload: false,
|
||||||
|
canDownload: false,
|
||||||
|
canEmailBook: false,
|
||||||
|
canDeleteBook: false,
|
||||||
|
canEditMetadata: false,
|
||||||
|
canManageLibrary: false,
|
||||||
|
canManageMetadataConfig: false,
|
||||||
|
canSyncKoReader: false,
|
||||||
|
canSyncKobo: false,
|
||||||
|
canAccessOpds: false,
|
||||||
|
canAccessBookdrop: false,
|
||||||
|
canAccessLibraryStats: false,
|
||||||
|
canAccessUserStats: false,
|
||||||
|
canAccessTaskManager: false,
|
||||||
|
canManageEmailConfig: false,
|
||||||
|
canManageGlobalPreferences: false,
|
||||||
|
canManageIcons: false,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: false,
|
||||||
|
canBulkCustomFetchMetadata: false,
|
||||||
|
canBulkEditMetadata: false,
|
||||||
|
canBulkRegenerateCover: false,
|
||||||
|
canMoveOrganizeFiles: false,
|
||||||
|
canBulkLockUnlockMetadata: false
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||||
|
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and',
|
||||||
|
filterSortingMode: 'alphabetical',
|
||||||
|
metadataCenterViewMode: 'route',
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
httpClientMock.put.mockReturnValue(of(mockUser));
|
||||||
|
service.updateUser(1, {name: 'Updated User'}).subscribe(user => {
|
||||||
|
expect(user).toHaveProperty('id');
|
||||||
|
expect(user).toHaveProperty('username');
|
||||||
|
expect(user).toHaveProperty('permissions');
|
||||||
|
expect(user).toHaveProperty('userSettings');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should expect void from createUser', () => {
|
||||||
|
httpClientMock.post.mockReturnValue(of(void 0));
|
||||||
|
const userData = {
|
||||||
|
username: 'new',
|
||||||
|
name: 'New',
|
||||||
|
email: 'new@test.com',
|
||||||
|
assignedLibraries: [],
|
||||||
|
permissions: {
|
||||||
|
admin: false,
|
||||||
|
canUpload: false,
|
||||||
|
canDownload: false,
|
||||||
|
canEmailBook: false,
|
||||||
|
canDeleteBook: false,
|
||||||
|
canEditMetadata: false,
|
||||||
|
canManageLibrary: false,
|
||||||
|
canManageMetadataConfig: false,
|
||||||
|
canSyncKoReader: false,
|
||||||
|
canSyncKobo: false,
|
||||||
|
canAccessOpds: false,
|
||||||
|
canAccessBookdrop: false,
|
||||||
|
canAccessLibraryStats: false,
|
||||||
|
canAccessUserStats: false,
|
||||||
|
canAccessTaskManager: false,
|
||||||
|
canManageEmailConfig: false,
|
||||||
|
canManageGlobalPreferences: false,
|
||||||
|
canManageIcons: false,
|
||||||
|
demoUser: false,
|
||||||
|
canBulkAutoFetchMetadata: false,
|
||||||
|
canBulkCustomFetchMetadata: false,
|
||||||
|
canBulkEditMetadata: false,
|
||||||
|
canBulkRegenerateCover: false,
|
||||||
|
canMoveOrganizeFiles: false,
|
||||||
|
canBulkLockUnlockMetadata: false
|
||||||
|
},
|
||||||
|
userSettings: {
|
||||||
|
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||||
|
pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false},
|
||||||
|
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||||
|
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||||
|
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||||
|
sidebarLibrarySorting: {field: '', order: ''},
|
||||||
|
sidebarShelfSorting: {field: '', order: ''},
|
||||||
|
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||||
|
filterMode: 'and' as const,
|
||||||
|
filterSortingMode: 'alphabetical' as const,
|
||||||
|
metadataCenterViewMode: 'route' as const,
|
||||||
|
enableSeriesView: true,
|
||||||
|
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||||
|
koReaderEnabled: false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
service.createUser(userData).subscribe(result => {
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,7 +10,7 @@ import {Button} from 'primeng/button';
|
|||||||
import {Menu} from 'primeng/menu';
|
import {Menu} from 'primeng/menu';
|
||||||
import {UserService} from '../../../../features/settings/user-management/user.service';
|
import {UserService} from '../../../../features/settings/user-management/user.service';
|
||||||
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
|
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
|
||||||
import {BookDialogHelperService} from '../../../../features/book/components/book-browser/BookDialogHelperService';
|
import {BookDialogHelperService} from '../../../../features/book/components/book-browser/book-dialog-helper.service';
|
||||||
import {IconDisplayComponent} from '../../../components/icon-display/icon-display.component';
|
import {IconDisplayComponent} from '../../../components/icon-display/icon-display.component';
|
||||||
import {MenuItem} from 'primeng/api';
|
import {MenuItem} from 'primeng/api';
|
||||||
import {IconSelection} from '../../../service/icon-picker.service';
|
import {IconSelection} from '../../../service/icon-picker.service';
|
||||||
|
|||||||
Reference in New Issue
Block a user