Add frontend unit tests (Part 2)

This commit is contained in:
acx10
2026-01-06 15:16:26 -07:00
parent 81442a1e5c
commit f63a8641d8
47 changed files with 3994 additions and 97 deletions
@@ -0,0 +1,102 @@
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 {UtilityService} from './utility.service';
describe('UtilityService', () => {
let service: UtilityService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UtilityService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(UtilityService)
);
});
it('should get folders for a given path', () => {
httpClientMock.get.mockReturnValue(of(['folder1', 'folder2']));
service.getFolders('/some/path').subscribe(folders => {
expect(folders).toEqual(['folder1', 'folder2']);
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringContaining('/api/v1/path'),
{params: expect.anything()}
);
});
});
it('should handle error when getting folders', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getFolders('/bad/path').subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('UtilityService - API Contract Tests', () => {
let service: UtilityService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UtilityService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(UtilityService)
);
});
it('should call correct endpoint and params for getFolders', () => {
httpClientMock.get.mockReturnValue(of(['a', 'b']));
service.getFolders('/root').subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/path$/),
{params: expect.objectContaining({get: expect.any(Function)})}
);
});
it('should expect string[] from getFolders', () => {
httpClientMock.get.mockReturnValue(of(['dirA', 'dirB']));
service.getFolders('/dir').subscribe(result => {
expect(Array.isArray(result)).toBe(true);
expect(typeof result[0]).toBe('string');
});
});
it('should send correct query param for path', () => {
httpClientMock.get.mockImplementation((url: string, opts: any) => {
expect(opts.params.get('path')).toBe('/my/path');
return of([]);
});
service.getFolders('/my/path').subscribe();
});
});
@@ -10,7 +10,7 @@ import {Subject} from 'rxjs';
import {BookService} from '../../../features/book/service/book.service';
import {Book} from '../../../features/book/model/book.model';
import {FileMoveRequest, FileOperationsService} from '../../service/file-operations-service';
import {FileMoveRequest, FileOperationsService} from '../../service/file-operations.service';
import {LibraryService} from "../../../features/book/service/library.service";
import {AppSettingsService} from '../../service/app-settings.service';
import {Select} from 'primeng/select';
@@ -393,8 +393,4 @@ export class FileMoverComponent implements OnDestroy {
togglePatternsCollapsed(): void {
this.patternsCollapsed = !this.patternsCollapsed;
}
trackByBookId(index: number, preview: FilePreview): number {
return preview.bookId;
}
}
@@ -9,7 +9,7 @@ import {Tooltip} from 'primeng/tooltip';
import {MessageService} from 'primeng/api';
import {MetadataBatchProgressNotification, MetadataBatchStatus, MetadataBatchStatusLabels} from '../../model/metadata-batch-progress.model';
import {MetadataProgressService} from '../../service/metadata-progress-service';
import {MetadataProgressService} from '../../service/metadata-progress.service';
import {MetadataTaskService} from '../../../features/book/service/metadata-task';
import {Tag} from 'primeng/tag';
import {TaskService} from '../../../features/settings/task-management/task.service';
@@ -0,0 +1,104 @@
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 {SetupPayload, SetupService} from './setup.service';
describe('SetupService', () => {
let service: SetupService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
SetupService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(SetupService)
);
});
it('should create admin with correct payload', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const payload: SetupPayload = {email: 'admin@test.com', password: 'pass'};
service.createAdmin(payload).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringContaining('/api/v1/setup'),
payload
);
});
});
it('should handle error when creating admin', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createAdmin({email: 'fail', password: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('SetupService - API Contract Tests', () => {
let service: SetupService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
SetupService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(SetupService)
);
});
it('should call correct endpoint for createAdmin', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const payload: SetupPayload = {email: 'a@b.com', password: 'pw'};
service.createAdmin(payload).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/setup$/),
payload
);
});
it('should expect void from createAdmin', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.createAdmin({email: 'x@y.com', password: 'pw'}).subscribe(result => {
expect(result).toBeUndefined();
});
});
it('should send correct payload structure', () => {
httpClientMock.post.mockImplementation((url: string, body: SetupPayload) => {
expect(body).toHaveProperty('email');
expect(body).toHaveProperty('password');
return of(void 0);
});
service.createAdmin({email: 'z@z.com', password: 'pw'}).subscribe();
});
});
@@ -1,6 +1,6 @@
import {Component, inject} from '@angular/core';
import {LiveNotificationBoxComponent} from '../live-notification-box/live-notification-box.component';
import {MetadataProgressService} from '../../service/metadata-progress-service';
import {MetadataProgressService} from '../../service/metadata-progress.service';
import {map} from 'rxjs/operators';
import {AsyncPipe} from '@angular/common';
import {BookdropFileService} from '../../../features/bookdrop/service/bookdrop-file.service';
@@ -16,7 +16,7 @@ import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurat
import {AuthService} from '../../../service/auth.service';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {Popover} from 'primeng/popover';
import {MetadataProgressService} from '../../../service/metadata-progress-service';
import {MetadataProgressService} from '../../../service/metadata-progress.service';
import {takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
import {MetadataBatchProgressNotification} from '../../../model/metadata-batch-progress.model';
@@ -0,0 +1,484 @@
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 {AppSettingsService, PublicAppSettings} from './app-settings.service';
import {AppSettings} from '../model/app-settings.model';
import {AuthService} from './auth.service';
describe('AppSettingsService', () => {
let service: AppSettingsService;
let httpClientMock: any;
let authServiceMock: any;
let injectorMock: any;
const mockAppSettings: AppSettings = {
autoBookSearch: true,
similarBookRecommendation: false,
defaultMetadataRefreshOptions: {} as any,
libraryMetadataRefreshOptions: [],
uploadPattern: '',
opdsServerEnabled: false,
remoteAuthEnabled: false,
oidcEnabled: true,
oidcProviderDetails: {
providerName: 'TestProvider',
clientId: 'clientid',
issuerUri: 'https://issuer.example.com',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
},
oidcAutoProvisionDetails: {
enableAutoProvisioning: false,
defaultPermissions: [],
defaultLibraryIds: []
},
cbxCacheSizeInMb: 0,
maxFileUploadSizeInMb: 0,
metadataProviderSettings: {
amazon: {enabled: false, cookie: '', domain: ''},
google: {enabled: false, language: ''},
goodReads: {enabled: false},
hardcover: {enabled: false, apiKey: ''},
comicvine: {enabled: false, apiKey: ''},
douban: {enabled: false},
lubimyczytac: {enabled: false}
},
metadataMatchWeights: {
title: 0,
subtitle: 0,
description: 0,
authors: 0,
publisher: 0,
publishedDate: 0,
seriesName: 0,
seriesNumber: 0,
seriesTotal: 0,
isbn13: 0,
isbn10: 0,
language: 0,
pageCount: 0,
categories: 0,
amazonRating: 0,
amazonReviewCount: 0,
goodreadsRating: 0,
goodreadsReviewCount: 0,
hardcoverRating: 0,
hardcoverReviewCount: 0,
doubanRating: 0,
doubanReviewCount: 0,
lubimyczytacRating: 0,
coverImage: 0
},
metadataPersistenceSettings: {
moveFilesToLibraryPattern: false,
saveToOriginalFile: false,
convertCbrCb7ToCbz: false
},
metadataPublicReviewsSettings: {
downloadEnabled: false,
autoDownloadEnabled: false,
providers: []
},
koboSettings: {
convertToKepub: false,
conversionLimitInMb: 0,
conversionImageCompressionPercentage: 0,
convertCbxToEpub: false,
conversionLimitInMbForCbx: 0,
forceEnableHyphenation: false
},
coverCroppingSettings: {
verticalCroppingEnabled: false,
horizontalCroppingEnabled: false,
aspectRatioThreshold: 0,
smartCroppingEnabled: false
},
metadataDownloadOnBookdrop: false,
telemetryEnabled: false
};
const mockPublicSettings: PublicAppSettings = {
oidcEnabled: true,
remoteAuthEnabled: false,
oidcProviderDetails: mockAppSettings.oidcProviderDetails
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
put: vi.fn()
};
authServiceMock = {
clearOIDCTokens: vi.fn()
};
injectorMock = {
get: vi.fn().mockReturnValue(authServiceMock)
};
TestBed.configureTestingModule({
providers: [
AppSettingsService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock},
{provide: EnvironmentInjector, useValue: injectorMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService));
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should fetch app settings and update subject', () => {
httpClientMock.get.mockReturnValue(of(mockAppSettings));
service['fetchAppSettings']().subscribe(settings => {
expect(settings).toEqual(mockAppSettings);
expect(service['appSettingsSubject'].value).toEqual(mockAppSettings);
});
});
it('should handle error when fetching app settings', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['fetchAppSettings']().subscribe({
error: (err: any) => {
expect(service['appSettingsSubject'].value).toBeNull();
expect(err).toBeInstanceOf(Error);
}
});
});
it('should fetch public settings and update subject', () => {
httpClientMock.get.mockReturnValue(of(mockPublicSettings));
service['fetchPublicSettings']().subscribe(settings => {
expect(settings).toEqual(mockPublicSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
});
it('should handle error when fetching public settings', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['fetchPublicSettings']().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should sync public settings from app settings', () => {
service['publicAppSettingsSubject'].next(null);
service['syncPublicSettings'](mockAppSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
it('should not update public settings if unchanged', () => {
service['publicAppSettingsSubject'].next(mockPublicSettings);
service['syncPublicSettings'](mockAppSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
it('should save settings and update appSettingsSubject', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(() => {
expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false);
});
});
it('should fetch settings if current is null on save', () => {
httpClientMock.put.mockReturnValue(of(void 0));
httpClientMock.get.mockReturnValue(of(mockAppSettings));
service['appSettingsSubject'].next(null);
service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe(() => {
expect(httpClientMock.get).toHaveBeenCalled();
});
});
it('should handle error on saveSettings', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(result => {
expect(result).toBeUndefined();
});
});
it('should toggle OIDC enabled and update state', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
service.toggleOidcEnabled(false).subscribe(() => {
expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false);
});
});
it('should call clearOIDCTokens when disabling OIDC', async () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
await new Promise<void>(resolve => {
service.toggleOidcEnabled(false).subscribe(() => {
setTimeout(() => {
expect(authServiceMock.clearOIDCTokens).toHaveBeenCalled();
resolve();
}, 10);
});
});
});
it('should handle error on toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.toggleOidcEnabled(true).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
describe('AppSettingsService - API Contract Tests', () => {
let service: AppSettingsService;
let httpClientMock: any;
let authServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
put: vi.fn()
};
authServiceMock = {
clearOIDCTokens: vi.fn()
};
injectorMock = {
get: vi.fn().mockReturnValue(authServiceMock)
};
TestBed.configureTestingModule({
providers: [
AppSettingsService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock},
{provide: EnvironmentInjector, useValue: injectorMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService));
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('PublicAppSettings interface contract', () => {
it('should validate all required PublicAppSettings fields exist', () => {
const requiredFields: (keyof PublicAppSettings)[] = [
'oidcEnabled', 'remoteAuthEnabled', 'oidcProviderDetails'
];
const mockResponse: PublicAppSettings = {
oidcEnabled: true,
remoteAuthEnabled: false,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
}
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service['fetchPublicSettings']().subscribe(settings => {
requiredFields.forEach(field => {
expect(settings).toHaveProperty(field);
expect(settings[field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for fetchAppSettings', () => {
httpClientMock.get.mockReturnValue(of({}));
service['fetchAppSettings']().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/settings$/));
});
it('should call correct endpoint for fetchPublicSettings', () => {
httpClientMock.get.mockReturnValue(of({}));
service['fetchPublicSettings']().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/public-settings$/));
});
it('should call correct endpoint for saveSettings', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/settings$/),
[{name: 'oidcEnabled', value: true}]
);
});
it('should call correct endpoint for toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.toggleOidcEnabled(true).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/settings$/),
[{name: 'OIDC_ENABLED', value: true}]
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for saveSettings', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.saveSettings([{key: 'remoteAuthEnabled', newValue: false}]).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
[{name: 'remoteAuthEnabled', value: false}]
);
});
it('should send correct structure for toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.toggleOidcEnabled(false).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
[{name: 'OIDC_ENABLED', value: false}]
);
});
});
describe('Response type contract', () => {
it('should expect AppSettings from fetchAppSettings', () => {
const mockSettings: AppSettings = {
autoBookSearch: true,
similarBookRecommendation: false,
defaultMetadataRefreshOptions: {} as any,
libraryMetadataRefreshOptions: [],
uploadPattern: '',
opdsServerEnabled: false,
remoteAuthEnabled: false,
oidcEnabled: true,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
},
oidcAutoProvisionDetails: {
enableAutoProvisioning: false,
defaultPermissions: [],
defaultLibraryIds: []
},
cbxCacheSizeInMb: 0,
maxFileUploadSizeInMb: 0,
metadataProviderSettings: {
amazon: {enabled: false, cookie: '', domain: ''},
google: {enabled: false, language: ''},
goodReads: {enabled: false},
hardcover: {enabled: false, apiKey: ''},
comicvine: {enabled: false, apiKey: ''},
douban: {enabled: false},
lubimyczytac: {enabled: false}
},
metadataMatchWeights: {
title: 0,
subtitle: 0,
description: 0,
authors: 0,
publisher: 0,
publishedDate: 0,
seriesName: 0,
seriesNumber: 0,
seriesTotal: 0,
isbn13: 0,
isbn10: 0,
language: 0,
pageCount: 0,
categories: 0,
amazonRating: 0,
amazonReviewCount: 0,
goodreadsRating: 0,
goodreadsReviewCount: 0,
hardcoverRating: 0,
hardcoverReviewCount: 0,
doubanRating: 0,
doubanReviewCount: 0,
lubimyczytacRating: 0,
coverImage: 0
},
metadataPersistenceSettings: {
moveFilesToLibraryPattern: false,
saveToOriginalFile: false,
convertCbrCb7ToCbz: false
},
metadataPublicReviewsSettings: {
downloadEnabled: false,
autoDownloadEnabled: false,
providers: []
},
koboSettings: {
convertToKepub: false,
conversionLimitInMb: 0,
conversionImageCompressionPercentage: 0,
convertCbxToEpub: false,
conversionLimitInMbForCbx: 0,
forceEnableHyphenation: false
},
coverCroppingSettings: {
verticalCroppingEnabled: false,
horizontalCroppingEnabled: false,
aspectRatioThreshold: 0,
smartCroppingEnabled: false
},
metadataDownloadOnBookdrop: false,
telemetryEnabled: false
};
httpClientMock.get.mockReturnValue(of(mockSettings));
service['fetchAppSettings']().subscribe(settings => {
expect(settings).toHaveProperty('oidcEnabled');
expect(settings).toHaveProperty('remoteAuthEnabled');
expect(settings).toHaveProperty('oidcProviderDetails');
});
});
it('should expect PublicAppSettings from fetchPublicSettings', () => {
const mockSettings: PublicAppSettings = {
oidcEnabled: false,
remoteAuthEnabled: true,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
}
};
httpClientMock.get.mockReturnValue(of(mockSettings));
service['fetchPublicSettings']().subscribe(settings => {
expect(settings).toHaveProperty('oidcEnabled');
expect(settings).toHaveProperty('remoteAuthEnabled');
expect(settings).toHaveProperty('oidcProviderDetails');
});
});
});
});
@@ -131,8 +131,8 @@ export class AppSettingsService {
this.syncPublicSettings(current);
}
if (!enabled) {
const authService = this.injector.get(AuthService);
setTimeout(() => {
const authService = this.injector.get(AuthService);
authService.clearOIDCTokens();
});
}
@@ -0,0 +1,309 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of} from 'rxjs';
import {AuthService} from './auth.service';
import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc';
import {Router} from '@angular/router';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
import {RxStompService} from '../websocket/rx-stomp.service';
describe('AuthService', () => {
let service: AuthService;
let httpClientMock: any;
let oAuthServiceMock: any;
let oAuthStorageMock: any;
let routerMock: any;
let postLoginInitializerMock: any;
let rxStompServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
oAuthServiceMock = {
getIdToken: vi.fn().mockReturnValue('oidc-token')
};
oAuthStorageMock = {
removeItem: vi.fn()
};
routerMock = {
navigate: vi.fn()
};
postLoginInitializerMock = {
initialize: vi.fn().mockReturnValue(of(void 0))
};
rxStompServiceMock = {
updateConfig: vi.fn(),
activate: vi.fn(),
deactivate: vi.fn()
};
injectorMock = {
get: vi.fn((token: any) => {
if (token === RxStompService) return rxStompServiceMock;
return undefined;
})
};
vi.stubGlobal('localStorage', {
getItem: vi.fn().mockReturnValue(null),
setItem: vi.fn(),
removeItem: vi.fn()
});
TestBed.configureTestingModule({
providers: [
AuthService,
{provide: HttpClient, useValue: httpClientMock},
{provide: OAuthService, useValue: oAuthServiceMock},
{provide: OAuthStorage, useValue: oAuthStorageMock},
{provide: Router, useValue: routerMock},
{provide: PostLoginInitializerService, useValue: postLoginInitializerMock},
{provide: RxStompService, useValue: rxStompServiceMock},
{provide: 'Injector', useValue: injectorMock}
]
});
// Patch inject() for Injector
(AuthService.prototype as any).injector = injectorMock;
service = TestBed.inject(AuthService);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should save and get internal tokens', () => {
service.saveInternalTokens('access', 'refresh');
expect(localStorage.setItem).toHaveBeenCalledWith('accessToken_Internal', 'access');
expect(localStorage.setItem).toHaveBeenCalledWith('refreshToken_Internal', 'refresh');
expect(service.tokenSubject.value).toBe('access');
});
it('should get internal access and refresh tokens', () => {
(localStorage.getItem as any).mockImplementation((key: string) => key === 'accessToken_Internal' ? 'access' : 'refresh');
expect(service.getInternalAccessToken()).toBe('access');
expect(service.getInternalRefreshToken()).toBe('refresh');
});
it('should get OIDC access token', () => {
expect(service.getOidcAccessToken()).toBe('oidc-token');
});
it('should call internalLogin and save tokens', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.internalLogin({username: 'u', password: 'p'}).subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should call internalRefreshToken and save tokens', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.internalRefreshToken().subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should call remoteLogin and save tokens', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.remoteLogin().subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should clear OIDC tokens and navigate if no internal tokens', () => {
(localStorage.getItem as any).mockReturnValue(null);
service.clearOIDCTokens();
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token');
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
});
it('should not clear OIDC tokens if internal tokens exist', () => {
(localStorage.getItem as any).mockReturnValue('access');
service.clearOIDCTokens();
expect(oAuthStorageMock.removeItem).not.toHaveBeenCalled();
expect(routerMock.navigate).not.toHaveBeenCalled();
});
it('should logout and clear all tokens', () => {
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
const loc = {href: ''};
vi.stubGlobal('window', {location: loc});
service.logout();
expect(localStorage.removeItem).toHaveBeenCalledWith('accessToken_Internal');
expect(localStorage.removeItem).toHaveBeenCalledWith('refreshToken_Internal');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token');
expect(rxStompServiceMock.deactivate).toHaveBeenCalled();
expect(loc.href).toBe('/login');
});
it('should initialize websocket connection if token exists', () => {
vi.spyOn(service, 'getOidcAccessToken').mockReturnValue('token');
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
service['postLoginInitialized'] = false;
service.initializeWebSocketConnection();
expect(rxStompServiceMock.updateConfig).toHaveBeenCalled();
expect(rxStompServiceMock.activate).toHaveBeenCalled();
});
it('should not initialize websocket connection if no token', () => {
vi.spyOn(service, 'getOidcAccessToken').mockReturnValue(null);
vi.spyOn(service, 'getInternalAccessToken').mockReturnValue(null);
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
service.initializeWebSocketConnection();
expect(rxStompServiceMock.updateConfig).not.toHaveBeenCalled();
expect(rxStompServiceMock.activate).not.toHaveBeenCalled();
});
it('should call postLoginInitializer only once', () => {
service['postLoginInitialized'] = false;
service['handleSuccessfulAuth']();
expect(postLoginInitializerMock.initialize).toHaveBeenCalled();
service['handleSuccessfulAuth']();
expect(postLoginInitializerMock.initialize).toHaveBeenCalledTimes(1);
});
it('should get RxStompService from injector', () => {
service['rxStompService'] = undefined;
expect(service.getRxStompService()).toBe(rxStompServiceMock);
expect(service.getRxStompService()).toBe(rxStompServiceMock); // cached
});
});
describe('AuthService - API Contract Tests', () => {
let service: AuthService;
let httpClientMock: any;
let oAuthServiceMock: any;
let oAuthStorageMock: any;
let routerMock: any;
let postLoginInitializerMock: any;
let rxStompServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
oAuthServiceMock = {getIdToken: vi.fn()};
oAuthStorageMock = {removeItem: vi.fn()};
routerMock = {navigate: vi.fn()};
postLoginInitializerMock = {initialize: vi.fn().mockReturnValue(of(void 0))};
rxStompServiceMock = {updateConfig: vi.fn(), activate: vi.fn(), deactivate: vi.fn()};
injectorMock = {get: vi.fn((token: any) => rxStompServiceMock)};
vi.stubGlobal('localStorage', {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn()
});
TestBed.configureTestingModule({
providers: [
AuthService,
{provide: HttpClient, useValue: httpClientMock},
{provide: OAuthService, useValue: oAuthServiceMock},
{provide: OAuthStorage, useValue: oAuthStorageMock},
{provide: Router, useValue: routerMock},
{provide: PostLoginInitializerService, useValue: postLoginInitializerMock},
{provide: RxStompService, useValue: rxStompServiceMock},
{provide: 'Injector', useValue: injectorMock}
]
});
(AuthService.prototype as any).injector = injectorMock;
service = TestBed.inject(AuthService);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.internalLogin({username: 'u', password: 'p'}).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/login$/),
{username: 'u', password: 'p'}
);
});
it('should call correct endpoint for internalRefreshToken', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/refresh$/),
{refreshToken: 'refresh'}
);
});
it('should call correct endpoint for remoteLogin', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.remoteLogin().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/remote$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const payload = {username: 'user', password: 'pass'};
service.internalLogin(payload).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), payload);
});
it('should send correct structure for internalRefreshToken', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), {refreshToken: 'refresh'});
});
});
describe('Response type contract', () => {
it('should expect token object from internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.internalLogin({username: 'u', password: 'p'}).subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
expect(res).toHaveProperty('isDefaultPassword');
});
});
it('should expect token object from remoteLogin', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.remoteLogin().subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
expect(res).toHaveProperty('isDefaultPassword');
});
});
it('should expect token object from internalRefreshToken', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
});
});
});
});
@@ -0,0 +1,264 @@
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 {BookMarkService, BookMark, CreateBookMarkRequest, UpdateBookMarkRequest} from './book-mark.service';
describe('BookMarkService', () => {
let service: BookMarkService;
let httpClientMock: any;
const mockBookmark: BookMark = {
id: 1,
userId: 2,
bookId: 3,
cfi: 'epubcfi(/6/2[cover]!/6)',
title: 'Bookmark 1',
color: 'yellow',
notes: 'note',
priority: 1,
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookMarkService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookMarkService);
});
it('should get bookmarks for a book', () => {
httpClientMock.get.mockReturnValue(of([mockBookmark]));
service.getBookmarksForBook(3).subscribe(bookmarks => {
expect(bookmarks).toEqual([mockBookmark]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3'));
});
});
it('should create a bookmark', () => {
httpClientMock.post.mockReturnValue(of(mockBookmark));
const req: CreateBookMarkRequest = {bookId: 3, cfi: 'epubcfi(/6/2[cover]!/6)', title: 'Bookmark 1'};
service.createBookmark(req).subscribe(bm => {
expect(bm).toEqual(mockBookmark);
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
it('should update a bookmark', () => {
httpClientMock.put.mockReturnValue(of(mockBookmark));
const req: UpdateBookMarkRequest = {title: 'Updated', notes: 'Updated note'};
service.updateBookmark(1, req).subscribe(bm => {
expect(bm).toEqual(mockBookmark);
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), req);
});
});
it('should delete a bookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(1).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
});
});
it('should handle getBookmarksForBook error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getBookmarksForBook(3).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle createBookmark error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createBookmark({bookId: 3, cfi: 'cfi'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle updateBookmark error', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.updateBookmark(1, {title: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle deleteBookmark error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
service.deleteBookmark(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
});
describe('BookMarkService - API Contract Tests', () => {
let service: BookMarkService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookMarkService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookMarkService);
});
describe('BookMark interface contract', () => {
it('should validate all required BookMark fields exist', () => {
const requiredFields: (keyof BookMark)[] = [
'id', 'bookId', 'cfi', 'title', 'createdAt'
];
const mockResponse: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getBookmarksForBook(2).subscribe(bookmarks => {
requiredFields.forEach(field => {
expect(bookmarks[0]).toHaveProperty(field);
expect(bookmarks[0][field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getBookmarksForBook', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getBookmarksForBook(5).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/bookmarks\/book\/5$/));
});
it('should call correct endpoint for createBookmark', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'};
service.createBookmark(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks$/),
req
);
});
it('should call correct endpoint for updateBookmark', () => {
httpClientMock.put.mockReturnValue(of({}));
const req: UpdateBookMarkRequest = {title: 't'};
service.updateBookmark(7, req).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks\/7$/),
req
);
});
it('should call correct endpoint for deleteBookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(8).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks\/8$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for createBookmark', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'};
service.createBookmark(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
it('should send correct structure for updateBookmark', () => {
httpClientMock.put.mockReturnValue(of({}));
const req: UpdateBookMarkRequest = {title: 't', notes: 'n'};
service.updateBookmark(9, req).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(expect.any(String), req);
});
});
describe('Response type contract', () => {
it('should expect BookMark[] from getBookmarksForBook', () => {
const mockBookmarks: BookMark[] = [{
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockBookmarks));
service.getBookmarksForBook(2).subscribe(bookmarks => {
expect(Array.isArray(bookmarks)).toBe(true);
expect(bookmarks[0]).toHaveProperty('id');
expect(bookmarks[0]).toHaveProperty('bookId');
});
});
it('should expect BookMark from createBookmark', () => {
const mockBookmark: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockBookmark));
service.createBookmark({bookId: 2, cfi: 'cfi', title: 't'}).subscribe(bm => {
expect(bm).toHaveProperty('id');
expect(bm).toHaveProperty('bookId');
});
});
it('should expect BookMark from updateBookmark', () => {
const mockBookmark: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.put.mockReturnValue(of(mockBookmark));
service.updateBookmark(1, {title: 't'}).subscribe(bm => {
expect(bm).toHaveProperty('id');
expect(bm).toHaveProperty('bookId');
});
});
it('should expect void from deleteBookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -49,6 +49,7 @@ export class BookMarkService {
deleteBookmark(bookmarkId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${bookmarkId}`);
}
updateBookmark(bookmarkId: number, request: UpdateBookMarkRequest): Observable<BookMark> {
return this.http.put<BookMark>(`${this.url}/${bookmarkId}`, request);
}
@@ -0,0 +1,215 @@
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 {BookNote, BookNoteService, CreateBookNoteRequest} from './book-note.service';
describe('BookNoteService', () => {
let service: BookNoteService;
let httpClientMock: any;
const mockNote: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 'Note Title',
content: 'Note content',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookNoteService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookNoteService);
});
it('should get notes for a book', () => {
httpClientMock.get.mockReturnValue(of([mockNote]));
service.getNotesForBook(3).subscribe(notes => {
expect(notes).toEqual([mockNote]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3'));
});
});
it('should create or update a note', () => {
httpClientMock.post.mockReturnValue(of(mockNote));
const req: CreateBookNoteRequest = {bookId: 3, title: 'Note Title', content: 'Note content'};
service.createOrUpdateNote(req).subscribe(note => {
expect(note).toEqual(mockNote);
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
it('should delete a note', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(1).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
});
});
it('should handle getNotesForBook error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getNotesForBook(3).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle createOrUpdateNote error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createOrUpdateNote({bookId: 3, title: 'fail', content: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle deleteNote error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
service.deleteNote(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
});
describe('BookNoteService - API Contract Tests', () => {
let service: BookNoteService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookNoteService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookNoteService);
});
describe('BookNote interface contract', () => {
it('should validate all required BookNote fields exist', () => {
const requiredFields: (keyof BookNote)[] = [
'id', 'userId', 'bookId', 'title', 'content', 'createdAt', 'updatedAt'
];
const mockResponse: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getNotesForBook(3).subscribe(notes => {
requiredFields.forEach(field => {
expect(notes[0]).toHaveProperty(field);
expect(notes[0][field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getNotesForBook', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getNotesForBook(5).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/book-notes\/book\/5$/));
});
it('should call correct endpoint for createOrUpdateNote', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'};
service.createOrUpdateNote(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/book-notes$/),
req
);
});
it('should call correct endpoint for deleteNote', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(8).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/book-notes\/8$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for createOrUpdateNote', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'};
service.createOrUpdateNote(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
describe('Response type contract', () => {
it('should expect BookNote[] from getNotesForBook', () => {
const mockNotes: BookNote[] = [{
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockNotes));
service.getNotesForBook(3).subscribe(notes => {
expect(Array.isArray(notes)).toBe(true);
expect(notes[0]).toHaveProperty('id');
expect(notes[0]).toHaveProperty('title');
});
});
it('should expect BookNote from createOrUpdateNote', () => {
const mockNote: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockNote));
service.createOrUpdateNote({bookId: 2, title: 't', content: 'c'}).subscribe(note => {
expect(note).toHaveProperty('id');
expect(note).toHaveProperty('title');
});
});
it('should expect void from deleteNote', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -0,0 +1,309 @@
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} from 'rxjs';
import {CustomFontService} from './custom-font.service';
import {CustomFont, FontFormat} from '../model/custom-font.model';
import {AuthService} from './auth.service';
describe('CustomFontService', () => {
let service: CustomFontService;
let httpClientMock: any;
let authServiceMock: any;
const mockFont: CustomFont = {
id: 1,
fontName: 'TestFont',
originalFileName: 'testfont.ttf',
format: FontFormat.TTF,
fileSize: 1024,
uploadedAt: '2024-01-01T00:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
getOidcAccessToken: vi.fn().mockReturnValue('token'),
getInternalAccessToken: vi.fn().mockReturnValue(null)
};
(globalThis as any).FontFace = function (family: string, source: string, descriptors?: any) {
this.family = family;
this.source = source;
this.descriptors = descriptors;
this.load = vi.fn().mockResolvedValue(this);
};
const fontsSet: any[] = [];
(globalThis as any).document = {
fonts: {
add: vi.fn(font => fontsSet.push(font)),
delete: vi.fn(font => {
const idx = fontsSet.indexOf(font);
if (idx !== -1) fontsSet.splice(idx, 1);
}),
[Symbol.iterator]: function* () {
yield* fontsSet;
}
}
};
TestBed.configureTestingModule({
providers: [
CustomFontService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService));
});
it('should initialize with empty fontsSubject', () => {
expect(service['fontsSubject'].value).toEqual([]);
});
it('should upload font and update cache', () => {
httpClientMock.post.mockReturnValue(of(mockFont));
const file = new File(['dummy'], 'testfont.ttf');
service.uploadFont(file, 'TestFont').subscribe(font => {
expect(font).toEqual(mockFont);
expect(service['fontsSubject'].value).toContainEqual(mockFont);
});
});
it('should get user fonts and update cache', () => {
httpClientMock.get.mockReturnValue(of([mockFont]));
service.getUserFonts().subscribe(fonts => {
expect(fonts).toEqual([mockFont]);
expect(service['fontsSubject'].value).toEqual([mockFont]);
});
});
it('should delete font and update cache', () => {
service['fontsSubject'].next([mockFont]);
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(1).subscribe(result => {
expect(result).toBeUndefined();
expect(service['fontsSubject'].value).toEqual([]);
});
});
it('should get font URL', () => {
expect(service.getFontUrl(123)).toMatch(/\/api\/v1\/custom-fonts\/123\/file$/);
});
it('should append token to URL', () => {
const url = 'http://test.com/font.ttf';
expect(service.appendToken(url)).toContain('token=');
});
it('should mark font as loaded after loadFontFace', async () => {
await service.loadFontFace(mockFont);
expect(service.isFontLoaded(mockFont.fontName)).toBe(true);
const fontsArr = Array.from((globalThis as any).document.fonts);
expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(true);
});
it('should call removeFontFace on delete', () => {
const fontObj = {family: mockFont.fontName};
(globalThis as any).document.fonts.add(fontObj);
service['fontsSubject'].next([mockFont]);
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(mockFont.id).subscribe(() => {
const fontsArr = Array.from((globalThis as any).document.fonts);
expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(false);
});
});
it('should handle loadAllFonts', async () => {
vi.spyOn(service, 'loadFontFace').mockResolvedValue(undefined);
await service.loadAllFonts([mockFont]);
expect(service.loadFontFace).toHaveBeenCalledWith(mockFont);
});
it('should return false for isFontLoaded if not loaded', () => {
expect(service.isFontLoaded('NotLoaded')).toBe(false);
});
});
describe('CustomFontService - API Contract Tests', () => {
let service: CustomFontService;
let httpClientMock: any;
let authServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
getOidcAccessToken: vi.fn().mockReturnValue('token'),
getInternalAccessToken: vi.fn().mockReturnValue(null)
};
TestBed.configureTestingModule({
providers: [
CustomFontService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService));
});
describe('CustomFont interface contract', () => {
it('should validate all required CustomFont fields exist', () => {
const requiredFields: (keyof CustomFont)[] = [
'id', 'fontName', 'originalFileName', 'format', 'fileSize', 'uploadedAt'
];
const mockResponse: CustomFont = {
id: 1,
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getUserFonts().subscribe(fonts => {
requiredFields.forEach(field => {
expect(fonts[0]).toHaveProperty(field);
expect(fonts[0][field]).toBeDefined();
});
});
});
it('should fail if API returns CustomFont without required id field', () => {
const invalidResponse = [{
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(invalidResponse));
service.getUserFonts().subscribe(fonts => {
expect(fonts[0]).not.toHaveProperty('id');
});
});
});
describe('Enum value contract', () => {
it('should validate FontFormat enum values from API', () => {
const validValues = [FontFormat.TTF, FontFormat.OTF, FontFormat.WOFF, FontFormat.WOFF2];
validValues.forEach(value => {
expect(Object.values(FontFormat)).toContain(value);
});
expect(Object.keys(FontFormat)).toHaveLength(4);
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getUserFonts', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getUserFonts().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts$/));
});
it('should call correct endpoint for uploadFont', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file, 'Font').subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/custom-fonts\/upload$/),
expect.any(FormData)
);
});
it('should call correct endpoint for deleteFont', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(123).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts\/123$/));
});
it('should call getFontUrl with correct format', () => {
expect(service.getFontUrl(42)).toMatch(/\/api\/v1\/custom-fonts\/42\/file$/);
});
});
describe('Request payload contract', () => {
it('should send FormData with file and fontName for uploadFont', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file, 'Font').subscribe();
const formData = httpClientMock.post.mock.calls[0][1];
expect(formData instanceof FormData).toBe(true);
expect(formData.has('file')).toBe(true);
expect(formData.has('fontName')).toBe(true);
});
it('should send FormData with only file if fontName not provided', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file).subscribe();
const formData = httpClientMock.post.mock.calls[0][1];
expect(formData instanceof FormData).toBe(true);
expect(formData.has('file')).toBe(true);
expect(formData.has('fontName')).toBe(false);
});
});
describe('Response type contract', () => {
it('should expect CustomFont array from getUserFonts', () => {
const mockFonts: CustomFont[] = [{
id: 1,
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockFonts));
service.getUserFonts().subscribe(fonts => {
expect(Array.isArray(fonts)).toBe(true);
expect(fonts[0]).toHaveProperty('id');
expect(fonts[0]).toHaveProperty('fontName');
});
});
it('should expect CustomFont from uploadFont', () => {
const mockFont: CustomFont = {
id: 2,
fontName: 'Font2',
originalFileName: 'font2.ttf',
format: FontFormat.OTF,
fileSize: 2048,
uploadedAt: '2024-01-02T00:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockFont));
const file = new File(['dummy'], 'font2.ttf');
service.uploadFont(file, 'Font2').subscribe(font => {
expect(font).toHaveProperty('id');
expect(font).toHaveProperty('fontName');
expect(font).toHaveProperty('format');
});
});
it('should expect void from deleteFont', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -0,0 +1,174 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {DownloadProgressService} from './download-progress.service';
import {Subject, take} from 'rxjs';
describe('DownloadProgressService', () => {
let service: DownloadProgressService;
beforeEach(() => {
service = new DownloadProgressService();
});
it('should initialize with default state', () => {
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress).toEqual({
visible: false,
filename: '',
progress: 0,
loaded: 0,
total: 0
});
});
expect(service.isDownloadInProgress()).toBe(false);
});
it('should start a download and set state', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.visible).toBe(true);
expect(progress.filename).toBe('file.pdf');
expect(progress.progress).toBe(0);
expect(progress.cancelSubject).toBe(cancelSubject);
});
expect(service.isDownloadInProgress()).toBe(true);
});
it('should update progress and throttle updates', async () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
// First update should be immediate
service.updateProgress(50, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(50);
expect(progress.loaded).toBe(50);
expect(progress.total).toBe(100);
});
// Throttled update (simulate time)
vi.useFakeTimers();
service.updateProgress(60, 100);
// Should not emit immediately
let emitted = false;
service.downloadProgress$.subscribe(progress => {
if (progress.loaded === 60) emitted = true;
});
vi.advanceTimersByTime(100);
expect(emitted).toBe(true);
vi.useRealTimers();
});
it('should immediately update when progress is 100', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(100, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(100);
expect(progress.loaded).toBe(100);
expect(progress.total).toBe(100);
});
});
it('should complete download and reset state', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.completeDownload();
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.visible).toBe(false);
expect(progress.filename).toBe('');
expect(progress.progress).toBe(0);
});
expect(service.isDownloadInProgress()).toBe(false);
});
it('should cancel download and call cancelSubject', () => {
const cancelSubject = new Subject<void>();
const nextSpy = vi.fn();
const completeSpy = vi.fn();
cancelSubject.subscribe({next: nextSpy, complete: completeSpy});
service.startDownload('file.pdf', cancelSubject);
service.cancelDownload();
expect(nextSpy).toHaveBeenCalled();
expect(completeSpy).toHaveBeenCalled();
expect(service.isDownloadInProgress()).toBe(false);
});
});
describe('DownloadProgressService - API Contract Tests', () => {
let service: DownloadProgressService;
beforeEach(() => {
service = new DownloadProgressService();
});
describe('DownloadProgress interface contract', () => {
it('should have all required fields', () => {
const cancelSubject = new Subject<void>();
service.startDownload('test.txt', cancelSubject);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress).toHaveProperty('visible');
expect(progress).toHaveProperty('filename');
expect(progress).toHaveProperty('progress');
expect(progress).toHaveProperty('loaded');
expect(progress).toHaveProperty('total');
expect(progress).toHaveProperty('cancelSubject');
});
});
it('should allow cancelSubject to be undefined after complete', () => {
service.completeDownload();
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.cancelSubject).toBeUndefined();
});
});
});
describe('Behavior contract', () => {
it('should emit correct progress values', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(25, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(25);
expect(progress.loaded).toBe(25);
expect(progress.total).toBe(100);
});
});
it('should not exceed 100% progress', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(150, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(100);
});
});
it('should set progress to 0 if total is 0', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(50, 0);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(0);
});
});
});
describe('API contract', () => {
it('should expose downloadProgress$ as observable', () => {
expect(typeof service.downloadProgress$.subscribe).toBe('function');
});
it('should expose isDownloadInProgress as boolean', () => {
expect(typeof service.isDownloadInProgress()).toBe('boolean');
});
it('should expose startDownload, updateProgress, completeDownload, cancelDownload', () => {
expect(typeof service.startDownload).toBe('function');
expect(typeof service.updateProgress).toBe('function');
expect(typeof service.completeDownload).toBe('function');
expect(typeof service.cancelDownload).toBe('function');
});
});
});
@@ -0,0 +1,215 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient, HttpEventType, HttpHeaders, HttpResponse} from '@angular/common/http';
import {of, Subject, throwError} from 'rxjs';
import {FileDownloadService} from './file-download.service';
import {DownloadProgressService} from './download-progress.service';
import {MessageService} from 'primeng/api';
describe('FileDownloadService', () => {
let service: FileDownloadService;
let httpClientMock: any;
let downloadProgressServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
downloadProgressServiceMock = {
isDownloadInProgress: vi.fn().mockReturnValue(false),
startDownload: vi.fn(),
updateProgress: vi.fn(),
completeDownload: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileDownloadService,
{provide: HttpClient, useValue: httpClientMock},
{provide: DownloadProgressService, useValue: downloadProgressServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
});
it('should trigger download and handle progress and completion', () => {
const events = [
{type: HttpEventType.DownloadProgress, loaded: 50, total: 100},
{
type: HttpEventType.Response,
body: new Blob(['test']),
headers: new HttpHeaders(),
clone: () => this,
status: 200,
statusText: 'OK',
url: '',
ok: true
}
];
httpClientMock.get.mockReturnValue(of(...events));
// Mock DOM for download
const appendChild = vi.fn();
const removeChild = vi.fn();
(globalThis as any).document = {
createElement: vi.fn().mockReturnValue({
setAttribute: vi.fn(),
click: vi.fn(),
style: {},
href: '',
download: ''
}),
body: {appendChild, removeChild}
};
(globalThis as any).window = {
URL: {
createObjectURL: vi.fn().mockReturnValue('blob:url'),
revokeObjectURL: vi.fn()
}
};
service.downloadFile('/api/file', 'file.txt').subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith('/api/file', expect.objectContaining({observe: 'events'}));
expect(downloadProgressServiceMock.startDownload).toHaveBeenCalledWith('file.txt', expect.any(Subject));
expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(50, 100);
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
it('should extract filename from Content-Disposition header', () => {
const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''test%20file.txt"});
const response = new HttpResponse({body: new Blob(['test']), headers});
const filename = (service as any).extractFilenameFromResponse(response, 'default.txt');
expect(filename).toBe('test file.txt');
});
it('should fallback to default filename if Content-Disposition is missing', () => {
const headers = new HttpHeaders();
const response = new HttpResponse({body: new Blob(['test']), headers});
const filename = (service as any).extractFilenameFromResponse(response, 'default.txt');
expect(filename).toBe('default.txt');
});
it('should handle download error and show error message', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.downloadFile('/api/file', 'file.txt').subscribe({
error: () => {
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
}
});
});
it('should not show error message for AbortError', () => {
httpClientMock.get.mockReturnValue(throwError(() => ({name: 'AbortError'})));
service.downloadFile('/api/file', 'file.txt').subscribe({
error: () => {
expect(messageServiceMock.add).not.toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
}
});
});
it('should throw if no file content received', () => {
const response = new HttpResponse({body: undefined, headers: new HttpHeaders()});
expect(() => (service as any).handleDownloadComplete(response, 'file.txt')).toThrow('No file content received');
});
});
describe('FileDownloadService - API Contract Tests', () => {
let service: FileDownloadService;
let httpClientMock: any;
let downloadProgressServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
downloadProgressServiceMock = {
isDownloadInProgress: vi.fn().mockReturnValue(false),
startDownload: vi.fn(),
updateProgress: vi.fn(),
completeDownload: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileDownloadService,
{provide: HttpClient, useValue: httpClientMock},
{provide: DownloadProgressService, useValue: downloadProgressServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
});
describe('API contract', () => {
it('should expose downloadFile as a function', () => {
expect(typeof service.downloadFile).toBe('function');
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint and options for downloadFile', () => {
httpClientMock.get.mockReturnValue(of());
service.downloadFile('/api/file', 'file.txt');
expect(httpClientMock.get).toHaveBeenCalledWith(
'/api/file',
expect.objectContaining({
responseType: 'blob',
observe: 'events',
reportProgress: true
})
);
});
});
describe('Request/Response contract', () => {
it('should expect Blob in HttpResponse', () => {
const headers = new HttpHeaders();
const response = new HttpResponse({body: new Blob(['test']), headers});
expect((service as any).extractFilenameFromResponse(response, 'file.txt')).toBe('file.txt');
});
it('should handle Content-Disposition with encoded filename', () => {
const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''encoded%20file.pdf"});
const response = new HttpResponse({body: new Blob(['test']), headers});
expect((service as any).extractFilenameFromResponse(response, 'fallback.pdf')).toBe('encoded file.pdf');
});
});
describe('Behavior contract', () => {
it('should call startDownload and updateProgress on DownloadProgressService', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.DownloadProgress, loaded: 10, total: 20}));
service.downloadFile('/api/file', 'file.txt').subscribe();
expect(downloadProgressServiceMock.startDownload).toHaveBeenCalled();
expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(10, 20);
});
it('should call completeDownload on finalize', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true}));
service.downloadFile('/api/file', 'file.txt').subscribe();
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
});
it('should show success message on download complete', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true}));
service.downloadFile('/api/file', 'file.txt').subscribe();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
});
});
@@ -13,10 +13,10 @@ export class FileDownloadService {
private downloadProgressService = inject(DownloadProgressService);
private messageService = inject(MessageService);
downloadFile(url: string, defaultFilename: string): void {
downloadFile(url: string, defaultFilename: string): Observable<any> {
const cancelSubject = new Subject<void>();
this.initiateDownload(url)
return this.initiateDownload(url)
.pipe(
takeUntil(cancelSubject),
tap(event => this.handleDownloadProgress(event, defaultFilename, cancelSubject)),
@@ -25,8 +25,7 @@ export class FileDownloadService {
this.handleDownloadError(error);
return throwError(() => error);
})
)
.subscribe();
);
}
private initiateDownload(url: string): Observable<HttpEvent<Blob>> {
@@ -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 {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {FileMoveRequest, FileOperationsService} from './file-operations.service';
describe('FileOperationsService', () => {
let service: FileOperationsService;
let httpClientMock: any;
const mockRequest: FileMoveRequest = {
bookIds: [1, 2],
moves: [
{bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100},
{bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200}
]
};
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileOperationsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService));
});
it('should move files and return void', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.moveFiles(mockRequest).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/files\/move$/),
mockRequest
);
});
});
it('should handle move files error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.moveFiles(mockRequest).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('FileOperationsService - API Contract Tests', () => {
let service: FileOperationsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileOperationsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService));
});
describe('FileMoveRequest interface contract', () => {
it('should have required fields', () => {
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
expect(req).toHaveProperty('bookIds');
expect(req).toHaveProperty('moves');
expect(Array.isArray(req.bookIds)).toBe(true);
expect(Array.isArray(req.moves)).toBe(true);
expect(req.moves[0]).toHaveProperty('bookId');
expect(req.moves[0]).toHaveProperty('targetLibraryId');
expect(req.moves[0]).toHaveProperty('targetLibraryPathId');
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for moveFiles', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
service.moveFiles(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/files\/move$/),
req
);
});
});
describe('Request payload contract', () => {
it('should send FileMoveRequest with correct structure', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1, 2],
moves: [
{bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100},
{bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200}
]
};
service.moveFiles(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.any(String),
req
);
});
});
describe('Response type contract', () => {
it('should expect void from moveFiles', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
service.moveFiles(req).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -0,0 +1,98 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of, Subject, take} from 'rxjs';
import {IconPickerService, IconSelection} from './icon-picker.service';
import {DialogLauncherService} from '../services/dialog-launcher.service';
describe('IconPickerService', () => {
let service: IconPickerService;
let dialogLauncherServiceMock: any;
beforeEach(() => {
dialogLauncherServiceMock = {
openIconPickerDialog: vi.fn()
};
TestBed.configureTestingModule({
providers: [
IconPickerService,
{provide: DialogLauncherService, useValue: dialogLauncherServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService));
});
it('should open icon picker dialog and return selection observable', () => {
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-book'};
const subject = new Subject<IconSelection>();
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: subject.asObservable()});
let result: IconSelection | undefined;
service.open().pipe(take(1)).subscribe(sel => {
result = sel;
});
subject.next(selection);
expect(result).toEqual(selection);
});
it('should call openIconPickerDialog on open()', () => {
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of({type: 'CUSTOM_SVG', value: '<svg></svg>'})});
service.open().pipe(take(1)).subscribe();
expect(dialogLauncherServiceMock.openIconPickerDialog).toHaveBeenCalled();
});
});
describe('IconPickerService - API Contract Tests', () => {
let service: IconPickerService;
let dialogLauncherServiceMock: any;
beforeEach(() => {
dialogLauncherServiceMock = {
openIconPickerDialog: vi.fn()
};
TestBed.configureTestingModule({
providers: [
IconPickerService,
{provide: DialogLauncherService, useValue: dialogLauncherServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService));
});
describe('IconSelection interface contract', () => {
it('should have required fields', () => {
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'};
expect(selection).toHaveProperty('type');
expect(selection).toHaveProperty('value');
expect(typeof selection.type).toBe('string');
expect(typeof selection.value).toBe('string');
});
it('should only allow valid type values', () => {
const validTypes = ['PRIME_NG', 'CUSTOM_SVG'];
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'};
expect(validTypes).toContain(selection.type);
});
});
describe('API contract', () => {
it('should expose open as a function', () => {
expect(typeof service.open).toBe('function');
});
it('should return Observable<IconSelection> from open()', () => {
const selection: IconSelection = {type: 'CUSTOM_SVG', value: '<svg></svg>'};
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of(selection)});
let result: IconSelection | undefined;
service.open().pipe(take(1)).subscribe(sel => {
result = sel;
});
expect(result).toEqual(selection);
});
});
});
@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable({
providedIn: 'root'
@@ -7,12 +7,4 @@ import { BehaviorSubject } from 'rxjs';
export class LoadingService {
private loadingSubject = new BehaviorSubject<boolean>(false);
loading$ = this.loadingSubject.asObservable();
show(): void {
this.loadingSubject.next(true);
}
hide(): void {
this.loadingSubject.next(false);
}
}
@@ -0,0 +1,49 @@
import {describe, it, expect, beforeEach, vi} from 'vitest';
import {LocalStorageService} from './local-storage.service';
describe('LocalStorageService', () => {
let service: LocalStorageService;
beforeEach(() => {
service = new LocalStorageService();
vi.spyOn(window.localStorage, 'getItem').mockClear();
vi.spyOn(window.localStorage, 'setItem').mockClear();
vi.spyOn(window.localStorage, 'removeItem').mockClear();
});
it('should get value from localStorage', () => {
window.localStorage.setItem('test', JSON.stringify({foo: 'bar'}));
const result = service.get<{foo: string}>('test');
expect(result).toEqual({foo: 'bar'});
});
it('should return null if key does not exist', () => {
window.localStorage.removeItem('notfound');
const result = service.get('notfound');
expect(result).toBeNull();
});
it('should handle JSON parse error and return null', () => {
window.localStorage.setItem('bad', 'not-json');
const result = service.get('bad');
expect(result).toBeNull();
});
it('should set value in localStorage', () => {
service.set('foo', {bar: 123});
const stored = window.localStorage.getItem('foo');
expect(stored).toBe(JSON.stringify({bar: 123}));
});
it('should handle set error gracefully', () => {
vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => { throw new Error('fail'); });
expect(() => service.set('fail', {a: 1})).not.toThrow();
});
it('should remove value from localStorage', () => {
window.localStorage.setItem('toremove', '1');
service.remove('toremove');
expect(window.localStorage.getItem('toremove')).toBeNull();
});
});
@@ -0,0 +1,111 @@
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 {MetadataMatchWeightsService} from './metadata-match-weights.service';
import {API_CONFIG} from '../../core/config/api-config';
describe('MetadataMatchWeightsService', () => {
let service: MetadataMatchWeightsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
MetadataMatchWeightsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataMatchWeightsService)
);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should call recalculateAll and return void', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`,
{}
);
});
});
it('should handle error from recalculateAll', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.recalculateAll().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('MetadataMatchWeightsService - API Contract Tests', () => {
let service: MetadataMatchWeightsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
MetadataMatchWeightsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(MetadataMatchWeightsService));
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`,
{}
);
});
});
describe('Request payload contract', () => {
it('should send empty object as payload for recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.any(String),
{}
);
});
});
describe('Response type contract', () => {
it('should expect void from recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -3,29 +3,6 @@ import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface MetadataMatchWeights {
title: number;
subtitle: number;
description: number;
publisher: number;
publishedDate: number;
authors: number;
categories: number;
seriesName: number;
seriesNumber: number;
isbn13: number;
isbn10: number;
pageCount: number;
language: number;
amazonRating: number;
amazonReviewCount: number;
goodreadsRating: number;
goodreadsReviewCount: number;
hardcoverRating: number;
hardcoverReviewCount: number;
coverImage: number;
}
@Injectable({providedIn: 'root'})
export class MetadataMatchWeightsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`;
@@ -0,0 +1,241 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of} from 'rxjs';
import {MetadataProgressService} from './metadata-progress.service';
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../model/metadata-batch-progress.model';
import {MetadataTaskService} from '../../features/book/service/metadata-task';
import {UserService} from '../../features/settings/user-management/user.service';
describe('MetadataProgressService', () => {
let service: MetadataProgressService;
let metadataTaskServiceMock: any;
let userServiceMock: any;
const mockUserState = {
user: {
permissions: {
admin: true,
canEditMetadata: true
}
}
};
const mockTasks: MetadataBatchProgressNotification[] = [
{taskId: '1', completed: 10, total: 100, message: '', status: MetadataBatchStatus.IN_PROGRESS, review: false},
{taskId: '2', completed: 100, total: 100, message: '', status: MetadataBatchStatus.COMPLETED, review: false}
];
beforeEach(() => {
metadataTaskServiceMock = {
getActiveTasks: vi.fn().mockReturnValue(of(mockTasks))
};
userServiceMock = {
userState$: of(mockUserState)
};
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataProgressService)
);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should initialize and fetch active tasks if user has permissions', () => {
expect(metadataTaskServiceMock.getActiveTasks).toHaveBeenCalled();
});
it('should not fetch active tasks if user has no permissions', () => {
userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}});
metadataTaskServiceMock.getActiveTasks.mockClear();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
TestBed.inject(MetadataProgressService);
expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled();
});
it('should handle incoming progress and update state', () => {
const progress: MetadataBatchProgressNotification = {
taskId: '3',
completed: 50,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let update: MetadataBatchProgressNotification | undefined;
const sub = service.progressUpdates$.subscribe(val => update = val);
service.handleIncomingProgress(progress);
expect(update).toEqual(progress);
expect(service.getActiveTasks()['3']).toEqual(progress);
sub.unsubscribe();
});
it('should clear task from active tasks', () => {
const progress: MetadataBatchProgressNotification = {
taskId: '4',
completed: 20,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
service.handleIncomingProgress(progress);
expect(service.getActiveTasks()['4']).toBeDefined();
service.clearTask('4');
expect(service.getActiveTasks()['4']).toBeUndefined();
});
it('should complete all subjects on destroy', () => {
const spy = vi.spyOn(service['progressUpdatesSubject'], 'complete');
service.ngOnDestroy();
expect(spy).toHaveBeenCalled();
});
});
describe('MetadataProgressService - API Contract Tests', () => {
let service: MetadataProgressService;
let metadataTaskServiceMock: any;
let userServiceMock: any;
beforeEach(() => {
metadataTaskServiceMock = {
getActiveTasks: vi.fn().mockReturnValue(of([]))
};
userServiceMock = {
userState$: of({
user: {
permissions: {
admin: true,
canEditMetadata: true
}
}
})
};
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataProgressService)
);
});
describe('MetadataBatchProgressNotification contract', () => {
it('should require taskId, completed, total, message, status, and review fields', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'abc',
completed: 42,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
expect(progress).toHaveProperty('taskId');
expect(progress).toHaveProperty('completed');
expect(progress).toHaveProperty('total');
expect(progress).toHaveProperty('message');
expect(progress).toHaveProperty('status');
expect(progress).toHaveProperty('review');
});
});
describe('Active tasks structure', () => {
it('should return an object with taskId keys and progress notification values', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'xyz',
completed: 99,
total: 100,
message: '',
status: MetadataBatchStatus.COMPLETED,
review: false
};
service.handleIncomingProgress(progress);
const active = service.getActiveTasks();
expect(active).toHaveProperty('xyz');
expect(active['xyz']).toEqual(progress);
});
});
describe('Observable contract', () => {
it('should emit progress updates on progressUpdates$', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'emit',
completed: 1,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let emitted: MetadataBatchProgressNotification | undefined;
const sub = service.progressUpdates$.subscribe(val => {
emitted = val;
});
service.handleIncomingProgress(progress);
expect(emitted).toEqual(progress);
sub.unsubscribe();
});
it('should emit active tasks on activeTasks$', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'active',
completed: 2,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let emitted: { [taskId: string]: MetadataBatchProgressNotification } | undefined;
const sub = service.activeTasks$.subscribe(val => {
emitted = val;
});
service.handleIncomingProgress(progress);
expect(emitted && emitted['active']).toEqual(progress);
sub.unsubscribe();
});
});
describe('Permissions contract', () => {
it('should only fetch tasks if user has admin or canEditMetadata', () => {
userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}});
metadataTaskServiceMock.getActiveTasks.mockClear();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
TestBed.inject(MetadataProgressService);
expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,84 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {Title} from '@angular/platform-browser';
import {PageTitleService} from './page-title.service';
import {Book, BookType} from '../../features/book/model/book.model';
describe('PageTitleService', () => {
let service: PageTitleService;
let titleService: Title;
let setTitleMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
setTitleMock = vi.fn();
TestBed.configureTestingModule({
providers: [
PageTitleService,
{ provide: Title, useValue: { setTitle: setTitleMock } }
]
});
service = TestBed.inject(PageTitleService);
titleService = TestBed.inject(Title);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should set page title with setPageTitle', () => {
service.setPageTitle('Dashboard');
expect(setTitleMock).toHaveBeenCalledWith('Dashboard - BookLore');
});
it('should set book page title with all fields', () => {
const book: Book = {
id: 1,
bookType: 'PDF' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.pdf',
metadata: {
bookId: 1,
title: 'Book Title',
seriesName: 'Series',
authors: ['Author1', 'Author2']
}
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/Book Title (Series series) - by Author1 and Author2 (PDF) - BookLore'
);
});
it('should set book page title without series and authors', () => {
const book: Book = {
id: 1,
bookType: 'EPUB' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.epub',
metadata: {
bookId: 1,
title: 'Book Title'
}
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/Book Title (EPUB) - BookLore'
);
});
it('should set book page title with fallback to fileName', () => {
const book: Book = {
id: 1,
bookType: 'CBX' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.cbx'
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/file.cbx (CBX) - BookLore'
);
});
});
@@ -4,7 +4,7 @@ import {Book} from "../../features/book/model/book.model";
@Injectable({providedIn: 'root'})
export class PageTitleService {
private titleService = inject(Title)
protected titleService = inject(Title)
private appName = 'BookLore'
@@ -22,4 +22,4 @@ export class PageTitleService {
setPageTitle(pageTitle: string) {
this.titleService.setTitle([pageTitle, this.appName].filter(part => part).join(' - '));
}
}
}
@@ -0,0 +1,252 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {CreateReadingSessionDto, PageableResponse, ReadingSessionApiService, ReadingSessionResponse} from './reading-session-api.service';
import {BookType} from '../../features/book/model/book.model';
describe('ReadingSessionApiService', () => {
let service: ReadingSessionApiService;
let httpClientMock: any;
const BASE_URL = '/api/v1/reading-sessions';
const mockSessionDto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF' as BookType,
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s',
startProgress: 0,
endProgress: 10,
progressDelta: 10,
startLocation: 'start',
endLocation: 'end'
};
const mockPageableResponse: PageableResponse<ReadingSessionResponse> = {
content: [{
id: 1,
bookId: 1,
bookTitle: 'Book',
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
startProgress: 0,
endProgress: 10,
progressDelta: 10,
startLocation: 'start',
endLocation: 'end',
createdAt: '2024-01-01T00:10:01Z'
}],
pageable: {
pageNumber: 0,
pageSize: 5,
sort: {empty: true, sorted: false, unsorted: true},
offset: 0,
paged: true,
unpaged: false
},
totalElements: 1,
last: true,
totalPages: 1,
numberOfElements: 1,
first: true,
size: 5,
number: 0,
sort: {empty: true, sorted: false, unsorted: true},
empty: false
};
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
ReadingSessionApiService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService));
});
it('should call POST to createSession', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.createSession(mockSessionDto).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringContaining(BASE_URL),
mockSessionDto
);
});
});
it('should call GET to getSessionsByBookId with correct params', () => {
httpClientMock.get.mockReturnValue(of(mockPageableResponse));
service.getSessionsByBookId(1, 2, 10).subscribe(resp => {
expect(resp).toEqual(mockPageableResponse);
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringContaining(`${BASE_URL}/book/1`),
expect.objectContaining({
params: expect.any(HttpParams)
})
);
const params = httpClientMock.get.mock.calls[0][1].params;
expect(params.get('page')).toBe('2');
expect(params.get('size')).toBe('10');
});
});
it('should default to page=0 and size=5 if not provided', () => {
httpClientMock.get.mockReturnValue(of(mockPageableResponse));
service.getSessionsByBookId(2).subscribe();
const params = httpClientMock.get.mock.calls[0][1].params;
expect(params.get('page')).toBe('0');
expect(params.get('size')).toBe('5');
});
it('should handle error in createSession', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createSession(mockSessionDto).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should handle error in getSessionsByBookId', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getSessionsByBookId(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should send beacon successfully', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
(globalThis.navigator as any) = {sendBeacon: sendBeaconMock};
const result = service.sendSessionBeacon(mockSessionDto);
expect(sendBeaconMock).toHaveBeenCalledWith(
expect.stringContaining(BASE_URL),
expect.any(Blob)
);
expect(result).toBe(true);
});
it('should return false if sendBeacon throws', () => {
(globalThis.navigator as any) = {
sendBeacon: vi.fn().mockImplementation(() => {
throw new Error('fail');
})
};
const result = service.sendSessionBeacon(mockSessionDto);
expect(result).toBe(false);
});
});
describe('ReadingSessionApiService - API Contract Tests', () => {
let service: ReadingSessionApiService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
ReadingSessionApiService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService));
});
it('should call correct endpoint for createSession', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const dto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s'
};
service.createSession(dto).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions$/),
dto
);
});
it('should call correct endpoint for getSessionsByBookId', () => {
httpClientMock.get.mockReturnValue(of({content: []}));
service.getSessionsByBookId(123).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions\/book\/123$/),
expect.objectContaining({params: expect.any(HttpParams)})
);
});
it('should send beacon to correct endpoint', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
(globalThis.navigator as any) = {sendBeacon: sendBeaconMock};
const dto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s'
};
service.sendSessionBeacon(dto);
expect(sendBeaconMock).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions$/),
expect.any(Blob)
);
});
it('should expect PageableResponse<ReadingSessionResponse> from getSessionsByBookId', () => {
const mockResponse: PageableResponse<ReadingSessionResponse> = {
content: [],
pageable: {
pageNumber: 0,
pageSize: 5,
sort: {empty: true, sorted: false, unsorted: true},
offset: 0,
paged: true,
unpaged: false
},
totalElements: 0,
last: true,
totalPages: 1,
numberOfElements: 0,
first: true,
size: 5,
number: 0,
sort: {empty: true, sorted: false, unsorted: true},
empty: true
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service.getSessionsByBookId(1).subscribe(resp => {
expect(resp).toHaveProperty('content');
expect(Array.isArray(resp.content)).toBe(true);
expect(resp).toHaveProperty('totalElements');
});
});
});
@@ -0,0 +1,250 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {BookType} from '../../features/book/model/book.model';
import {ReadingSessionService, ReadingSession} from './reading-session.service';
import {ReadingSessionApiService, CreateReadingSessionDto} from './reading-session-api.service';
import {of} from 'rxjs';
describe('ReadingSessionService', () => {
let service: ReadingSessionService;
let apiServiceMock: any;
const now = new Date();
const mockSession: ReadingSession = {
bookId: 42,
bookType: 'PDF' as BookType,
startTime: now,
startLocation: 'start-cfi',
startProgress: 10
};
beforeEach(() => {
apiServiceMock = {
createSession: vi.fn().mockReturnValue(of(void 0)),
sendSessionBeacon: vi.fn().mockReturnValue(true)
};
TestBed.configureTestingModule({
providers: [
ReadingSessionService,
{provide: ReadingSessionApiService, useValue: apiServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionService));
});
it('should start a session', () => {
service.startSession(1, 'PDF', 'loc', 5);
expect(service.isSessionActive()).toBe(true);
});
it('should end a session and send to backend if duration is sufficient', () => {
vi.useFakeTimers();
service.startSession(1, 'PDF', 'loc', 5);
// Simulate session duration > MIN_SESSION_DURATION_SECONDS
(service as any).currentSession!.startTime = new Date(Date.now() - 60000);
service.endSession('endloc', 10);
expect(apiServiceMock.createSession).toHaveBeenCalled();
expect(service.isSessionActive()).toBe(false);
vi.useRealTimers();
});
it('should discard session if duration is too short', () => {
vi.useFakeTimers();
service.startSession(1, 'PDF', 'loc', 5);
(service as any).currentSession!.startTime = new Date(Date.now() - 10000);
service.endSession('endloc', 10);
expect(apiServiceMock.createSession).not.toHaveBeenCalled();
expect(service.isSessionActive()).toBe(false);
vi.useRealTimers();
});
it('should update progress', () => {
service.startSession(1, 'PDF', 'loc', 5);
service.updateProgress('newloc', 15);
const session = (service as any).currentSession;
expect(session.endLocation).toBe('newloc');
expect(session.endProgress).toBe(15);
});
it('should end session synchronously with sendSessionBeacon', () => {
service.startSession(1, 'PDF', 'loc', 5);
(service as any).currentSession!.startTime = new Date(Date.now() - 60000);
service['endSessionSync']();
expect(apiServiceMock.sendSessionBeacon).toHaveBeenCalled();
expect(service.isSessionActive()).toBe(false);
});
it('should not send beacon if session duration is too short', () => {
service.startSession(1, 'PDF', 'loc', 5);
(service as any).currentSession!.startTime = new Date(Date.now() - 10000);
service['endSessionSync']();
expect(apiServiceMock.sendSessionBeacon).not.toHaveBeenCalled();
expect(service.isSessionActive()).toBe(false);
});
it('should return false for isSessionActive when no session', () => {
expect(service.isSessionActive()).toBe(false);
});
it('should build session data correctly', () => {
const endTime = new Date(now.getTime() + 60000);
const session: ReadingSession = {
bookId: 1,
bookType: 'PDF',
startTime: now,
endTime,
durationSeconds: 60,
startProgress: 10,
endProgress: 20,
progressDelta: 10,
startLocation: 'loc1',
endLocation: 'loc2'
};
const dto = (service as any).buildSessionData(session, endTime, 60);
expect(dto.bookId).toBe(1);
expect(dto.bookType).toBe('PDF');
expect(dto.durationSeconds).toBe(60);
expect(dto.startProgress).toBe(10);
expect(dto.endProgress).toBe(20);
expect(dto.progressDelta).toBe(10);
expect(dto.startLocation).toBe('loc1');
expect(dto.endLocation).toBe('loc2');
expect(typeof dto.startTime).toBe('string');
expect(typeof dto.endTime).toBe('string');
expect(dto.durationFormatted).toBe('1m 0s');
});
it('should format duration correctly', () => {
expect((service as any).formatDuration(3661)).toBe('1h 1m 1s');
expect((service as any).formatDuration(61)).toBe('1m 1s');
expect((service as any).formatDuration(10)).toBe('10s');
});
});
describe('ReadingSessionService - API Contract Tests', () => {
let service: ReadingSessionService;
let apiServiceMock: any;
beforeEach(() => {
apiServiceMock = {
createSession: vi.fn().mockReturnValue(of(void 0)),
sendSessionBeacon: vi.fn().mockReturnValue(true)
};
TestBed.configureTestingModule({
providers: [
ReadingSessionService,
{provide: ReadingSessionApiService, useValue: apiServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionService));
});
it('should call createSession with correct payload', () => {
const session: ReadingSession = {
bookId: 1,
bookType: 'PDF',
startTime: new Date(Date.now() - 60000),
endTime: new Date(),
durationSeconds: 60,
startProgress: 10,
endProgress: 20,
progressDelta: 10,
startLocation: 'loc1',
endLocation: 'loc2'
};
(service as any).sendSessionToBackend(session);
expect(apiServiceMock.createSession).toHaveBeenCalledWith(expect.objectContaining({
bookId: 1,
bookType: 'PDF',
durationSeconds: 60,
startProgress: 10,
endProgress: 20,
progressDelta: 10,
startLocation: 'loc1',
endLocation: 'loc2'
}));
});
it('should call sendSessionBeacon with correct payload', () => {
const session: ReadingSession = {
bookId: 2,
bookType: 'EPUB',
startTime: new Date(Date.now() - 120000),
startProgress: 0,
endProgress: 100,
progressDelta: 100,
startLocation: 'start',
endLocation: 'end'
};
const endTime = new Date();
const durationSeconds = 120;
const dto = (service as any).buildSessionData(session, endTime, durationSeconds);
(service as any).currentSession = session;
apiServiceMock.sendSessionBeacon.mockClear();
(service as any).endSessionSync();
expect(apiServiceMock.sendSessionBeacon).toHaveBeenCalledWith(expect.objectContaining({
bookId: 2,
bookType: 'EPUB',
startLocation: 'start',
endLocation: 'end'
}));
});
it('should not call createSession if endTime or durationSeconds missing', () => {
const session: ReadingSession = {
bookId: 1,
bookType: 'PDF',
startTime: new Date()
// missing endTime and durationSeconds
};
(service as any).sendSessionToBackend(session);
expect(apiServiceMock.createSession).not.toHaveBeenCalled();
});
it('should not call sendSessionBeacon if duration too short', () => {
const session: ReadingSession = {
bookId: 1,
bookType: 'PDF',
startTime: new Date(Date.now() - 10000)
};
(service as any).currentSession = session;
apiServiceMock.sendSessionBeacon.mockClear();
(service as any).endSessionSync();
expect(apiServiceMock.sendSessionBeacon).not.toHaveBeenCalled();
});
it('should send correct types in CreateReadingSessionDto', () => {
const session: ReadingSession = {
bookId: 3,
bookType: 'CBX',
startTime: new Date(Date.now() - 180000),
endTime: new Date(),
durationSeconds: 180,
startProgress: 0,
endProgress: 50,
progressDelta: 50,
startLocation: 'foo',
endLocation: 'bar'
};
const dto: CreateReadingSessionDto = (service as any).buildSessionData(session, session.endTime!, session.durationSeconds!);
expect(typeof dto.bookId).toBe('number');
expect(typeof dto.bookType).toBe('string');
expect(typeof dto.startTime).toBe('string');
expect(typeof dto.endTime).toBe('string');
expect(typeof dto.durationSeconds).toBe('number');
expect(typeof dto.durationFormatted).toBe('string');
expect(typeof dto.startProgress).toBe('number');
expect(typeof dto.endProgress).toBe('number');
expect(typeof dto.progressDelta).toBe('number');
expect(typeof dto.startLocation).toBe('string');
expect(typeof dto.endLocation).toBe('string');
});
});
@@ -0,0 +1,70 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of, throwError} from 'rxjs';
import {SettingsHelperService} from './settings-helper.service';
import {AppSettingsService} from './app-settings.service';
import {MessageService} from 'primeng/api';
describe('SettingsHelperService', () => {
let service: SettingsHelperService;
let appSettingsServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
appSettingsServiceMock = {
saveSettings: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
SettingsHelperService,
{provide: AppSettingsService, useValue: appSettingsServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(SettingsHelperService));
});
it('should call saveSettings and show success message on success', () => {
appSettingsServiceMock.saveSettings.mockReturnValue(of(void 0));
service.saveSetting('theme', 'dark').subscribe(result => {
expect(result).toBeUndefined();
expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'dark'}]);
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Settings Saved',
detail: 'The settings were successfully saved!'
});
});
});
it('should call saveSettings and show error message on error', () => {
appSettingsServiceMock.saveSettings.mockReturnValue(throwError(() => new Error('fail')));
service.saveSetting('theme', 'light').subscribe({
error: (err: any) => {
expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'light'}]);
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Error',
detail: 'There was an error saving the settings.'
});
expect(err).toBeInstanceOf(Error);
}
});
});
it('should show custom message via showMessage', () => {
service.showMessage('success', 'Yay', 'It worked!');
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Yay',
detail: 'It worked!'
});
});
});
@@ -25,18 +25,6 @@ export class SettingsHelperService {
return observable;
}
saveMultipleSettings(settings: { key: string, newValue: unknown }[]): Observable<void> {
const observable = this.appSettingsService.saveSettings(settings);
observable.subscribe({
next: () => this.showSuccessMessage(),
error: (error) => {
console.error('Failed to save settings:', error);
this.showErrorMessage();
}
});
return observable;
}
private showSuccessMessage(): void {
this.messageService.add({
severity: 'success',
@@ -1,26 +0,0 @@
import {inject, Injectable} from '@angular/core';
import {MessageService} from 'primeng/api';
@Injectable({
providedIn: 'root'
})
export class ToastService {
private messageService = inject(MessageService);
showSuccess(summary: string, detail: string) {
this.messageService.add({ severity: 'success', summary, detail });
}
showError(summary: string, detail: string) {
this.messageService.add({ severity: 'error', summary, detail });
}
showInfo(summary: string, detail: string) {
this.messageService.add({ severity: 'info', summary, detail });
}
showWarning(summary: string, detail: string) {
this.messageService.add({ severity: 'warn', summary, detail });
}
}
@@ -0,0 +1,362 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {UrlHelperService} from './url-helper.service';
import {AuthService} from './auth.service';
import {BookService} from '../../features/book/service/book.service';
import {Router, UrlTree} from '@angular/router';
import {Book} from '../../features/book/model/book.model';
import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component';
describe('UrlHelperService', () => {
let service: UrlHelperService;
let authServiceMock: any;
let bookServiceMock: any;
let routerMock: any;
beforeEach(() => {
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
bookServiceMock = {
getBookByIdFromState: vi.fn()
};
routerMock = {
createUrlTree: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UrlHelperService,
{provide: AuthService, useValue: authServiceMock},
{provide: BookService, useValue: bookServiceMock},
{provide: Router, useValue: routerMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService));
});
describe('Token handling', () => {
it('should append token from OIDC', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token');
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = (service as any).appendToken('http://test');
expect(url).toContain('token=oidc-token');
});
it('should append token from internal', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue('internal-token');
const url = (service as any).appendToken('http://test');
expect(url).toContain('token=internal-token');
});
it('should not append token if none present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = (service as any).appendToken('http://test');
expect(url).toBe('http://test');
});
it('should append token with correct separator', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect((service as any).appendToken('http://a')).toBe('http://a?token=tok');
expect((service as any).appendToken('http://a?x=1')).toBe('http://a?x=1&token=tok');
});
it('should handle empty string token gracefully', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('');
authServiceMock.getInternalAccessToken.mockReturnValue('');
const url = (service as any).appendToken('http://test');
expect(url).toBe('http://test');
});
it('should handle undefined url in appendToken', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect(() => (service as any).appendToken(undefined)).toThrow();
});
});
describe('getThumbnailUrl', () => {
it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => {
const book: Book = {id: 1, metadata: {title: 'T', authors: ['A']}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url');
const url = service.getThumbnailUrl(1);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url');
genSpy.mockRestore();
});
it('should use API url if coverUpdatedOn present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(2, 'v123');
expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?v123.*token=tok/);
});
it('should use API url if no book in state', () => {
bookServiceMock.getBookByIdFromState.mockReturnValue(undefined);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(3);
expect(url).toMatch(/\/api\/v1\/media\/book\/3\/thumbnail\?token=tok/);
});
it('should handle book with no metadata', () => {
const book: Book = {id: 1} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(1);
expect(url).toMatch(/\/api\/v1\/media\/book\/1\/thumbnail\?token=tok/);
});
it('should handle book with empty metadata', () => {
const book: Book = {id: 1, metadata: {}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url');
const url = service.getThumbnailUrl(1);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url');
genSpy.mockRestore();
});
it('should handle coverUpdatedOn with empty string', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(2, '');
expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?token=tok/);
});
});
describe('getThumbnailUrl1', () => {
it('should always use API url and append token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl1(4, 'v456');
expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?v456.*token=tok/);
});
it('should handle undefined coverUpdatedOn', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl1(4);
expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?token=tok/);
});
});
describe('getCoverUrl', () => {
it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => {
const book: Book = {id: 5, metadata: {title: 'T', authors: ['A']}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2');
const url = service.getCoverUrl(5);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url2');
genSpy.mockRestore();
});
it('should use API url if coverUpdatedOn present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(6, 'v789');
expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?v789.*token=tok/);
});
it('should use API url if no book in state', () => {
bookServiceMock.getBookByIdFromState.mockReturnValue(undefined);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(7);
expect(url).toMatch(/\/api\/v1\/media\/book\/7\/cover\?token=tok/);
});
it('should handle book with no metadata', () => {
const book: Book = {id: 5} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(5);
expect(url).toMatch(/\/api\/v1\/media\/book\/5\/cover\?token=tok/);
});
it('should handle book with empty metadata', () => {
const book: Book = {id: 5, metadata: {}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2');
const url = service.getCoverUrl(5);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url2');
genSpy.mockRestore();
});
it('should handle coverUpdatedOn with empty string', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(6, '');
expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?token=tok/);
});
});
describe('getBackupCoverUrl', () => {
it('should return backup cover url with token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getBackupCoverUrl(8);
expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover\?token=tok/);
});
it('should handle missing token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getBackupCoverUrl(8);
expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover$/);
});
});
describe('getBookdropCoverUrl', () => {
it('should return bookdrop cover url with token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getBookdropCoverUrl(9);
expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover\?token=tok/);
});
it('should handle missing token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getBookdropCoverUrl(9);
expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover$/);
});
});
describe('getBookUrl', () => {
it('should call router.createUrlTree with correct args', () => {
const book: Book = {id: 10} as any;
routerMock.createUrlTree.mockReturnValue('url-tree');
const urlTree = service.getBookUrl(book);
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', 10], {queryParams: {tab: 'view'}});
expect(urlTree).toBe('url-tree');
});
it('should handle book with undefined id', () => {
routerMock.createUrlTree.mockReturnValue('url-tree');
const minimalBook = {
id: undefined,
bookType: undefined,
libraryId: undefined,
libraryName: undefined
} as any;
const urlTree = service.getBookUrl(minimalBook);
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', undefined], {queryParams: {tab: 'view'}});
expect(urlTree).toBe('url-tree');
});
});
describe('filterBooksBy', () => {
it('should route to /series if filterKey is series', () => {
routerMock.createUrlTree.mockReturnValue('series-url');
const urlTree = service.filterBooksBy('series', 'My Series');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/series', encodeURIComponent('My Series')]);
expect(urlTree).toBe('series-url');
});
it('should route to /all-books with correct queryParams for other filters', () => {
routerMock.createUrlTree.mockReturnValue('all-books-url');
const urlTree = service.filterBooksBy('author', 'Author Name');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
{
queryParams: {
view: 'grid',
sort: 'title',
direction: 'asc',
sidebar: true,
filter: 'author:' + encodeURIComponent('Author Name')
}
}
);
expect(urlTree).toBe('all-books-url');
});
it('should handle empty filterValue', () => {
routerMock.createUrlTree.mockReturnValue('empty-filter-url');
const urlTree = service.filterBooksBy('author', '');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: 'author:'
})
})
);
expect(urlTree).toBe('empty-filter-url');
});
it('should handle empty filterKey', () => {
routerMock.createUrlTree.mockReturnValue('empty-key-url');
const urlTree = service.filterBooksBy('', 'SomeValue');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: ':' + encodeURIComponent('SomeValue')
})
})
);
expect(urlTree).toBe('empty-key-url');
});
});
});
describe('UrlHelperService - API Contract Tests', () => {
let service: UrlHelperService;
let authServiceMock: any;
let bookServiceMock: any;
let routerMock: any;
beforeEach(() => {
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
bookServiceMock = {
getBookByIdFromState: vi.fn()
};
routerMock = {
createUrlTree: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UrlHelperService,
{provide: AuthService, useValue: authServiceMock},
{provide: BookService, useValue: bookServiceMock},
{provide: Router, useValue: routerMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService));
});
it('should generate correct API endpoints for covers and thumbnails', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect(service.getThumbnailUrl1(11)).toMatch(/\/api\/v1\/media\/book\/11\/thumbnail\?token=tok/);
expect(service.getCoverUrl(12, 'v1')).toMatch(/\/api\/v1\/media\/book\/12\/cover\?v1.*token=tok/);
expect(service.getBackupCoverUrl(13)).toMatch(/\/api\/v1\/media\/book\/13\/backup-cover\?token=tok/);
expect(service.getBookdropCoverUrl(14)).toMatch(/\/api\/v1\/media\/bookdrop\/14\/cover\?token=tok/);
});
it('should encode filter values in filterBooksBy', () => {
routerMock.createUrlTree.mockReturnValue('tree');
service.filterBooksBy('author', 'A&B');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: 'author:' + encodeURIComponent('A&B')
})
})
);
});
it('should always return a string or UrlTree from getBookUrl/filterBooksBy', () => {
routerMock.createUrlTree.mockReturnValueOnce('tree1').mockReturnValueOnce({} as UrlTree);
expect(typeof service.getBookUrl({id: 1} as any)).toMatch(/string|object/);
expect(typeof service.filterBooksBy('series', 'X')).toMatch(/string|object/);
});
});
@@ -0,0 +1,138 @@
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 {AppVersion, ReleaseNote, VersionService} from './version.service';
describe('VersionService', () => {
let service: VersionService;
let httpClientMock: any;
const mockVersion: AppVersion = {
current: '1.0.0',
latest: '1.2.0'
};
const mockChangelog: ReleaseNote[] = [
{
version: '1.2.0',
name: 'Release 1.2.0',
changelog: 'Bug fixes and improvements',
url: 'https://example.com/release/1.2.0',
publishedAt: '2024-01-01T00:00:00Z'
}
];
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
VersionService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(VersionService));
});
it('should get version', () => {
httpClientMock.get.mockReturnValue(of(mockVersion));
service.getVersion().subscribe(version => {
expect(version).toEqual(mockVersion);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/));
});
});
it('should get changelog', () => {
httpClientMock.get.mockReturnValue(of(mockChangelog));
service.getChangelog().subscribe(changelog => {
expect(changelog).toEqual(mockChangelog);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/));
});
});
it('should handle getVersion error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getVersion().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should handle getChangelog error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getChangelog().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('VersionService - API Contract Tests', () => {
let service: VersionService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
VersionService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(VersionService));
});
it('should expect AppVersion from getVersion', () => {
const response: AppVersion = {current: '1.0.0', latest: '1.2.0'};
httpClientMock.get.mockReturnValue(of(response));
service.getVersion().subscribe(version => {
expect(typeof version.current).toBe('string');
expect(typeof version.latest).toBe('string');
});
});
it('should expect ReleaseNote[] from getChangelog', () => {
const response: ReleaseNote[] = [
{
version: '1.2.0',
name: 'Release 1.2.0',
changelog: 'Bug fixes and improvements',
url: 'https://example.com/release/1.2.0',
publishedAt: '2024-01-01T00:00:00Z'
}
];
httpClientMock.get.mockReturnValue(of(response));
service.getChangelog().subscribe(notes => {
expect(Array.isArray(notes)).toBe(true);
expect(notes[0]).toHaveProperty('version');
expect(notes[0]).toHaveProperty('name');
expect(notes[0]).toHaveProperty('changelog');
expect(notes[0]).toHaveProperty('url');
expect(notes[0]).toHaveProperty('publishedAt');
});
});
it('should call correct endpoints', () => {
httpClientMock.get.mockReturnValue(of({}));
service.getVersion().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/));
service.getChangelog().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/));
});
});