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 {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||
import {BookSorter} from './sorting/BookSorter';
|
||||
import {BookDialogHelperService} from './BookDialogHelperService';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {Popover} from 'primeng/popover';
|
||||
import {Slider} from 'primeng/slider';
|
||||
import {Divider} from 'primeng/divider';
|
||||
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 {BookMenuService} from '../../service/book-menu.service';
|
||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.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 {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
||||
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 {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||
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 {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 {
|
||||
switch (filterType.toLowerCase()) {
|
||||
case 'filesize':
|
||||
const fileSizeRange = fileSizeRanges.find(r => r.id === value);
|
||||
return fileSizeRange?.label || value;
|
||||
// Try both lower and original case for id match
|
||||
{
|
||||
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':
|
||||
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':
|
||||
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':
|
||||
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 'goodreadsrating':
|
||||
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:
|
||||
return value;
|
||||
}
|
||||
@@ -60,4 +87,3 @@ export class FilterLabelHelper {
|
||||
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> {
|
||||
return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe(
|
||||
map(([activeFilters, mode]) => {
|
||||
// Return original state if books is null or undefined
|
||||
if (bookState.books == null) return bookState;
|
||||
if (!activeFilters) return bookState;
|
||||
const filteredBooks = (bookState.books || []).filter(book => {
|
||||
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;
|
||||
|
||||
sortOptions: SortOption[] = [
|
||||
{ label: 'Title', field: 'title', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING },
|
||||
{ label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Author', field: 'author', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING },
|
||||
{ label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Random', field: 'random', direction: SortDirection.ASCENDING },
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
{label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING},
|
||||
{label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING},
|
||||
{label: 'Author', field: 'author', direction: SortDirection.ASCENDING},
|
||||
{label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING},
|
||||
{label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING},
|
||||
{label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING},
|
||||
{label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING},
|
||||
{label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING},
|
||||
{label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING},
|
||||
{label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING},
|
||||
{label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING},
|
||||
{label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING},
|
||||
{label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING},
|
||||
{label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING},
|
||||
{label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING},
|
||||
{label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING},
|
||||
{label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING},
|
||||
{label: 'Pages', field: 'pageCount', 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 {
|
||||
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 {Checkbox} from 'primeng/checkbox';
|
||||
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 {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
|
||||
import {IconSelection} from '../../../../shared/service/icon-picker.service';
|
||||
|
||||
Reference in New Issue
Block a user