Add tests and fix tests

This commit is contained in:
Yana De Pauw
2021-03-04 17:10:01 +01:00
parent d07f44ac41
commit b18f9c7c9f
47 changed files with 937 additions and 454 deletions

View File

@@ -25,6 +25,9 @@ import { NotificationsServiceStub } from '../../../shared/testing/notifications-
import { RouterStub } from '../../../shared/testing/router.stub'; import { RouterStub } from '../../../shared/testing/router.stub';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service'; import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { RequestService } from '../../../core/data/request.service'; import { RequestService } from '../../../core/data/request.service';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('EPeopleRegistryComponent', () => { describe('EPeopleRegistryComponent', () => {
let component: EPeopleRegistryComponent; let component: EPeopleRegistryComponent;
@@ -37,6 +40,8 @@ describe('EPeopleRegistryComponent', () => {
let authorizationService: AuthorizationDataService; let authorizationService: AuthorizationDataService;
let modalService; let modalService;
let paginationService;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
mockEPeople = [EPersonMock, EPersonMock2]; mockEPeople = [EPersonMock, EPersonMock2];
ePersonDataServiceStub = { ePersonDataServiceStub = {
@@ -115,6 +120,16 @@ describe('EPeopleRegistryComponent', () => {
}); });
builderService = getMockFormBuilderService(); builderService = getMockFormBuilderService();
translateService = getMockTranslateService(); translateService = getMockTranslateService();
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({ TranslateModule.forRoot({
@@ -131,7 +146,8 @@ describe('EPeopleRegistryComponent', () => {
{ provide: AuthorizationDataService, useValue: authorizationService }, { provide: AuthorizationDataService, useValue: authorizationService },
{ provide: FormBuilderService, useValue: builderService }, { provide: FormBuilderService, useValue: builderService },
{ provide: Router, useValue: new RouterStub() }, { provide: Router, useValue: new RouterStub() },
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) } { provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) },
{ provide: PaginationService, useValue: paginationService }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();

View File

@@ -26,6 +26,9 @@ import { AuthorizationDataService } from '../../../../core/data/feature-authoriz
import { GroupDataService } from '../../../../core/eperson/group-data.service'; import { GroupDataService } from '../../../../core/eperson/group-data.service';
import { createPaginatedList } from '../../../../shared/testing/utils.test'; import { createPaginatedList } from '../../../../shared/testing/utils.test';
import { RequestService } from '../../../../core/data/request.service'; import { RequestService } from '../../../../core/data/request.service';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../core/cache/models/sort-options.model';
import { PaginationService } from '../../../../core/pagination/pagination.service';
describe('EPersonFormComponent', () => { describe('EPersonFormComponent', () => {
let component: EPersonFormComponent; let component: EPersonFormComponent;
@@ -38,6 +41,10 @@ describe('EPersonFormComponent', () => {
let authorizationService: AuthorizationDataService; let authorizationService: AuthorizationDataService;
let groupsDataService: GroupDataService; let groupsDataService: GroupDataService;
let paginationService: PaginationService;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
mockEPeople = [EPersonMock, EPersonMock2]; mockEPeople = [EPersonMock, EPersonMock2];
ePersonDataServiceStub = { ePersonDataServiceStub = {
@@ -104,6 +111,17 @@ describe('EPersonFormComponent', () => {
findAllByHref: createSuccessfulRemoteDataObject$(createPaginatedList([])), findAllByHref: createSuccessfulRemoteDataObject$(createPaginatedList([])),
getGroupRegistryRouterLink: '' getGroupRegistryRouterLink: ''
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {}
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({ TranslateModule.forRoot({
@@ -121,6 +139,7 @@ describe('EPersonFormComponent', () => {
{ provide: NotificationsService, useValue: new NotificationsServiceStub() }, { provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: AuthService, useValue: authService }, { provide: AuthService, useValue: authService },
{ provide: AuthorizationDataService, useValue: authorizationService }, { provide: AuthorizationDataService, useValue: authorizationService },
{ provide: PaginationService, useValue: paginationService },
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) } { provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

@@ -271,14 +271,12 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
})]); })]);
}), }),
switchMap(([eperson, findListOptions]) => { switchMap(([eperson, findListOptions]) => {
return this.groupsDataService.findAllByHref(eperson._links.groups.href, findListOptions); if (eperson != null) {
return this.groupsDataService.findAllByHref(eperson._links.groups.href, findListOptions);
}
return observableOf(undefined);
}) })
); );
// this.subs.push(combineLatest([activeEPerson$, paginationOption$]).subscribe(([eperson, options]) => {
// if (eperson != null) {
// this.groups = this.groupsDataService.findAllByHref(eperson._links.groups.href, options);
// }
// }));
this.canImpersonate$ = activeEPerson$.pipe( this.canImpersonate$ = activeEPerson$.pipe(
switchMap((eperson) => this.authorizationService.isAuthorized(FeatureID.LoginOnBehalfOf, hasValue(eperson) ? eperson.self : undefined)) switchMap((eperson) => this.authorizationService.isAuthorized(FeatureID.LoginOnBehalfOf, hasValue(eperson) ? eperson.self : undefined))

View File

@@ -26,6 +26,10 @@ import { getMockFormBuilderService } from '../../../../../shared/mocks/form-buil
import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loader.mock'; import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loader.mock';
import { NotificationsServiceStub } from '../../../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../../../shared/testing/notifications-service.stub';
import { RouterMock } from '../../../../../shared/mocks/router.mock'; import { RouterMock } from '../../../../../shared/mocks/router.mock';
import { PaginationComponentOptions } from '../../../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../../core/data/request.models';
import { PaginationService } from '../../../../../core/pagination/pagination.service';
describe('MembersListComponent', () => { describe('MembersListComponent', () => {
let component: MembersListComponent; let component: MembersListComponent;
@@ -39,6 +43,7 @@ describe('MembersListComponent', () => {
let allGroups; let allGroups;
let epersonMembers; let epersonMembers;
let subgroupMembers; let subgroupMembers;
let paginationService;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
activeGroup = GroupMock; activeGroup = GroupMock;
@@ -113,6 +118,17 @@ describe('MembersListComponent', () => {
}; };
builderService = getMockFormBuilderService(); builderService = getMockFormBuilderService();
translateService = getMockTranslateService(); translateService = getMockTranslateService();
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
clearPagination : {},
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({ TranslateModule.forRoot({
@@ -129,6 +145,7 @@ describe('MembersListComponent', () => {
{ provide: NotificationsService, useValue: new NotificationsServiceStub() }, { provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: FormBuilderService, useValue: builderService }, { provide: FormBuilderService, useValue: builderService },
{ provide: Router, useValue: new RouterMock() }, { provide: Router, useValue: new RouterMock() },
{ provide: PaginationService, useValue: paginationService },
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();

View File

@@ -35,6 +35,10 @@ import { getMockTranslateService } from '../../../../../shared/mocks/translate.s
import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loader.mock'; import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loader.mock';
import { NotificationsServiceStub } from '../../../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../../../shared/testing/notifications-service.stub';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { PaginationComponentOptions } from '../../../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../../core/data/request.models';
import { PaginationService } from '../../../../../core/pagination/pagination.service';
describe('SubgroupsListComponent', () => { describe('SubgroupsListComponent', () => {
let component: SubgroupsListComponent; let component: SubgroupsListComponent;
@@ -47,6 +51,7 @@ describe('SubgroupsListComponent', () => {
let subgroups; let subgroups;
let allGroups; let allGroups;
let routerStub; let routerStub;
let paginationService;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
activeGroup = GroupMock; activeGroup = GroupMock;
@@ -100,6 +105,18 @@ describe('SubgroupsListComponent', () => {
routerStub = new RouterMock(); routerStub = new RouterMock();
builderService = getMockFormBuilderService(); builderService = getMockFormBuilderService();
translateService = getMockTranslateService(); translateService = getMockTranslateService();
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {},
clearPagination: {}
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({ TranslateModule.forRoot({
@@ -115,6 +132,7 @@ describe('SubgroupsListComponent', () => {
{ provide: NotificationsService, useValue: new NotificationsServiceStub() }, { provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: FormBuilderService, useValue: builderService }, { provide: FormBuilderService, useValue: builderService },
{ provide: Router, useValue: routerStub }, { provide: Router, useValue: routerStub },
{ provide: PaginationService, useValue: paginationService },
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();

View File

@@ -28,6 +28,10 @@ import { TranslateLoaderMock } from '../../../shared/testing/translate-loader.mo
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { routeServiceStub } from '../../../shared/testing/route-service.stub'; import { routeServiceStub } from '../../../shared/testing/route-service.stub';
import { RouterMock } from '../../../shared/mocks/router.mock'; import { RouterMock } from '../../../shared/mocks/router.mock';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('GroupRegistryComponent', () => { describe('GroupRegistryComponent', () => {
let component: GroupsRegistryComponent; let component: GroupsRegistryComponent;
@@ -39,6 +43,7 @@ describe('GroupRegistryComponent', () => {
let mockGroups; let mockGroups;
let mockEPeople; let mockEPeople;
let paginationService;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
mockGroups = [GroupMock, GroupMock2]; mockGroups = [GroupMock, GroupMock2];
@@ -131,6 +136,16 @@ describe('GroupRegistryComponent', () => {
authorizationService = jasmine.createSpyObj('authorizationService', { authorizationService = jasmine.createSpyObj('authorizationService', {
isAuthorized: observableOf(true) isAuthorized: observableOf(true)
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {}
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({ TranslateModule.forRoot({
@@ -149,6 +164,7 @@ describe('GroupRegistryComponent', () => {
{ provide: RouteService, useValue: routeServiceStub }, { provide: RouteService, useValue: routeServiceStub },
{ provide: Router, useValue: new RouterMock() }, { provide: Router, useValue: new RouterMock() },
{ provide: AuthorizationDataService, useValue: authorizationService }, { provide: AuthorizationDataService, useValue: authorizationService },
{ provide: PaginationService, useValue: paginationService },
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) } { provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

@@ -9,7 +9,7 @@ import {
of as observableOf, of as observableOf,
Subscription Subscription
} from 'rxjs'; } from 'rxjs';
import { catchError, map, switchMap, take, tap } from 'rxjs/operators'; import { catchError, map, switchMap, take } from 'rxjs/operators';
import { DSpaceObjectDataService } from '../../../core/data/dspace-object-data.service'; import { DSpaceObjectDataService } from '../../../core/data/dspace-object-data.service';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service'; import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../../core/data/feature-authorization/feature-id'; import { FeatureID } from '../../../core/data/feature-authorization/feature-id';
@@ -25,9 +25,9 @@ import { RouteService } from '../../../core/services/route.service';
import { DSpaceObject } from '../../../core/shared/dspace-object.model'; import { DSpaceObject } from '../../../core/shared/dspace-object.model';
import { import {
getAllSucceededRemoteData, getAllSucceededRemoteData,
getAllSucceededRemoteDataPayload,
getFirstCompletedRemoteData, getFirstCompletedRemoteData,
getFirstSucceededRemoteData getFirstSucceededRemoteData,
getRemoteDataPayload
} from '../../../core/shared/operators'; } from '../../../core/shared/operators';
import { PageInfo } from '../../../core/shared/page-info.model'; import { PageInfo } from '../../../core/shared/page-info.model';
import { hasValue } from '../../../shared/empty.util'; import { hasValue } from '../../../shared/empty.util';
@@ -113,72 +113,58 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
* @param data Contains query param * @param data Contains query param
*/ */
search(data: any) { search(data: any) {
const query: string = data.query;
if (query != null && this.currentSearchQuery !== query) {
this.router.navigateByUrl(this.groupService.getGroupRegistryRouterLink());
this.currentSearchQuery = query;
this.config.currentPage = 1;
}
if (hasValue(this.searchSub)) { if (hasValue(this.searchSub)) {
this.searchSub.unsubscribe(); this.searchSub.unsubscribe();
this.subs = this.subs.filter((sub: Subscription) => sub !== this.searchSub); this.subs = this.subs.filter((sub: Subscription) => sub !== this.searchSub);
} }
this.searchSub = this.paginationService.getCurrentPagination(this.config.id, this.config).pipe( this.searchSub = this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((paginationOptions) => { switchMap((paginationOptions) => {
const query: string = data.query; const query: string = data.query;
if (query != null && this.currentSearchQuery !== query) { if (query != null && this.currentSearchQuery !== query) {
this.router.navigate([], {
queryParamsHandling: 'merge'
});
this.currentSearchQuery = query; this.currentSearchQuery = query;
this.paginationService.resetPage(this.config.id); this.paginationService.updateRouteWithUrl(this.config.id, [], {page: 1});
}
if (hasValue(this.searchSub)) {
this.searchSub.unsubscribe();
this.subs = this.subs.filter((sub: Subscription) => sub !== this.searchSub);
} }
return this.groupService.searchGroups(this.currentSearchQuery.trim(), { return this.groupService.searchGroups(this.currentSearchQuery.trim(), {
currentPage: paginationOptions.currentPage, currentPage: paginationOptions.currentPage,
elementsPerPage: paginationOptions.pageSize elementsPerPage: paginationOptions.pageSize
}).pipe(
getAllSucceededRemoteData()
switchMap((groups: PaginatedList<Group>) => {
if (groups.page.length === 0) {
return observableOf(buildPaginatedList(groups.pageInfo, []));
}
return observableCombineLatest(groups.page.map((group: Group) => {
if (!this.deletedGroupsIds.includes(group.id)) {
return observableCombineLatest([
this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(group) ? group.self : undefined),
this.hasLinkedDSO(group),
this.getSubgroups(group),
this.getMembers(group)
]).pipe(
map(([isAuthorized, hasLinkedDSO, subgroups, members]:
[boolean, boolean, RemoteData<PaginatedList<Group>>, RemoteData<PaginatedList<EPerson>>]) => {
const groupDtoModel: GroupDtoModel = new GroupDtoModel();
groupDtoModel.ableToDelete = isAuthorized && !hasLinkedDSO;
groupDtoModel.group = group;
groupDtoModel.subgroups = subgroups.payload;
groupDtoModel.epersons = members.payload;
return groupDtoModel;
}
)
);
}
})).pipe(map((dtos: GroupDtoModel[]) => {
return buildPaginatedList(groups.pageInfo, dtos);
}));
})
).
subscribe((value: PaginatedList<GroupDtoModel>) => {
this.groupsDto$.next(value);
this.pageInfoState$.next(value.pageInfo);
}); });
this.subs.push(this.searchSub); }),
getAllSucceededRemoteData(),
getRemoteDataPayload(),
switchMap((groups: PaginatedList<Group>) => {
if (groups.page.length === 0) {
return observableOf(buildPaginatedList(groups.pageInfo, []));
}
return observableCombineLatest(groups.page.map((group: Group) => {
if (!this.deletedGroupsIds.includes(group.id)) {
return observableCombineLatest([
this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(group) ? group.self : undefined),
this.hasLinkedDSO(group),
this.getSubgroups(group),
this.getMembers(group)
]).pipe(
map(([isAuthorized, hasLinkedDSO, subgroups, members]:
[boolean, boolean, RemoteData<PaginatedList<Group>>, RemoteData<PaginatedList<EPerson>>]) => {
const groupDtoModel: GroupDtoModel = new GroupDtoModel();
groupDtoModel.ableToDelete = isAuthorized && !hasLinkedDSO;
groupDtoModel.group = group;
groupDtoModel.subgroups = subgroups.payload;
groupDtoModel.epersons = members.payload;
return groupDtoModel;
}
)
);
}
})).pipe(map((dtos: GroupDtoModel[]) => {
return buildPaginatedList(groups.pageInfo, dtos);
}));
})
).subscribe((value: PaginatedList<GroupDtoModel>) => {
this.groupsDto$.next(value);
this.pageInfoState$.next(value.pageInfo);
});
this.subs.push(this.searchSub);
} }
/** /**

View File

@@ -23,6 +23,10 @@ import {
createSuccessfulRemoteDataObject$ createSuccessfulRemoteDataObject$
} from '../../../shared/remote-data.utils'; } from '../../../shared/remote-data.utils';
import { createPaginatedList } from '../../../shared/testing/utils.test'; import { createPaginatedList } from '../../../shared/testing/utils.test';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('BitstreamFormatsComponent', () => { describe('BitstreamFormatsComponent', () => {
let comp: BitstreamFormatsComponent; let comp: BitstreamFormatsComponent;
@@ -30,6 +34,7 @@ describe('BitstreamFormatsComponent', () => {
let bitstreamFormatService; let bitstreamFormatService;
let scheduler: TestScheduler; let scheduler: TestScheduler;
let notificationsServiceStub; let notificationsServiceStub;
let paginationService;
const bitstreamFormat1 = new BitstreamFormat(); const bitstreamFormat1 = new BitstreamFormat();
bitstreamFormat1.uuid = 'test-uuid-1'; bitstreamFormat1.uuid = 'test-uuid-1';
@@ -79,6 +84,10 @@ describe('BitstreamFormatsComponent', () => {
]; ];
const mockFormatsRD = createSuccessfulRemoteDataObject(createPaginatedList(mockFormatsList)); const mockFormatsRD = createSuccessfulRemoteDataObject(createPaginatedList(mockFormatsList));
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const initAsync = () => { const initAsync = () => {
notificationsServiceStub = new NotificationsServiceStub(); notificationsServiceStub = new NotificationsServiceStub();
@@ -95,13 +104,23 @@ describe('BitstreamFormatsComponent', () => {
clearBitStreamFormatRequests: observableOf('cleared') clearBitStreamFormatRequests: observableOf('cleared')
}); });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe], declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: BitstreamFormatDataService, useValue: bitstreamFormatService }, { provide: BitstreamFormatDataService, useValue: bitstreamFormatService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: NotificationsService, useValue: notificationsServiceStub } { provide: NotificationsService, useValue: notificationsServiceStub },
{ provide: PaginationService, useValue: paginationService }
] ]
}).compileComponents(); }).compileComponents();
}; };
@@ -217,13 +236,23 @@ describe('BitstreamFormatsComponent', () => {
clearBitStreamFormatRequests: observableOf('cleared') clearBitStreamFormatRequests: observableOf('cleared')
}); });
TestBed.configureTestingModule({ paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe], declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: BitstreamFormatDataService, useValue: bitstreamFormatService }, { provide: BitstreamFormatDataService, useValue: bitstreamFormatService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: NotificationsService, useValue: notificationsServiceStub } { provide: NotificationsService, useValue: notificationsServiceStub },
{ provide: PaginationService, useValue: paginationService }
] ]
}).compileComponents(); }).compileComponents();
} }
@@ -263,13 +292,22 @@ describe('BitstreamFormatsComponent', () => {
clearBitStreamFormatRequests: observableOf('cleared') clearBitStreamFormatRequests: observableOf('cleared')
}); });
TestBed.configureTestingModule({ paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe], declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: BitstreamFormatDataService, useValue: bitstreamFormatService }, { provide: BitstreamFormatDataService, useValue: bitstreamFormatService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: NotificationsService, useValue: notificationsServiceStub } { provide: NotificationsService, useValue: notificationsServiceStub },
{ provide: PaginationService, useValue: paginationService }
] ]
}).compileComponents(); }).compileComponents();
} }

View File

@@ -18,11 +18,16 @@ import { NotificationsServiceStub } from '../../../shared/testing/notifications-
import { RestResponse } from '../../../core/cache/response.models'; import { RestResponse } from '../../../core/cache/response.models';
import { MetadataSchema } from '../../../core/metadata/metadata-schema.model'; import { MetadataSchema } from '../../../core/metadata/metadata-schema.model';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { PaginationService } from '../../../core/pagination/pagination.service';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
describe('MetadataRegistryComponent', () => { describe('MetadataRegistryComponent', () => {
let comp: MetadataRegistryComponent; let comp: MetadataRegistryComponent;
let fixture: ComponentFixture<MetadataRegistryComponent>; let fixture: ComponentFixture<MetadataRegistryComponent>;
let registryService: RegistryService; let registryService: RegistryService;
let paginationService: PaginationService;
const mockSchemasList = [ const mockSchemasList = [
{ {
id: 1, id: 1,
@@ -62,6 +67,15 @@ describe('MetadataRegistryComponent', () => {
}; };
/* tslint:enable:no-empty */ /* tslint:enable:no-empty */
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
@@ -69,6 +83,7 @@ describe('MetadataRegistryComponent', () => {
providers: [ providers: [
{ provide: RegistryService, useValue: registryServiceStub }, { provide: RegistryService, useValue: registryServiceStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() } { provide: NotificationsService, useValue: new NotificationsServiceStub() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

@@ -23,6 +23,10 @@ import { MetadataSchema } from '../../../core/metadata/metadata-schema.model';
import { MetadataField } from '../../../core/metadata/metadata-field.model'; import { MetadataField } from '../../../core/metadata/metadata-field.model';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { VarDirective } from '../../../shared/utils/var.directive'; import { VarDirective } from '../../../shared/utils/var.directive';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('MetadataSchemaComponent', () => { describe('MetadataSchemaComponent', () => {
let comp: MetadataSchemaComponent; let comp: MetadataSchemaComponent;
@@ -125,6 +129,16 @@ describe('MetadataSchemaComponent', () => {
}) })
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
@@ -134,6 +148,7 @@ describe('MetadataSchemaComponent', () => {
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: Router, useValue: new RouterStub() }, { provide: Router, useValue: new RouterStub() },
{ provide: PaginationService, useValue: paginationService },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() } { provide: NotificationsService, useValue: new NotificationsServiceStub() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

@@ -18,11 +18,16 @@ import { BrowseEntrySearchOptions } from '../../core/browse/browse-entry-search-
import { toRemoteData } from '../+browse-by-metadata-page/browse-by-metadata-page.component.spec'; import { toRemoteData } from '../+browse-by-metadata-page/browse-by-metadata-page.component.spec';
import { VarDirective } from '../../shared/utils/var.directive'; import { VarDirective } from '../../shared/utils/var.directive';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../core/data/request.models';
import { PaginationService } from '../../core/pagination/pagination.service';
describe('BrowseByDatePageComponent', () => { describe('BrowseByDatePageComponent', () => {
let comp: BrowseByDatePageComponent; let comp: BrowseByDatePageComponent;
let fixture: ComponentFixture<BrowseByDatePageComponent>; let fixture: ComponentFixture<BrowseByDatePageComponent>;
let route: ActivatedRoute; let route: ActivatedRoute;
let paginationService;
const mockCommunity = Object.assign(new Community(), { const mockCommunity = Object.assign(new Community(), {
id: 'test-uuid', id: 'test-uuid',
@@ -65,6 +70,16 @@ describe('BrowseByDatePageComponent', () => {
detectChanges: () => fixture.detectChanges() detectChanges: () => fixture.detectChanges()
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
@@ -74,6 +89,7 @@ describe('BrowseByDatePageComponent', () => {
{ provide: BrowseService, useValue: mockBrowseService }, { provide: BrowseService, useValue: mockBrowseService },
{ provide: DSpaceObjectDataService, useValue: mockDsoService }, { provide: DSpaceObjectDataService, useValue: mockDsoService },
{ provide: Router, useValue: new RouterMock() }, { provide: Router, useValue: new RouterMock() },
{ provide: PaginationService, useValue: paginationService },
{ provide: ChangeDetectorRef, useValue: mockCdRef } { provide: ChangeDetectorRef, useValue: mockCdRef }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

@@ -14,7 +14,7 @@ import { RemoteData } from '../../core/data/remote-data';
import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model'; import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model';
import { PageInfo } from '../../core/shared/page-info.model'; import { PageInfo } from '../../core/shared/page-info.model';
import { BrowseEntrySearchOptions } from '../../core/browse/browse-entry-search-options.model'; import { BrowseEntrySearchOptions } from '../../core/browse/browse-entry-search-options.model';
import { SortDirection } from '../../core/cache/models/sort-options.model'; import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { Item } from '../../core/shared/item.model'; import { Item } from '../../core/shared/item.model';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { Community } from '../../core/shared/community.model'; import { Community } from '../../core/shared/community.model';
@@ -22,12 +22,18 @@ import { RouterMock } from '../../shared/mocks/router.mock';
import { BrowseEntry } from '../../core/shared/browse-entry.model'; import { BrowseEntry } from '../../core/shared/browse-entry.model';
import { VarDirective } from '../../shared/utils/var.directive'; import { VarDirective } from '../../shared/utils/var.directive';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { PaginationService } from '../../core/pagination/pagination.service';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
describe('BrowseByMetadataPageComponent', () => { describe('BrowseByMetadataPageComponent', () => {
let comp: BrowseByMetadataPageComponent; let comp: BrowseByMetadataPageComponent;
let fixture: ComponentFixture<BrowseByMetadataPageComponent>; let fixture: ComponentFixture<BrowseByMetadataPageComponent>;
let browseService: BrowseService; let browseService: BrowseService;
let route: ActivatedRoute; let route: ActivatedRoute;
let paginationService: PaginationService;
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const mockCommunity = Object.assign(new Community(), { const mockCommunity = Object.assign(new Community(), {
id: 'test-uuid', id: 'test-uuid',
@@ -82,6 +88,12 @@ describe('BrowseByMetadataPageComponent', () => {
params: observableOf({}) params: observableOf({})
}); });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getRouteParameterValue: observableOf('')
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
@@ -90,6 +102,7 @@ describe('BrowseByMetadataPageComponent', () => {
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: BrowseService, useValue: mockBrowseService }, { provide: BrowseService, useValue: mockBrowseService },
{ provide: DSpaceObjectDataService, useValue: mockDsoService }, { provide: DSpaceObjectDataService, useValue: mockDsoService },
{ provide: PaginationService, useValue: paginationService },
{ provide: Router, useValue: new RouterMock() } { provide: Router, useValue: new RouterMock() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
@@ -133,18 +146,23 @@ describe('BrowseByMetadataPageComponent', () => {
let result: BrowseEntrySearchOptions; let result: BrowseEntrySearchOptions;
beforeEach(() => { beforeEach(() => {
const paramsWithPaginationAndScope = { const paramsScope = {
page: 5,
pageSize: 10,
sortDirection: SortDirection.ASC,
sortField: 'fake-field',
scope: 'fake-scope' scope: 'fake-scope'
}; };
const paginationOptions = Object.assign(new PaginationComponentOptions(), {
currentPage: 5,
pageSize: 10,
});
const sortOptions = {
direction: SortDirection.ASC,
field: 'fake-field',
};
result = browseParamsToOptions(paramsWithPaginationAndScope, Object.assign({}), Object.assign({}), 'author'); result = browseParamsToOptions(paramsScope, paginationOptions, sortOptions, 'author');
}); });
it('should return BrowseEntrySearchOptions with the correct properties', () => { it('should return BrowseEntrySearchOptions with the correct properties', () => {
expect(result.metadataDefinition).toEqual('author'); expect(result.metadataDefinition).toEqual('author');
expect(result.pagination.currentPage).toEqual(5); expect(result.pagination.currentPage).toEqual(5);
expect(result.pagination.pageSize).toEqual(10); expect(result.pagination.pageSize).toEqual(10);

View File

@@ -18,6 +18,10 @@ import { BrowseService } from '../../core/browse/browse.service';
import { RouterMock } from '../../shared/mocks/router.mock'; import { RouterMock } from '../../shared/mocks/router.mock';
import { VarDirective } from '../../shared/utils/var.directive'; import { VarDirective } from '../../shared/utils/var.directive';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../core/data/request.models';
import { PaginationService } from '../../core/pagination/pagination.service';
describe('BrowseByTitlePageComponent', () => { describe('BrowseByTitlePageComponent', () => {
let comp: BrowseByTitlePageComponent; let comp: BrowseByTitlePageComponent;
@@ -61,6 +65,16 @@ describe('BrowseByTitlePageComponent', () => {
data: observableOf({ metadata: 'title' }) data: observableOf({ metadata: 'title' })
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
@@ -69,6 +83,7 @@ describe('BrowseByTitlePageComponent', () => {
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: BrowseService, useValue: mockBrowseService }, { provide: BrowseService, useValue: mockBrowseService },
{ provide: DSpaceObjectDataService, useValue: mockDsoService }, { provide: DSpaceObjectDataService, useValue: mockDsoService },
{ provide: PaginationService, useValue: paginationService },
{ provide: Router, useValue: new RouterMock() } { provide: Router, useValue: new RouterMock() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

@@ -18,6 +18,10 @@ import { PageInfo } from '../../core/shared/page-info.model';
import { HostWindowService } from '../../shared/host-window.service'; import { HostWindowService } from '../../shared/host-window.service';
import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub'; import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub';
import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service'; import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../../core/pagination/pagination.service';
import { getMockThemeService } from '../../shared/mocks/theme-service.mock'; import { getMockThemeService } from '../../shared/mocks/theme-service.mock';
import { ThemeService } from '../../shared/theme-support/theme.service'; import { ThemeService } from '../../shared/theme-support/theme.service';
@@ -113,6 +117,17 @@ describe('CommunityPageSubCollectionList Component', () => {
} }
}; };
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {}
});
themeService = getMockThemeService(); themeService = getMockThemeService();
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
@@ -128,6 +143,7 @@ describe('CommunityPageSubCollectionList Component', () => {
providers: [ providers: [
{ provide: CollectionDataService, useValue: collectionDataServiceStub }, { provide: CollectionDataService, useValue: collectionDataServiceStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService },
{ provide: SelectableListService, useValue: {} }, { provide: SelectableListService, useValue: {} },
{ provide: ThemeService, useValue: themeService }, { provide: ThemeService, useValue: themeService },
], ],
@@ -161,28 +177,4 @@ describe('CommunityPageSubCollectionList Component', () => {
const subComHead = fixture.debugElement.queryAll(By.css('h2')); const subComHead = fixture.debugElement.queryAll(By.css('h2'));
expect(subComHead.length).toEqual(0); expect(subComHead.length).toEqual(0);
}); });
it('should update list of collections on pagination change', () => {
subCollList = collections;
fixture.detectChanges();
const pagination = Object.create({
pagination:{
id: comp.pageId,
currentPage: 2,
pageSize: 5
},
sort: {
field: 'dc.title',
direction: 'ASC'
}
});
comp.onPaginationChange(pagination);
fixture.detectChanges();
const collList = fixture.debugElement.queryAll(By.css('li'));
expect(collList.length).toEqual(2);
expect(collList[0].nativeElement.textContent).toContain('Collection 6');
expect(collList[1].nativeElement.textContent).toContain('Collection 7');
});
}); });

View File

@@ -18,6 +18,10 @@ import { HostWindowService } from '../../shared/host-window.service';
import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub'; import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub';
import { CommunityDataService } from '../../core/data/community-data.service'; import { CommunityDataService } from '../../core/data/community-data.service';
import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service'; import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../../core/pagination/pagination.service';
import { getMockThemeService } from '../../shared/mocks/theme-service.mock'; import { getMockThemeService } from '../../shared/mocks/theme-service.mock';
import { ThemeService } from '../../shared/theme-support/theme.service'; import { ThemeService } from '../../shared/theme-support/theme.service';
@@ -114,6 +118,16 @@ describe('CommunityPageSubCommunityListComponent Component', () => {
} }
}; };
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
themeService = getMockThemeService(); themeService = getMockThemeService();
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
@@ -129,6 +143,7 @@ describe('CommunityPageSubCommunityListComponent Component', () => {
providers: [ providers: [
{ provide: CommunityDataService, useValue: communityDataServiceStub }, { provide: CommunityDataService, useValue: communityDataServiceStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService },
{ provide: SelectableListService, useValue: {} }, { provide: SelectableListService, useValue: {} },
{ provide: ThemeService, useValue: themeService }, { provide: ThemeService, useValue: themeService },
], ],
@@ -163,28 +178,4 @@ describe('CommunityPageSubCommunityListComponent Component', () => {
const subComHead = fixture.debugElement.queryAll(By.css('h2')); const subComHead = fixture.debugElement.queryAll(By.css('h2'));
expect(subComHead.length).toEqual(0); expect(subComHead.length).toEqual(0);
}); });
it('should update list of sub-communities on pagination change', () => {
subCommList = subcommunities;
fixture.detectChanges();
const pagination = Object.create({
pagination:{
id: comp.pageId,
currentPage: 2,
pageSize: 5
},
sort: {
field: 'dc.title',
direction: 'ASC'
}
});
comp.onPaginationChange(pagination);
fixture.detectChanges();
const collList = fixture.debugElement.queryAll(By.css('li'));
expect(collList.length).toEqual(2);
expect(collList[0].nativeElement.textContent).toContain('SubCommunity 6');
expect(collList[1].nativeElement.textContent).toContain('SubCommunity 7');
});
}); });

View File

@@ -18,6 +18,10 @@ import { HostWindowService } from '../../shared/host-window.service';
import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub'; import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub';
import { CommunityDataService } from '../../core/data/community-data.service'; import { CommunityDataService } from '../../core/data/community-data.service';
import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service'; import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service';
import { of as observableOf } from 'rxjs';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { PaginationService } from '../../core/pagination/pagination.service';
import { getMockThemeService } from '../../shared/mocks/theme-service.mock'; import { getMockThemeService } from '../../shared/mocks/theme-service.mock';
import { ThemeService } from '../../shared/theme-support/theme.service'; import { ThemeService } from '../../shared/theme-support/theme.service';
@@ -25,6 +29,7 @@ describe('TopLevelCommunityList Component', () => {
let comp: TopLevelCommunityListComponent; let comp: TopLevelCommunityListComponent;
let fixture: ComponentFixture<TopLevelCommunityListComponent>; let fixture: ComponentFixture<TopLevelCommunityListComponent>;
let communityDataServiceStub: any; let communityDataServiceStub: any;
let paginationService;
let themeService; let themeService;
const topCommList = [Object.assign(new Community(), { const topCommList = [Object.assign(new Community(), {
@@ -104,6 +109,15 @@ describe('TopLevelCommunityList Component', () => {
} }
}; };
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getRouteParameterValue: observableOf('')
});
themeService = getMockThemeService(); themeService = getMockThemeService();
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
@@ -119,6 +133,7 @@ describe('TopLevelCommunityList Component', () => {
providers: [ providers: [
{ provide: CommunityDataService, useValue: communityDataServiceStub }, { provide: CommunityDataService, useValue: communityDataServiceStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService },
{ provide: SelectableListService, useValue: {} }, { provide: SelectableListService, useValue: {} },
{ provide: ThemeService, useValue: themeService }, { provide: ThemeService, useValue: themeService },
], ],
@@ -143,25 +158,4 @@ describe('TopLevelCommunityList Component', () => {
expect(subComList[3].nativeElement.textContent).toContain('TopCommunity 4'); expect(subComList[3].nativeElement.textContent).toContain('TopCommunity 4');
expect(subComList[4].nativeElement.textContent).toContain('TopCommunity 5'); expect(subComList[4].nativeElement.textContent).toContain('TopCommunity 5');
}); });
it('should update list of top-communities on pagination change', () => {
const pagination = Object.create({
pagination: {
id: comp.pageId,
currentPage: 2,
pageSize: 5
},
sort: {
field: 'dc.title',
direction: 'ASC'
}
});
comp.onPaginationChange(pagination);
fixture.detectChanges();
const collList = fixture.debugElement.queryAll(By.css('li'));
expect(collList.length).toEqual(2);
expect(collList[0].nativeElement.textContent).toContain('TopCommunity 6');
expect(collList[1].nativeElement.textContent).toContain('TopCommunity 7');
});
}); });

View File

@@ -16,6 +16,10 @@ import { ResponsiveColumnSizes } from '../../../../../shared/responsive-table-si
import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote-data.utils';
import { createPaginatedList } from '../../../../../shared/testing/utils.test'; import { createPaginatedList } from '../../../../../shared/testing/utils.test';
import { RequestService } from '../../../../../core/data/request.service'; import { RequestService } from '../../../../../core/data/request.service';
import { PaginationService } from '../../../../../core/pagination/pagination.service';
import { PaginationComponentOptions } from '../../../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../../core/data/request.models';
describe('PaginatedDragAndDropBitstreamListComponent', () => { describe('PaginatedDragAndDropBitstreamListComponent', () => {
let comp: PaginatedDragAndDropBitstreamListComponent; let comp: PaginatedDragAndDropBitstreamListComponent;
@@ -24,6 +28,7 @@ describe('PaginatedDragAndDropBitstreamListComponent', () => {
let bundleService: BundleDataService; let bundleService: BundleDataService;
let objectValuesPipe: ObjectValuesPipe; let objectValuesPipe: ObjectValuesPipe;
let requestService: RequestService; let requestService: RequestService;
let paginationService: PaginationService;
const columnSizes = new ResponsiveTableSizes([ const columnSizes = new ResponsiveTableSizes([
new ResponsiveColumnSizes(2, 2, 3, 4, 4), new ResponsiveColumnSizes(2, 2, 3, 4, 4),
@@ -109,6 +114,16 @@ describe('PaginatedDragAndDropBitstreamListComponent', () => {
hasByHref$: observableOf(true) hasByHref$: observableOf(true)
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()], imports: [TranslateModule.forRoot()],
declarations: [PaginatedDragAndDropBitstreamListComponent, VarDirective], declarations: [PaginatedDragAndDropBitstreamListComponent, VarDirective],
@@ -116,7 +131,8 @@ describe('PaginatedDragAndDropBitstreamListComponent', () => {
{ provide: ObjectUpdatesService, useValue: objectUpdatesService }, { provide: ObjectUpdatesService, useValue: objectUpdatesService },
{ provide: BundleDataService, useValue: bundleService }, { provide: BundleDataService, useValue: bundleService },
{ provide: ObjectValuesPipe, useValue: objectValuesPipe }, { provide: ObjectValuesPipe, useValue: objectValuesPipe },
{ provide: RequestService, useValue: requestService } { provide: RequestService, useValue: requestService },
{ provide: PaginationService, useValue: paginationService }
], schemas: [ ], schemas: [
NO_ERRORS_SCHEMA NO_ERRORS_SCHEMA
] ]

View File

@@ -16,6 +16,10 @@ import { MockBitstreamFormat1 } from '../../../../shared/mocks/item.mock';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { NotificationsService } from '../../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../../shared/testing/notifications-service.stub';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../core/data/request.models';
import { PaginationService } from '../../../../core/pagination/pagination.service';
describe('FullFileSectionComponent', () => { describe('FullFileSectionComponent', () => {
let comp: FullFileSectionComponent; let comp: FullFileSectionComponent;
@@ -52,6 +56,16 @@ describe('FullFileSectionComponent', () => {
findAllByItemAndBundleName: createSuccessfulRemoteDataObject$(createPaginatedList([mockBitstream, mockBitstream, mockBitstream])) findAllByItemAndBundleName: createSuccessfulRemoteDataObject$(createPaginatedList([mockBitstream, mockBitstream, mockBitstream]))
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
@@ -64,7 +78,8 @@ describe('FullFileSectionComponent', () => {
declarations: [FullFileSectionComponent, VarDirective, FileSizePipe, MetadataFieldWrapperComponent], declarations: [FullFileSectionComponent, VarDirective, FileSizePipe, MetadataFieldWrapperComponent],
providers: [ providers: [
{ provide: BitstreamDataService, useValue: bitstreamDataService }, { provide: BitstreamDataService, useValue: bitstreamDataService },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() } { provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: PaginationService, useValue: paginationService }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
@@ -82,39 +97,5 @@ describe('FullFileSectionComponent', () => {
const fileSection = fixture.debugElement.queryAll(By.css('.file-section')); const fileSection = fixture.debugElement.queryAll(By.css('.file-section'));
expect(fileSection.length).toEqual(6); expect(fileSection.length).toEqual(6);
}); });
describe('when we press the pageChange button for original bundle', () => {
beforeEach(() => {
comp.switchOriginalPage(2);
fixture.detectChanges();
});
it('should give the value to the currentpage', () => {
expect(comp.originalOptions.currentPage).toBe(2);
});
it('should call the next function on the originalCurrentPage', (done) => {
comp.originalCurrentPage$.subscribe((event) => {
expect(event).toEqual(2);
done();
});
});
});
describe('when we press the pageChange button for license bundle', () => {
beforeEach(() => {
comp.switchLicensePage(2);
fixture.detectChanges();
});
it('should give the value to the currentpage', () => {
expect(comp.licenseOptions.currentPage).toBe(2);
});
it('should call the next function on the licenseCurrentPage', (done) => {
comp.licenseCurrentPage$.subscribe((event) => {
expect(event).toEqual(2);
done();
});
});
});
}); });
}); });

View File

@@ -34,12 +34,18 @@ describe('MyDSpaceConfigurationService', () => {
getRouteDataValue: observableOf({}) getRouteDataValue: observableOf({})
}); });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(defaults.pagination),
getCurrentSort: observableOf(defaults.sort),
getRouteParameterValue: observableOf('')
});
const activatedRoute: any = new ActivatedRouteStub(); const activatedRoute: any = new ActivatedRouteStub();
const roleService: any = new RoleServiceMock(); const roleService: any = new RoleServiceMock();
beforeEach(() => { beforeEach(() => {
service = new MyDSpaceConfigurationService(roleService, spy, activatedRoute); service = new MyDSpaceConfigurationService(roleService, spy, paginationService, activatedRoute);
}); });
describe('when the scope is called', () => { describe('when the scope is called', () => {
@@ -102,25 +108,19 @@ describe('MyDSpaceConfigurationService', () => {
describe('when getCurrentSort is called', () => { describe('when getCurrentSort is called', () => {
beforeEach(() => { beforeEach(() => {
// service.getCurrentSort({} as any); service.getCurrentSort('page-id', defaults.sort);
}); });
it('should call getQueryParameterValue on the routeService with parameter name \'sortDirection\'', () => { it('should call getCurrentSort on the paginationService with the provided id and sort options', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('sortDirection'); expect((service as any).paginationService.getCurrentSort).toHaveBeenCalledWith('page-id', defaults.sort);
});
it('should call getQueryParameterValue on the routeService with parameter name \'sortField\'', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('sortField');
}); });
}); });
describe('when getCurrentPagination is called', () => { describe('when getCurrentPagination is called', () => {
beforeEach(() => { beforeEach(() => {
// service.getCurrentPagination({ currentPage: 1, pageSize: 10 } as any); service.getCurrentPagination('page-id', defaults.pagination);
}); });
it('should call getQueryParameterValue on the routeService with parameter name \'page\'', () => { it('should call getCurrentPagination on the paginationService with the provided id and sort options', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('page'); expect((service as any).paginationService.getCurrentPagination).toHaveBeenCalledWith('page-id', defaults.pagination);
});
it('should call getQueryParameterValue on the routeService with parameter name \'pageSize\'', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('pageSize');
}); });
}); });
@@ -152,7 +152,7 @@ describe('MyDSpaceConfigurationService', () => {
describe('when subscribeToPaginatedSearchOptions is called', () => { describe('when subscribeToPaginatedSearchOptions is called', () => {
beforeEach(() => { beforeEach(() => {
(service as any).subscribeToPaginatedSearchOptions(defaults); (service as any).subscribeToPaginatedSearchOptions('id', defaults);
}); });
it('should call all getters it needs', () => { it('should call all getters it needs', () => {
expect(service.getCurrentPagination).toHaveBeenCalled(); expect(service.getCurrentPagination).toHaveBeenCalled();

View File

@@ -56,6 +56,7 @@ export class MyDSpaceConfigurationService extends SearchConfigurationService {
* *
* @param {roleService} roleService * @param {roleService} roleService
* @param {RouteService} routeService * @param {RouteService} routeService
* @param {PaginationService} paginationService
* @param {ActivatedRoute} route * @param {ActivatedRoute} route
*/ */
constructor(protected roleService: RoleService, constructor(protected roleService: RoleService,

View File

@@ -0,0 +1,149 @@
import { PaginationService } from './pagination.service';
import { RouterStub } from '../../shared/testing/router.stub';
import { of as observableOf } from 'rxjs';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../cache/models/sort-options.model';
import { FindListOptions } from '../data/request.models';
describe('PaginationService', () => {
let service: PaginationService;
let router;
let routeService;
const defaultPagination = new PaginationComponentOptions();
const defaultSort = new SortOptions('id', SortDirection.DESC);
const defaultFindListOptions = new FindListOptions();
beforeEach(() => {
router = new RouterStub();
routeService = {
getQueryParameterValue: (param) => {
let value;
if (param.startsWith('p.')) {
value = 5;
}
if (param.startsWith('rpp.')) {
value = 10;
}
if (param.startsWith('sd.')) {
value = 'ASC';
}
if (param.startsWith('sf.')) {
value = 'score';
}
return observableOf(value);
}
};
service = new PaginationService(routeService, router);
});
describe('getCurrentPagination', () => {
it('should retrieve the current pagination info from the routerService', () => {
service.getCurrentPagination('test-id', defaultPagination).subscribe((currentPagination) => {
expect(currentPagination).toEqual(Object.assign(new PaginationComponentOptions(), {
currentPage: 5,
pageSize: 10
}));
});
});
});
describe('getCurrentSort', () => {
it('should retrieve the current sort info from the routerService', () => {
service.getCurrentSort('test-id', defaultSort).subscribe((currentSort) => {
expect(currentSort).toEqual(Object.assign(new SortOptions('score', SortDirection.ASC )));
});
});
});
describe('getFindListOptions', () => {
it('should retrieve the current findListOptions info from the routerService', () => {
service.getFindListOptions('test-id', defaultFindListOptions).subscribe((findListOptions) => {
expect(findListOptions).toEqual(Object.assign(new FindListOptions(),
{
sort: new SortOptions('score', SortDirection.ASC ),
currentPage: 5,
elementsPerPage: 10
}));
});
});
});
describe('resetPage', () => {
it('should call the updateRoute method with the id and page 1', () => {
spyOn(service, 'updateRoute');
service.resetPage('test');
expect(service.updateRoute).toHaveBeenCalledWith('test', {page: 1});
});
});
describe('updateRoute', () => {
it('should update the route with the provided page params', () => {
service.updateRoute('test', {page: 2, pageSize: 5, sortField: 'title', sortDirection: SortDirection.DESC});
const navigateParams = {};
navigateParams[`p.test`] = `2`;
navigateParams[`rpp.test`] = `5`;
navigateParams[`sf.test`] = `title`;
navigateParams[`sd.test`] = `DESC`;
expect(router.navigate).toHaveBeenCalledWith([], {queryParams: navigateParams, queryParamsHandling: 'merge'});
});
it('should update the route with the provided page params while keeping the existing non provided ones', () => {
service.updateRoute('test', {page: 2});
const navigateParams = {};
navigateParams[`p.test`] = `2`;
navigateParams[`rpp.test`] = `10`;
navigateParams[`sf.test`] = `score`;
navigateParams[`sd.test`] = `ASC`;
expect(router.navigate).toHaveBeenCalledWith([], {queryParams: navigateParams, queryParamsHandling: 'merge'});
});
});
describe('updateRouteWithUrl', () => {
it('should update the route with the provided page params and url', () => {
service.updateRouteWithUrl('test', ['someUrl'], {page: 2, pageSize: 5, sortField: 'title', sortDirection: SortDirection.DESC});
const navigateParams = {};
navigateParams[`p.test`] = `2`;
navigateParams[`rpp.test`] = `5`;
navigateParams[`sf.test`] = `title`;
navigateParams[`sd.test`] = `DESC`;
expect(router.navigate).toHaveBeenCalledWith(['someUrl'], {queryParams: navigateParams, queryParamsHandling: 'merge'});
});
it('should update the route with the provided page params and url while keeping the existing non provided ones', () => {
service.updateRouteWithUrl('test',['someUrl'], {page: 2});
const navigateParams = {};
navigateParams[`p.test`] = `2`;
navigateParams[`rpp.test`] = `10`;
navigateParams[`sf.test`] = `score`;
navigateParams[`sd.test`] = `ASC`;
expect(router.navigate).toHaveBeenCalledWith(['someUrl'], {queryParams: navigateParams, queryParamsHandling: 'merge'});
});
});
describe('clearPagination', () => {
it('should clear the pagination info from the route for the current id', () => {
service.clearPagination('test');
const params = {};
params[`p.test`] = null;
params[`rpp.test`] = null;
params[`sf.test`] = null;
params[`sd.test`] = null;
expect(router.navigate).toHaveBeenCalledWith([], {queryParams: params, queryParamsHandling: 'merge'});
});
});
describe('getPageParam', () => {
it('should return the name of the page param', () => {
const pageParam = service.getPageParam('test');
expect(pageParam).toEqual('p.test');
});
});
});

View File

@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { Router } from '@angular/router';
import { RouteService } from '../services/route.service'; import { RouteService } from '../services/route.service';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { combineLatest as observableCombineLatest, Observable } from 'rxjs';
@@ -9,7 +9,6 @@ import { FindListOptions } from '../data/request.models';
import { hasValue, isEmpty, isNotEmpty } from '../../shared/empty.util'; import { hasValue, isEmpty, isNotEmpty } from '../../shared/empty.util';
import { difference } from '../../shared/object.util'; import { difference } from '../../shared/object.util';
import { isNumeric } from 'rxjs/internal-compatibility'; import { isNumeric } from 'rxjs/internal-compatibility';
import { Location } from '@angular/common';
@Injectable({ @Injectable({
@@ -20,9 +19,7 @@ export class PaginationService {
private defaultSortOptions = new SortOptions('id', SortDirection.ASC); private defaultSortOptions = new SortOptions('id', SortDirection.ASC);
constructor(protected routeService: RouteService, constructor(protected routeService: RouteService,
protected route: ActivatedRoute, protected router: Router
protected router: Router,
protected location: Location
) { ) {
} }
@@ -33,6 +30,7 @@ export class PaginationService {
const page$ = this.routeService.getQueryParameterValue(`p.${paginationId}`); const page$ = this.routeService.getQueryParameterValue(`p.${paginationId}`);
const size$ = this.routeService.getQueryParameterValue(`rpp.${paginationId}`); const size$ = this.routeService.getQueryParameterValue(`rpp.${paginationId}`);
return observableCombineLatest([page$, size$]).pipe(map(([page, size]) => { return observableCombineLatest([page$, size$]).pipe(map(([page, size]) => {
console.log(page, size);
return Object.assign(new PaginationComponentOptions(), defaultPagination, { return Object.assign(new PaginationComponentOptions(), defaultPagination, {
currentPage: this.convertToNumeric(page, defaultPagination.currentPage), currentPage: this.convertToNumeric(page, defaultPagination.currentPage),
pageSize: this.getBestMatchPageSize(size, defaultPagination) pageSize: this.getBestMatchPageSize(size, defaultPagination)
@@ -80,7 +78,7 @@ export class PaginationService {
this.updateRoute(paginationId, {page: 1}); this.updateRoute(paginationId, {page: 1});
} }
getCurrentRouting(paginationId: string) { private getCurrentRouting(paginationId: string) {
return this.getFindListOptions(paginationId, {}, true).pipe( return this.getFindListOptions(paginationId, {}, true).pipe(
take(1), take(1),
map((findListoptions: FindListOptions) => { map((findListoptions: FindListOptions) => {
@@ -88,7 +86,7 @@ export class PaginationService {
page: findListoptions.currentPage, page: findListoptions.currentPage,
pageSize: findListoptions.elementsPerPage, pageSize: findListoptions.elementsPerPage,
sortField: findListoptions.sort.field, sortField: findListoptions.sort.field,
sortDir: findListoptions.sort.direction, sortDirection: findListoptions.sort.direction,
}; };
}) })
); );
@@ -101,12 +99,12 @@ export class PaginationService {
sortDirection?: SortDirection sortDirection?: SortDirection
}, extraParams?, retainScrollPosition?: boolean) { }, extraParams?, retainScrollPosition?: boolean) {
this.getCurrentRouting(paginationId).subscribe((currentFindListOptions) => { this.getCurrentRouting(paginationId).subscribe((currentFindListOptions) => {
console.log('currentFindListOptions',currentFindListOptions );
const currentParametersWithIdName = this.getParametersWithIdName(paginationId, currentFindListOptions); const currentParametersWithIdName = this.getParametersWithIdName(paginationId, currentFindListOptions);
const parametersWithIdName = this.getParametersWithIdName(paginationId, params); const parametersWithIdName = this.getParametersWithIdName(paginationId, params);
if (isNotEmpty(difference(parametersWithIdName, currentParametersWithIdName)) || isNotEmpty(extraParams)) { if (isNotEmpty(difference(parametersWithIdName, currentParametersWithIdName)) || isNotEmpty(extraParams)) {
const queryParams = Object.assign({}, currentParametersWithIdName, const queryParams = Object.assign({}, currentParametersWithIdName,
parametersWithIdName, extraParams); parametersWithIdName, extraParams);
console.log(retainScrollPosition);
if (retainScrollPosition) { if (retainScrollPosition) {
this.router.navigate([], { this.router.navigate([], {
queryParams: queryParams, queryParams: queryParams,
@@ -169,7 +167,7 @@ export class PaginationService {
return `p.${paginationId}`; return `p.${paginationId}`;
} }
getParametersWithIdName(paginationId: string, params: { private getParametersWithIdName(paginationId: string, params: {
page?: number page?: number
pageSize?: number pageSize?: number
sortField?: string sortField?: string

View File

@@ -15,7 +15,7 @@ describe('SearchConfigurationService', () => {
'f.date.max': ['2018'] 'f.date.max': ['2018']
}; };
const defaults = new PaginatedSearchOptions({ const defaults = new PaginatedSearchOptions({
pagination: Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 }), pagination: Object.assign(new PaginationComponentOptions(), { id: 'page-id', currentPage: 1, pageSize: 20 }),
sort: new SortOptions('score', SortDirection.DESC), sort: new SortOptions('score', SortDirection.DESC),
configuration: 'default', configuration: 'default',
query: '', query: '',
@@ -30,10 +30,17 @@ describe('SearchConfigurationService', () => {
getRouteParameterValue: observableOf('') getRouteParameterValue: observableOf('')
}); });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(defaults.pagination),
getCurrentSort: observableOf(defaults.sort),
getRouteParameterValue: observableOf('')
});
const activatedRoute: any = new ActivatedRouteStub(); const activatedRoute: any = new ActivatedRouteStub();
beforeEach(() => { beforeEach(() => {
service = new SearchConfigurationService(routeService, activatedRoute); service = new SearchConfigurationService(routeService, paginationService, activatedRoute);
}); });
describe('when the scope is called', () => { describe('when the scope is called', () => {
beforeEach(() => { beforeEach(() => {
@@ -95,25 +102,19 @@ describe('SearchConfigurationService', () => {
describe('when getCurrentSort is called', () => { describe('when getCurrentSort is called', () => {
beforeEach(() => { beforeEach(() => {
service.getCurrentSort({} as any); service.getCurrentSort(defaults.pagination.id, {} as any);
}); });
it('should call getQueryParameterValue on the routeService with parameter name \'sortDirection\'', () => { it('should call getCurrentSort on the paginationService with the provided id and sort options', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('sortDirection'); expect((service as any).paginationService.getCurrentSort).toHaveBeenCalledWith(defaults.pagination.id, {});
});
it('should call getQueryParameterValue on the routeService with parameter name \'sortField\'', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('sortField');
}); });
}); });
describe('when getCurrentPagination is called', () => { describe('when getCurrentPagination is called', () => {
beforeEach(() => { beforeEach(() => {
service.getCurrentPagination({ currentPage: 1, pageSize: 10 } as any); service.getCurrentPagination(defaults.pagination.id, defaults.pagination);
}); });
it('should call getQueryParameterValue on the routeService with parameter name \'page\'', () => { it('should call getCurrentPagination on the paginationService with the provided id and sort options', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('page'); expect((service as any).paginationService.getCurrentPagination).toHaveBeenCalledWith(defaults.pagination.id, defaults.pagination);
});
it('should call getQueryParameterValue on the routeService with parameter name \'pageSize\'', () => {
expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('pageSize');
}); });
}); });
@@ -145,7 +146,7 @@ describe('SearchConfigurationService', () => {
describe('when subscribeToPaginatedSearchOptions is called', () => { describe('when subscribeToPaginatedSearchOptions is called', () => {
beforeEach(() => { beforeEach(() => {
(service as any).subscribeToPaginatedSearchOptions(defaults); (service as any).subscribeToPaginatedSearchOptions(defaults.pagination.id, defaults);
}); });
it('should call all getters it needs', () => { it('should call all getters it needs', () => {
expect(service.getCurrentPagination).toHaveBeenCalled(); expect(service.getCurrentPagination).toHaveBeenCalled();

View File

@@ -22,6 +22,11 @@ import { routeServiceStub } from '../../../shared/testing/route-service.stub';
import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { SearchObjects } from '../../../shared/search/search-objects.model'; import { SearchObjects } from '../../../shared/search/search-objects.model';
import { PaginationService } from '../../pagination/pagination.service';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../cache/models/sort-options.model';
import { FindListOptions } from '../../data/request.models';
import { SearchConfigurationService } from './search-configuration.service';
@Component({ template: '' }) @Component({ template: '' })
class DummyComponent { class DummyComponent {
@@ -32,6 +37,7 @@ describe('SearchService', () => {
let searchService: SearchService; let searchService: SearchService;
const router = new RouterStub(); const router = new RouterStub();
const route = new ActivatedRouteStub(); const route = new ActivatedRouteStub();
const searchConfigService = {paginationID: 'page-id'};
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
@@ -51,6 +57,8 @@ describe('SearchService', () => {
{ provide: HALEndpointService, useValue: {} }, { provide: HALEndpointService, useValue: {} },
{ provide: CommunityDataService, useValue: {} }, { provide: CommunityDataService, useValue: {} },
{ provide: DSpaceObjectDataService, useValue: {} }, { provide: DSpaceObjectDataService, useValue: {} },
{ provide: PaginationService, useValue: {} },
{ provide: SearchConfigurationService, useValue: searchConfigService },
SearchService SearchService
], ],
}); });
@@ -94,6 +102,18 @@ describe('SearchService', () => {
} }
}; };
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {}
});
const searchConfigService = {paginationID: 'page-id'};
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
@@ -113,6 +133,8 @@ describe('SearchService', () => {
{ provide: HALEndpointService, useValue: halService }, { provide: HALEndpointService, useValue: halService },
{ provide: CommunityDataService, useValue: {} }, { provide: CommunityDataService, useValue: {} },
{ provide: DSpaceObjectDataService, useValue: {} }, { provide: DSpaceObjectDataService, useValue: {} },
{ provide: PaginationService, useValue: paginationService },
{ provide: SearchConfigurationService, useValue: searchConfigService },
SearchService SearchService
], ],
}); });
@@ -124,18 +146,14 @@ describe('SearchService', () => {
it('should call the navigate method on the Router with view mode list parameter as a parameter when setViewMode is called', () => { it('should call the navigate method on the Router with view mode list parameter as a parameter when setViewMode is called', () => {
searchService.setViewMode(ViewMode.ListElement); searchService.setViewMode(ViewMode.ListElement);
expect(router.navigate).toHaveBeenCalledWith(['/search'], { expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('page-id', ['/search'], {page: 1}, { view: ViewMode.ListElement }
queryParams: { view: ViewMode.ListElement, page: 1 }, );
queryParamsHandling: 'merge'
});
}); });
it('should call the navigate method on the Router with view mode grid parameter as a parameter when setViewMode is called', () => { it('should call the navigate method on the Router with view mode grid parameter as a parameter when setViewMode is called', () => {
searchService.setViewMode(ViewMode.GridElement); searchService.setViewMode(ViewMode.GridElement);
expect(router.navigate).toHaveBeenCalledWith(['/search'], { expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('page-id', ['/search'], {page: 1}, { view: ViewMode.GridElement }
queryParams: { view: ViewMode.GridElement, page: 1 }, );
queryParamsHandling: 'merge'
});
}); });
it('should return ViewMode.List when the viewMode is set to ViewMode.List in the ActivatedRoute', () => { it('should return ViewMode.List when the viewMode is set to ViewMode.List in the ActivatedRoute', () => {

View File

@@ -12,6 +12,11 @@ import { By } from '@angular/platform-browser';
import { ProcessStatus } from '../processes/process-status.model'; import { ProcessStatus } from '../processes/process-status.model';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { createPaginatedList } from '../../shared/testing/utils.test'; import { createPaginatedList } from '../../shared/testing/utils.test';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../../core/pagination/pagination.service';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../core/data/request.models';
describe('ProcessOverviewComponent', () => { describe('ProcessOverviewComponent', () => {
let component: ProcessOverviewComponent; let component: ProcessOverviewComponent;
@@ -19,10 +24,15 @@ describe('ProcessOverviewComponent', () => {
let processService: ProcessDataService; let processService: ProcessDataService;
let ePersonService: EPersonDataService; let ePersonService: EPersonDataService;
let paginationService: PaginationService;
let processes: Process[]; let processes: Process[];
let ePerson: EPerson; let ePerson: EPerson;
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
function init() { function init() {
processes = [ processes = [
Object.assign(new Process(), { Object.assign(new Process(), {
@@ -69,6 +79,12 @@ describe('ProcessOverviewComponent', () => {
ePersonService = jasmine.createSpyObj('ePersonService', { ePersonService = jasmine.createSpyObj('ePersonService', {
findById: createSuccessfulRemoteDataObject$(ePerson) findById: createSuccessfulRemoteDataObject$(ePerson)
}); });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
});
} }
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
@@ -78,7 +94,8 @@ describe('ProcessOverviewComponent', () => {
imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([])], imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([])],
providers: [ providers: [
{ provide: ProcessDataService, useValue: processService }, { provide: ProcessDataService, useValue: processService },
{ provide: EPersonDataService, useValue: ePersonService } { provide: EPersonDataService, useValue: ePersonService },
{ provide: PaginationService, useValue: paginationService }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();
@@ -143,16 +160,4 @@ describe('ProcessOverviewComponent', () => {
}); });
}); });
}); });
describe('onPageChange', () => {
const toPage = 2;
beforeEach(() => {
component.onPageChange(toPage);
});
it('should call a new findAll with the corresponding page', () => {
expect(processService.findAll).toHaveBeenCalledWith(jasmine.objectContaining({ currentPage: toPage }));
});
});
}); });

View File

@@ -8,6 +8,11 @@ import { SearchService } from '../core/shared/search/search.service';
import { TranslateLoaderMock } from '../shared/mocks/translate-loader.mock'; import { TranslateLoaderMock } from '../shared/mocks/translate-loader.mock';
import { SearchNavbarComponent } from './search-navbar.component'; import { SearchNavbarComponent } from './search-navbar.component';
import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../core/cache/models/sort-options.model';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../core/pagination/pagination.service';
import { SearchConfigurationService } from '../core/shared/search/search-configuration.service';
describe('SearchNavbarComponent', () => { describe('SearchNavbarComponent', () => {
let component: SearchNavbarComponent; let component: SearchNavbarComponent;
@@ -15,6 +20,7 @@ describe('SearchNavbarComponent', () => {
let mockSearchService: any; let mockSearchService: any;
let router: Router; let router: Router;
let routerStub; let routerStub;
let paginationService;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
mockSearchService = { mockSearchService = {
@@ -26,6 +32,18 @@ describe('SearchNavbarComponent', () => {
routerStub = { routerStub = {
navigate: (commands) => commands navigate: (commands) => commands
}; };
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getRouteParameterValue: observableOf(''),
updateRouteWithUrl: {},
clearPagination : {}
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
FormsModule, FormsModule,
@@ -40,7 +58,9 @@ describe('SearchNavbarComponent', () => {
declarations: [SearchNavbarComponent], declarations: [SearchNavbarComponent],
providers: [ providers: [
{ provide: SearchService, useValue: mockSearchService }, { provide: SearchService, useValue: mockSearchService },
{ provide: Router, useValue: routerStub } { provide: PaginationService, useValue: paginationService },
{ provide: Router, useValue: routerStub },
{ provide: SearchConfigurationService, useValue: {paginationID: 'page-id'} }
] ]
}) })
.compileComponents(); .compileComponents();
@@ -88,7 +108,7 @@ describe('SearchNavbarComponent', () => {
})); }));
it('to search page with empty query', () => { it('to search page with empty query', () => {
expect(component.onSubmit).toHaveBeenCalledWith({ query: '' }); expect(component.onSubmit).toHaveBeenCalledWith({ query: '' });
expect(router.navigate).toHaveBeenCalled(); expect(paginationService.updateRouteWithUrl).toHaveBeenCalled();
}); });
}); });
}); });
@@ -112,7 +132,7 @@ describe('SearchNavbarComponent', () => {
})); }));
it('to search page with query', async () => { it('to search page with query', async () => {
expect(component.onSubmit).toHaveBeenCalledWith({ query: 'test' }); expect(component.onSubmit).toHaveBeenCalledWith({ query: 'test' });
expect(router.navigate).toHaveBeenCalled(); expect(paginationService.updateRouteWithUrl).toHaveBeenCalled();
}); });
}); });
}); });

View File

@@ -18,6 +18,8 @@ import { PaginationComponentOptions } from '../pagination/pagination-component-o
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { createSuccessfulRemoteDataObject$ } from '../remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../remote-data.utils';
import { storeModuleConfig } from '../../app.reducer'; import { storeModuleConfig } from '../../app.reducer';
import { FindListOptions } from '../../core/data/request.models';
import { PaginationService } from '../../core/pagination/pagination.service';
describe('BrowseByComponent', () => { describe('BrowseByComponent', () => {
let comp: BrowseByComponent; let comp: BrowseByComponent;
@@ -45,6 +47,22 @@ describe('BrowseByComponent', () => {
]; ];
const mockItemsRD$ = createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), mockItems)); const mockItemsRD$ = createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), mockItems));
const paginationConfig = Object.assign(new PaginationComponentOptions(), {
id: 'test-pagination',
currentPage: 1,
pageSizeOptions: [5, 10, 15, 20],
pageSize: 15
});
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(paginationConfig),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
updateRoute: {},
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
@@ -63,7 +81,9 @@ describe('BrowseByComponent', () => {
BrowserAnimationsModule BrowserAnimationsModule
], ],
declarations: [], declarations: [],
providers: [], providers: [
{provide: PaginationService, useValue: paginationService}
],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();
})); }));
@@ -95,12 +115,8 @@ describe('BrowseByComponent', () => {
beforeEach(() => { beforeEach(() => {
comp.enableArrows = true; comp.enableArrows = true;
comp.objects$ = mockItemsRD$; comp.objects$ = mockItemsRD$;
comp.paginationConfig = Object.assign(new PaginationComponentOptions(), {
id: 'test-pagination', comp.paginationConfig = paginationConfig;
currentPage: 1,
pageSizeOptions: [5, 10, 15, 20],
pageSize: 15
});
comp.sortConfig = Object.assign(new SortOptions('dc.title', SortDirection.ASC)); comp.sortConfig = Object.assign(new SortOptions('dc.title', SortDirection.ASC));
fixture.detectChanges(); fixture.detectChanges();
}); });
@@ -136,8 +152,8 @@ describe('BrowseByComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should emit a signal to the EventEmitter', () => { it('should call the updateRoute method from the paginationService', () => {
expect(comp.pageSizeChange.emit).toHaveBeenCalled(); expect(paginationService.updateRoute).toHaveBeenCalledWith('test-pagination', {pageSize: paginationConfig.pageSizeOptions[0]});
}); });
}); });
@@ -148,8 +164,8 @@ describe('BrowseByComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should emit a signal to the EventEmitter', () => { it('should call the updateRoute method from the paginationService', () => {
expect(comp.sortDirectionChange.emit).toHaveBeenCalled(); expect(paginationService.updateRoute).toHaveBeenCalledWith('test-pagination', {sortDirection: 'ASC'});
}); });
}); });
}); });

View File

@@ -144,7 +144,7 @@ export class BrowseByComponent implements OnInit {
this.objectInjector = Injector.create({ this.objectInjector = Injector.create({
providers: [ providers: [
{ provide: 'startsWithOptions', useFactory: () => (this.startsWithOptions), deps:[] }, { provide: 'startsWithOptions', useFactory: () => (this.startsWithOptions), deps:[] },
{ provide: 'paginationId', useFactory: () => (this.paginationConfig.id), deps:[] } { provide: 'paginationId', useFactory: () => (this.paginationConfig?.id), deps:[] }
], ],
parent: this.injector parent: this.injector
}); });

View File

@@ -11,11 +11,18 @@ import { VersionHistoryDataService } from '../../../core/data/version-history-da
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { createSuccessfulRemoteDataObject$ } from '../../remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../remote-data.utils';
import { createPaginatedList } from '../../testing/utils.test'; import { createPaginatedList } from '../../testing/utils.test';
import { PaginationComponentOptions } from '../../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('ItemVersionsComponent', () => { describe('ItemVersionsComponent', () => {
let component: ItemVersionsComponent; let component: ItemVersionsComponent;
let fixture: ComponentFixture<ItemVersionsComponent>; let fixture: ComponentFixture<ItemVersionsComponent>;
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const versionHistory = Object.assign(new VersionHistory(), { const versionHistory = Object.assign(new VersionHistory(), {
id: '1' id: '1'
}); });
@@ -52,12 +59,19 @@ describe('ItemVersionsComponent', () => {
getVersions: createSuccessfulRemoteDataObject$(createPaginatedList(versions)) getVersions: createSuccessfulRemoteDataObject$(createPaginatedList(versions))
}); });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getRouteParameterValue: observableOf('')
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [ItemVersionsComponent, VarDirective], declarations: [ItemVersionsComponent, VarDirective],
imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([])], imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([])],
providers: [ providers: [
{ provide: VersionHistoryDataService, useValue: versionHistoryService } { provide: VersionHistoryDataService, useValue: versionHistoryService },
{ provide: PaginationService, useValue: paginationService }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();
@@ -107,16 +121,4 @@ describe('ItemVersionsComponent', () => {
expect(summary.nativeElement.textContent).toEqual(version.summary); expect(summary.nativeElement.textContent).toEqual(version.summary);
}); });
}); });
describe('switchPage', () => {
const page = 5;
beforeEach(() => {
component.switchPage(page);
});
it('should set the option\'s currentPage to the new page', () => {
expect(component.options.currentPage).toEqual(page);
});
});
}); });

View File

@@ -13,6 +13,10 @@ import { CollectionSelectComponent } from './collection-select.component';
import { Collection } from '../../../core/shared/collection.model'; import { Collection } from '../../../core/shared/collection.model';
import { createSuccessfulRemoteDataObject$ } from '../../remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../remote-data.utils';
import { createPaginatedList } from '../../testing/utils.test'; import { createPaginatedList } from '../../testing/utils.test';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('CollectionSelectComponent', () => { describe('CollectionSelectComponent', () => {
let comp: CollectionSelectComponent; let comp: CollectionSelectComponent;
@@ -36,13 +40,24 @@ describe('CollectionSelectComponent', () => {
currentPage: 1 currentPage: 1
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), SharedModule, RouterTestingModule.withRoutes([])], imports: [TranslateModule.forRoot(), SharedModule, RouterTestingModule.withRoutes([])],
declarations: [], declarations: [],
providers: [ providers: [
{ provide: ObjectSelectService, useValue: new ObjectSelectServiceStub([mockCollectionList[1].id]) }, { provide: ObjectSelectService, useValue: new ObjectSelectServiceStub([mockCollectionList[1].id]) },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) } { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();

View File

@@ -11,14 +11,18 @@ import { HostWindowService } from '../../host-window.service';
import { HostWindowServiceStub } from '../../testing/host-window-service.stub'; import { HostWindowServiceStub } from '../../testing/host-window-service.stub';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { of } from 'rxjs'; import { of as observableOf, of } from 'rxjs';
import { createSuccessfulRemoteDataObject$ } from '../../remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../remote-data.utils';
import { createPaginatedList } from '../../testing/utils.test'; import { createPaginatedList } from '../../testing/utils.test';
import { PaginationService } from '../../../core/pagination/pagination.service';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
describe('ItemSelectComponent', () => { describe('ItemSelectComponent', () => {
let comp: ItemSelectComponent; let comp: ItemSelectComponent;
let fixture: ComponentFixture<ItemSelectComponent>; let fixture: ComponentFixture<ItemSelectComponent>;
let objectSelectService: ObjectSelectService; let objectSelectService: ObjectSelectService;
let paginationService: PaginationService;
const mockItemList = [ const mockItemList = [
Object.assign(new Item(), { Object.assign(new Item(), {
@@ -59,13 +63,25 @@ describe('ItemSelectComponent', () => {
currentPage: 1 currentPage: 1
}); });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(mockPaginationOptions),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), SharedModule, RouterTestingModule.withRoutes([])], imports: [TranslateModule.forRoot(), SharedModule, RouterTestingModule.withRoutes([])],
declarations: [], declarations: [],
providers: [ providers: [
{ provide: ObjectSelectService, useValue: new ObjectSelectServiceStub([mockItemList[1].id]) }, { provide: ObjectSelectService, useValue: new ObjectSelectServiceStub([mockItemList[1].id]) },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) } { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();

View File

@@ -12,6 +12,7 @@ import { SortDirection, SortOptions } from '../../core/cache/models/sort-options
import { EnumKeysPipe } from '../utils/enum-keys-pipe'; import { EnumKeysPipe } from '../utils/enum-keys-pipe';
import { VarDirective } from '../utils/var.directive'; import { VarDirective } from '../utils/var.directive';
import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component';
import { PaginationService } from '../../core/pagination/pagination.service';
describe('PageSizeSelectorComponent', () => { describe('PageSizeSelectorComponent', () => {
@@ -33,6 +34,12 @@ describe('PageSizeSelectorComponent', () => {
sort sort
}; };
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getRouteParameterValue: observableOf('')
});
const activatedRouteStub = { const activatedRouteStub = {
queryParams: observableOf({ queryParams: observableOf({
query: queryParam, query: queryParam,
@@ -46,6 +53,7 @@ describe('PageSizeSelectorComponent', () => {
declarations: [PageSizeSelectorComponent, EnumKeysPipe, VarDirective], declarations: [PageSizeSelectorComponent, EnumKeysPipe, VarDirective],
providers: [ providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: PaginationService, useValue: paginationService },
{ {
provide: SEARCH_CONFIG_SERVICE, provide: SEARCH_CONFIG_SERVICE,
useValue: { useValue: {

View File

@@ -11,6 +11,9 @@ import { PaginationComponent } from '../pagination/pagination.component';
import { createSuccessfulRemoteDataObject } from '../remote-data.utils'; import { createSuccessfulRemoteDataObject } from '../remote-data.utils';
import { createPaginatedList } from '../testing/utils.test'; import { createPaginatedList } from '../testing/utils.test';
import { ObjectValuesPipe } from '../utils/object-values-pipe'; import { ObjectValuesPipe } from '../utils/object-values-pipe';
import { PaginationService } from '../../core/pagination/pagination.service';
import { PaginationComponentOptions } from '../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
@Component({ @Component({
selector: 'ds-mock-paginated-drag-drop-abstract', selector: 'ds-mock-paginated-drag-drop-abstract',
@@ -22,8 +25,9 @@ class MockAbstractPaginatedDragAndDropListComponent extends AbstractPaginatedDra
protected elRef: ElementRef, protected elRef: ElementRef,
protected objectValuesPipe: ObjectValuesPipe, protected objectValuesPipe: ObjectValuesPipe,
protected mockUrl: string, protected mockUrl: string,
protected mockObjectsRD$: Observable<RemoteData<PaginatedList<DSpaceObject>>>) { protected paginationService: PaginationService,
super(objectUpdatesService, elRef, objectValuesPipe); protected mockObjectsRD$: Observable<RemoteData<PaginatedList<DSpaceObject>>>) {
super(objectUpdatesService, elRef, objectValuesPipe, paginationService);
} }
initializeObjectsRD(): void { initializeObjectsRD(): void {
@@ -43,10 +47,14 @@ describe('AbstractPaginatedDragAndDropListComponent', () => {
const url = 'mock-abstract-paginated-drag-and-drop-list-component'; const url = 'mock-abstract-paginated-drag-and-drop-list-component';
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const object1 = Object.assign(new DSpaceObject(), { uuid: 'object-1' }); const object1 = Object.assign(new DSpaceObject(), { uuid: 'object-1' });
const object2 = Object.assign(new DSpaceObject(), { uuid: 'object-2' }); const object2 = Object.assign(new DSpaceObject(), { uuid: 'object-2' });
const objectsRD = createSuccessfulRemoteDataObject(createPaginatedList([object1, object2])); const objectsRD = createSuccessfulRemoteDataObject(createPaginatedList([object1, object2]));
let objectsRD$: BehaviorSubject<RemoteData<PaginatedList<DSpaceObject>>>; let objectsRD$: BehaviorSubject<RemoteData<PaginatedList<DSpaceObject>>>;
let paginationService;
const updates = { const updates = {
[object1.uuid]: { field: object1, changeType: undefined }, [object1.uuid]: { field: object1, changeType: undefined },
@@ -69,8 +77,13 @@ describe('AbstractPaginatedDragAndDropListComponent', () => {
paginationComponent = jasmine.createSpyObj('paginationComponent', { paginationComponent = jasmine.createSpyObj('paginationComponent', {
doPageChange: {} doPageChange: {}
}); });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getRouteParameterValue: observableOf('')
});
objectsRD$ = new BehaviorSubject(objectsRD); objectsRD$ = new BehaviorSubject(objectsRD);
component = new MockAbstractPaginatedDragAndDropListComponent(objectUpdatesService, elRef, objectValuesPipe, url, objectsRD$); component = new MockAbstractPaginatedDragAndDropListComponent(objectUpdatesService, elRef, objectValuesPipe, url, paginationService, objectsRD$);
component.paginationComponent = paginationComponent; component.paginationComponent = paginationComponent;
component.ngOnInit(); component.ngOnInit();
}); });
@@ -86,18 +99,6 @@ describe('AbstractPaginatedDragAndDropListComponent', () => {
}); });
}); });
describe('switchPage', () => {
const page = 3;
beforeEach(() => {
component.switchPage(page);
});
it('should set currentPage$ to the new page', () => {
expect(component.currentPage$.value).toEqual(page);
});
});
describe('drop', () => { describe('drop', () => {
const event = { const event = {
previousIndex: 0, previousIndex: 0,

View File

@@ -31,10 +31,15 @@ import { SortDirection, SortOptions } from '../../core/cache/models/sort-options
import { createTestComponent } from '../testing/utils.test'; import { createTestComponent } from '../testing/utils.test';
import { storeModuleConfig } from '../../app.reducer'; import { storeModuleConfig } from '../../app.reducer';
import { PaginationService } from '../../core/pagination/pagination.service';
import { FindListOptions } from '../../core/data/request.models';
import { BehaviorSubject, of as observableOf } from 'rxjs';
function expectPages(fixture: ComponentFixture<any>, pagesDef: string[]): void { function expectPages(fixture: ComponentFixture<any>, pagesDef: string[]): void {
const de = fixture.debugElement.query(By.css('.pagination')); const de = fixture.debugElement.query(By.css('.pagination'));
const pages = de.nativeElement.querySelectorAll('li'); const pages = de.nativeElement.querySelectorAll('li');
console.log('pages', pages.length, pagesDef.length);
console.log(pages);
expect(pages.length).toEqual(pagesDef.length); expect(pages.length).toEqual(pagesDef.length);
@@ -105,14 +110,39 @@ describe('Pagination component', () => {
let activatedRouteStub: MockActivatedRoute; let activatedRouteStub: MockActivatedRoute;
let routerStub: RouterMock; let routerStub: RouterMock;
let paginationService: PaginationService;
// Define initial state and test state // Define initial state and test state
const _initialState = { width: 1600, height: 770 }; const _initialState = { width: 1600, height: 770 };
const pagination = new PaginationComponentOptions();
pagination.currentPage = 1;
pagination.pageSize = 10;
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 10 });
let currentPagination;
let currentSort;
let currentFindListOptions;
// waitForAsync beforeEach // waitForAsync beforeEach
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
activatedRouteStub = new MockActivatedRoute(); activatedRouteStub = new MockActivatedRoute();
routerStub = new RouterMock(); routerStub = new RouterMock(); hostWindowServiceStub = new HostWindowServiceMock(_initialState.width);
hostWindowServiceStub = new HostWindowServiceMock(_initialState.width);
currentPagination = new BehaviorSubject<PaginationComponentOptions>(pagination);
currentSort = new BehaviorSubject<SortOptions>(sort);
currentFindListOptions = new BehaviorSubject<FindListOptions>(findlistOptions);
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: currentPagination,
getCurrentSort: currentSort,
getFindListOptions: currentFindListOptions,
resetPage: {},
updateRoute: {},
updateRouteWithUrl: {}
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
@@ -138,6 +168,7 @@ describe('Pagination component', () => {
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: Router, useValue: routerStub }, { provide: Router, useValue: routerStub },
{ provide: HostWindowService, useValue: hostWindowServiceStub }, { provide: HostWindowService, useValue: hostWindowServiceStub },
{ provide: PaginationService, useValue: paginationService },
ChangeDetectorRef, ChangeDetectorRef,
PaginationComponent PaginationComponent
], ],
@@ -179,11 +210,17 @@ describe('Pagination component', () => {
it('should render and respond to page change', () => { it('should render and respond to page change', () => {
testComp.collectionSize = 30; testComp.collectionSize = 30;
testFixture.detectChanges();
currentPagination.next(Object.assign(new PaginationComponentOptions(), pagination, {currentPage: 3}));
testFixture.detectChanges();
changePage(testFixture, 3);
expectPages(testFixture, ['« Previous', '1', '2', '+3', '-» Next']); expectPages(testFixture, ['« Previous', '1', '2', '+3', '-» Next']);
changePage(testFixture, 0); currentPagination.next(Object.assign(new PaginationComponentOptions(), pagination, {currentPage: 2}));
testFixture.detectChanges();
expectPages(testFixture, ['« Previous', '1', '+2', '3', '» Next']); expectPages(testFixture, ['« Previous', '1', '+2', '3', '» Next']);
}); });
@@ -205,58 +242,41 @@ describe('Pagination component', () => {
testFixture.detectChanges(); testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '3', '» Next']); expectPages(testFixture, ['-« Previous', '+1', '2', '3', '» Next']);
paginationComponent.setPageSize(5); currentPagination.next(Object.assign(new PaginationComponentOptions(), pagination, {pageSize: 5}));
testFixture.detectChanges(); testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '3', '4', '5', '6', '» Next']); expectPages(testFixture, ['-« Previous', '+1', '2', '3', '4', '5', '6', '» Next']);
paginationComponent.setPageSize(10); currentPagination.next(Object.assign(new PaginationComponentOptions(), pagination, {pageSize: 10}));
testFixture.detectChanges(); testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '3', '» Next']); expectPages(testFixture, ['-« Previous', '+1', '2', '3', '» Next']);
paginationComponent.setPageSize(20); currentPagination.next(Object.assign(new PaginationComponentOptions(), pagination, {pageSize: 20}));
testFixture.detectChanges(); testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '» Next']); expectPages(testFixture, ['-« Previous', '+1', '2', '» Next']);
}); });
it('should emit pageChange event with correct value', fakeAsync(() => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
spyOn(testComp, 'pageChanged');
paginationComponent.setPage(3);
tick();
expect(testComp.pageChanged).toHaveBeenCalledWith(3);
}));
it('should emit pageSizeChange event with correct value', fakeAsync(() => { it('should emit pageSizeChange event with correct value', fakeAsync(() => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p; const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
spyOn(testComp, 'pageSizeChanged'); spyOn(testComp, 'pageSizeChanged');
paginationComponent.setPageSize(5); testComp.pageSizeChanged(5);
tick(); tick();
expect(testComp.pageSizeChanged).toHaveBeenCalledWith(5); expect(testComp.pageSizeChanged).toHaveBeenCalledWith(5);
})); }));
it('should set correct page route parameters', fakeAsync(() => { it('should call the updateRoute method on the paginationService with the correct params', fakeAsync(() => {
routerStub = testFixture.debugElement.injector.get(Router) as any;
testComp.collectionSize = 60; testComp.collectionSize = 60;
changePage(testFixture, 3); changePage(testFixture, 3);
tick(); tick();
expect(routerStub.navigate).toHaveBeenCalledWith([], { expect(paginationService.updateRoute).toHaveBeenCalledWith('test', Object.assign({ page: '3'}), {}, false);
queryParams: {
pageId: 'test',
page: '3',
pageSize: 10,
sortDirection: 'ASC',
sortField: 'dc.title'
}, queryParamsHandling: 'merge'
});
changePage(testFixture, 0);
tick();
expect(paginationService.updateRoute).toHaveBeenCalledWith('test', Object.assign({ page: '2'}), {}, false);
})); }));
it('should set correct pageSize route parameters', fakeAsync(() => { it('should set correct pageSize route parameters', fakeAsync(() => {
@@ -266,58 +286,9 @@ describe('Pagination component', () => {
changePageSize(testFixture, '20'); changePageSize(testFixture, '20');
tick(); tick();
expect(routerStub.navigate).toHaveBeenCalledWith([], { expect(paginationService.updateRoute).toHaveBeenCalledWith('test', Object.assign({ pageId: 'test', page: 1, pageSize: 20}), {}, false);
queryParams: {
pageId: 'test',
page: 1,
pageSize: 20,
sortDirection: 'ASC',
sortField: 'dc.title'
}, queryParamsHandling: 'merge'
});
})); }));
it('should set correct values', fakeAsync(() => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
routerStub = testFixture.debugElement.injector.get(Router) as any;
testComp.collectionSize = 60;
paginationComponent.setPage(3);
expect(paginationComponent.currentPage).toEqual(3);
paginationComponent.setPageSize(20);
expect(paginationComponent.pageSize).toEqual(20);
}));
it('should get parameters from route', () => {
activatedRouteStub = testFixture.debugElement.injector.get(ActivatedRoute) as any;
activatedRouteStub.testParams = {
pageId: 'test',
page: 2,
pageSize: 20
};
testFixture.detectChanges();
expectPages(testFixture, ['« Previous', '1', '+2', '3', '4', '5', '» Next']);
expect(testComp.paginationOptions.currentPage).toEqual(2);
expect(testComp.paginationOptions.pageSize).toEqual(20);
activatedRouteStub.testParams = {
pageId: 'test',
page: 3,
pageSize: 40
};
testFixture.detectChanges();
expectPages(testFixture, ['« Previous', '1', '2', '+3', '-» Next']);
expect(testComp.paginationOptions.currentPage).toEqual(3);
expect(testComp.paginationOptions.pageSize).toEqual(40);
});
it('should respond to windows resize', () => { it('should respond to windows resize', () => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p; const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
hostWindowServiceStub = testFixture.debugElement.injector.get(HostWindowService) as any; hostWindowServiceStub = testFixture.debugElement.injector.get(HostWindowService) as any;

View File

@@ -20,6 +20,7 @@ import { hasValue } from '../empty.util';
import { PageInfo } from '../../core/shared/page-info.model'; import { PageInfo } from '../../core/shared/page-info.model';
import { PaginationService } from '../../core/pagination/pagination.service'; import { PaginationService } from '../../core/pagination/pagination.service';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { tap } from 'rxjs/internal/operators/tap';
/** /**
* The default pagination controls component. * The default pagination controls component.
@@ -194,11 +195,14 @@ export class PaginationComponent implements OnDestroy, OnInit {
this.id = this.paginationOptions.id || null; this.id = this.paginationOptions.id || null;
this.pageSizeOptions = this.paginationOptions.pageSizeOptions; this.pageSizeOptions = this.paginationOptions.pageSizeOptions;
this.currentPage$ = this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe( this.currentPage$ = this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe(
tap((v) => console.log('currentPage', v)),
map((currentPagination) => currentPagination.currentPage) map((currentPagination) => currentPagination.currentPage)
); );
this.pageSize$ = this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe( this.pageSize$ = this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe(
map((currentPagination) => currentPagination.pageSize) map((currentPagination) => currentPagination.pageSize)
); );
this.pageSize$.subscribe((v) => console.log('this.pageSize$', v));
this.currentPage$.subscribe((v) => console.log('this.currentPage$', v));
let sortOptions; let sortOptions;
if (this.sortOptions) { if (this.sortOptions) {
@@ -237,6 +241,7 @@ export class PaginationComponent implements OnDestroy, OnInit {
*/ */
public doPageChange(page: number) { public doPageChange(page: number) {
this.updateParams({page: page.toString()}); this.updateParams({page: page.toString()});
this.emitPaginationChange();
} }
/** /**
@@ -247,6 +252,7 @@ export class PaginationComponent implements OnDestroy, OnInit {
*/ */
public doPageSizeChange(pageSize: number) { public doPageSizeChange(pageSize: number) {
this.updateParams({ pageId: this.id, page: 1, pageSize: pageSize }); this.updateParams({ pageId: this.id, page: 1, pageSize: pageSize });
this.emitPaginationChange();
} }
/** /**
@@ -257,6 +263,7 @@ export class PaginationComponent implements OnDestroy, OnInit {
*/ */
public doSortDirectionChange(sortDirection: SortDirection) { public doSortDirectionChange(sortDirection: SortDirection) {
this.updateParams({ pageId: this.id, page: 1, sortDirection: sortDirection }); this.updateParams({ pageId: this.id, page: 1, sortDirection: sortDirection });
this.emitPaginationChange();
} }
/** /**
@@ -267,50 +274,6 @@ export class PaginationComponent implements OnDestroy, OnInit {
*/ */
public doSortFieldChange(field: string) { public doSortFieldChange(field: string) {
this.updateParams({ pageId: this.id, page: 1, sortField: field }); this.updateParams({ pageId: this.id, page: 1, sortField: field });
}
/**
* Method to set the current page and trigger page change events
*
* @param page
* The new page value
*/
public setPage(page: number) {
this.pageChange.emit(page);
this.emitPaginationChange();
}
/**
* Method to set the current page size and trigger page size change events
*
* @param pageSize
* The new page size value.
*/
public setPageSize(pageSize: number) {
this.pageSizeChange.emit(pageSize);
this.emitPaginationChange();
}
/**
* Method to set the current sort direction and trigger sort direction change events
*
* @param sortDirection
* The new sort directionvalue.
*/
public setSortDirection(sortDirection: SortDirection) {
this.sortDirectionChange.emit(sortDirection);
this.emitPaginationChange();
}
/**
* Method to set the current sort field and trigger sort field change events
*
* @param sortField
* The new sort field.
*/
public setSortField(field: string) {
// this.sortField = field;
this.sortFieldChange.emit(field);
this.emitPaginationChange(); this.emitPaginationChange();
} }
@@ -370,21 +333,6 @@ export class PaginationComponent implements OnDestroy, OnInit {
} }
} }
/**
* Method to check if none of the query params necessary for pagination are filled out.
*
* @param paginateOptions
* The paginate options object.
*/
private isEmptyPaginationParams(paginateOptions): boolean {
const properties = ['id', 'currentPage', 'pageSize', 'pageSizeOptions'];
const missing = properties.filter((prop) => {
return !(prop in paginateOptions);
});
return properties.length === missing.length;
}
/** /**
* Property to check whether the current pagination object has multiple pages * Property to check whether the current pagination object has multiple pages
* @returns true if there are multiple pages, else returns false * @returns true if there are multiple pages, else returns false

View File

@@ -19,6 +19,9 @@ import { PaginationComponentOptions } from '../../../pagination/pagination-compo
import { buildPaginatedList } from '../../../../core/data/paginated-list.model'; import { buildPaginatedList } from '../../../../core/data/paginated-list.model';
import { PageInfo } from '../../../../core/shared/page-info.model'; import { PageInfo } from '../../../../core/shared/page-info.model';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { SortDirection, SortOptions } from '../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../core/data/request.models';
import { PaginationService } from '../../../../core/pagination/pagination.service';
describe('EpersonGroupListComponent test suite', () => { describe('EpersonGroupListComponent test suite', () => {
let comp: EpersonGroupListComponent; let comp: EpersonGroupListComponent;
@@ -27,6 +30,7 @@ describe('EpersonGroupListComponent test suite', () => {
let de; let de;
let groupService: any; let groupService: any;
let epersonService: any; let epersonService: any;
let paginationService;
const paginationOptions: PaginationComponentOptions = new PaginationComponentOptions(); const paginationOptions: PaginationComponentOptions = new PaginationComponentOptions();
paginationOptions.id = uniqueId('eperson-group-list-pagination-test'); paginationOptions.id = uniqueId('eperson-group-list-pagination-test');
@@ -60,6 +64,16 @@ describe('EpersonGroupListComponent test suite', () => {
const groupPaginatedList = buildPaginatedList(new PageInfo(), [GroupMock, GroupMock]); const groupPaginatedList = buildPaginatedList(new PageInfo(), [GroupMock, GroupMock]);
const groupPaginatedListRD = createSuccessfulRemoteDataObject(groupPaginatedList); const groupPaginatedListRD = createSuccessfulRemoteDataObject(groupPaginatedList);
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(paginationOptions),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
clearPagination: {}
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [
@@ -74,6 +88,7 @@ describe('EpersonGroupListComponent test suite', () => {
{ provide: EPersonDataService, useValue: mockEpersonService }, { provide: EPersonDataService, useValue: mockEpersonService },
{ provide: GroupDataService, useValue: mockGroupService }, { provide: GroupDataService, useValue: mockGroupService },
{ provide: RequestService, useValue: getMockRequestService() }, { provide: RequestService, useValue: getMockRequestService() },
{ provide: PaginationService, useValue: paginationService },
EpersonGroupListComponent, EpersonGroupListComponent,
ChangeDetectorRef, ChangeDetectorRef,
Injector Injector
@@ -177,12 +192,6 @@ describe('EpersonGroupListComponent test suite', () => {
a: false a: false
})); }));
}); });
it('should update list on page change', () => {
spyOn(comp, 'updateList');
expect(compAsAny.updateList).toHaveBeenCalled();
});
}); });
describe('when is list of group', () => { describe('when is list of group', () => {
@@ -254,12 +263,6 @@ describe('EpersonGroupListComponent test suite', () => {
})); }));
}); });
it('should update list on page change', () => {
spyOn(comp, 'updateList');
expect(compAsAny.updateList).toHaveBeenCalled();
});
it('should update list on search triggered', () => { it('should update list on search triggered', () => {
const options: PaginationComponentOptions = comp.paginationOptions; const options: PaginationComponentOptions = comp.paginationOptions;
const event: SearchEvent = { const event: SearchEvent = {
@@ -269,7 +272,7 @@ describe('EpersonGroupListComponent test suite', () => {
spyOn(comp, 'updateList'); spyOn(comp, 'updateList');
comp.onSearch(event); comp.onSearch(event);
expect(compAsAny.updateList).toHaveBeenCalledWith(options, 'metadata', 'test'); expect(compAsAny.updateList).toHaveBeenCalledWith('metadata', 'test');
}); });
}); });
}); });

View File

@@ -8,6 +8,12 @@ import { Community } from '../../core/shared/community.model';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { SearchService } from '../../core/shared/search/search.service'; import { SearchService } from '../../core/shared/search/search.service';
import { PaginationComponentOptions } from '../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../core/data/request.models';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../../core/pagination/pagination.service';
import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service';
describe('SearchFormComponent', () => { describe('SearchFormComponent', () => {
let comp: SearchFormComponent; let comp: SearchFormComponent;
@@ -15,6 +21,19 @@ describe('SearchFormComponent', () => {
let de: DebugElement; let de: DebugElement;
let el: HTMLElement; let el: HTMLElement;
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {}
});
const searchConfigService = {paginationID: 'test-id'};
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [FormsModule, RouterTestingModule, TranslateModule.forRoot()], imports: [FormsModule, RouterTestingModule, TranslateModule.forRoot()],
@@ -22,7 +41,9 @@ describe('SearchFormComponent', () => {
{ {
provide: SearchService, provide: SearchService,
useValue: {} useValue: {}
} },
{ provide: PaginationService, useValue: paginationService },
{ provide: SearchConfigurationService, useValue: searchConfigService }
], ],
declarations: [SearchFormComponent] declarations: [SearchFormComponent]
}).compileComponents(); }).compileComponents();

View File

@@ -15,6 +15,10 @@ import { FacetValue } from '../../../../facet-value.model';
import { FilterType } from '../../../../filter-type.model'; import { FilterType } from '../../../../filter-type.model';
import { SearchFilterConfig } from '../../../../search-filter-config.model'; import { SearchFilterConfig } from '../../../../search-filter-config.model';
import { SearchFacetOptionComponent } from './search-facet-option.component'; import { SearchFacetOptionComponent } from './search-facet-option.component';
import { PaginationComponentOptions } from '../../../../../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../../../core/data/request.models';
import { PaginationService } from '../../../../../../core/pagination/pagination.service';
describe('SearchFacetOptionComponent', () => { describe('SearchFacetOptionComponent', () => {
let comp: SearchFacetOptionComponent; let comp: SearchFacetOptionComponent;
@@ -81,6 +85,17 @@ describe('SearchFacetOptionComponent', () => {
let router; let router;
const page = observableOf(0); const page = observableOf(0);
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
getPageParam: 'p.page-id',
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule], imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule],
@@ -88,8 +103,10 @@ describe('SearchFacetOptionComponent', () => {
providers: [ providers: [
{ provide: SearchService, useValue: new SearchServiceStub(searchLink) }, { provide: SearchService, useValue: new SearchServiceStub(searchLink) },
{ provide: Router, useValue: new RouterStub() }, { provide: Router, useValue: new RouterStub() },
{ provide: PaginationService, useValue: paginationService },
{ {
provide: SearchConfigurationService, useValue: { provide: SearchConfigurationService, useValue: {
paginationID: 'page-id',
searchOptions: observableOf({}) searchOptions: observableOf({})
} }
}, },
@@ -131,7 +148,7 @@ describe('SearchFacetOptionComponent', () => {
(comp as any).updateAddParams(selectedValues); (comp as any).updateAddParams(selectedValues);
expect(comp.addQueryParams).toEqual({ expect(comp.addQueryParams).toEqual({
[mockFilterConfig.paramName]: [`${value1},${operator}`, value.value + ',equals'], [mockFilterConfig.paramName]: [`${value1},${operator}`, value.value + ',equals'],
page: 1 ['p.page-id']: 1
}); });
}); });
}); });
@@ -146,7 +163,7 @@ describe('SearchFacetOptionComponent', () => {
(comp as any).updateAddParams(selectedValues); (comp as any).updateAddParams(selectedValues);
expect(comp.addQueryParams).toEqual({ expect(comp.addQueryParams).toEqual({
[mockAuthorityFilterConfig.paramName]: [value1 + ',equals', `${value2},${operator}`], [mockAuthorityFilterConfig.paramName]: [value1 + ',equals', `${value2},${operator}`],
page: 1 ['p.page-id']: 1
}); });
}); });
}); });

View File

@@ -19,6 +19,10 @@ import {
RANGE_FILTER_MAX_SUFFIX, RANGE_FILTER_MAX_SUFFIX,
RANGE_FILTER_MIN_SUFFIX RANGE_FILTER_MIN_SUFFIX
} from '../../search-range-filter/search-range-filter.component'; } from '../../search-range-filter/search-range-filter.component';
import { PaginationComponentOptions } from '../../../../../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../../../core/data/request.models';
import { PaginationService } from '../../../../../../core/pagination/pagination.service';
describe('SearchFacetRangeOptionComponent', () => { describe('SearchFacetRangeOptionComponent', () => {
let comp: SearchFacetRangeOptionComponent; let comp: SearchFacetRangeOptionComponent;
@@ -54,6 +58,18 @@ describe('SearchFacetRangeOptionComponent', () => {
let router; let router;
const page = observableOf(0); const page = observableOf(0);
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {},
getPageParam: 'p.page-id',
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule], imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule],
@@ -61,9 +77,11 @@ describe('SearchFacetRangeOptionComponent', () => {
providers: [ providers: [
{ provide: SearchService, useValue: new SearchServiceStub(searchLink) }, { provide: SearchService, useValue: new SearchServiceStub(searchLink) },
{ provide: Router, useValue: new RouterStub() }, { provide: Router, useValue: new RouterStub() },
{ provide: PaginationService, useValue: paginationService },
{ {
provide: SearchConfigurationService, useValue: { provide: SearchConfigurationService, useValue: {
searchOptions: observableOf({}) searchOptions: observableOf({}),
paginationId: 'page-id'
} }
}, },
{ {
@@ -116,7 +134,7 @@ describe('SearchFacetRangeOptionComponent', () => {
expect(comp.changeQueryParams).toEqual({ expect(comp.changeQueryParams).toEqual({
[mockFilterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: ['50'], [mockFilterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: ['50'],
[mockFilterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: ['60'], [mockFilterConfig.paramName + RANGE_FILTER_MAX_SUFFIX]: ['60'],
page: 1 ['p.page-id']: 1
}); });
}); });
}); });

View File

@@ -14,6 +14,10 @@ import { FacetValue } from '../../../../facet-value.model';
import { FilterType } from '../../../../filter-type.model'; import { FilterType } from '../../../../filter-type.model';
import { SearchFilterConfig } from '../../../../search-filter-config.model'; import { SearchFilterConfig } from '../../../../search-filter-config.model';
import { SearchFacetSelectedOptionComponent } from './search-facet-selected-option.component'; import { SearchFacetSelectedOptionComponent } from './search-facet-selected-option.component';
import { PaginationComponentOptions } from '../../../../../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../../../core/data/request.models';
import { PaginationService } from '../../../../../../core/pagination/pagination.service';
describe('SearchFacetSelectedOptionComponent', () => { describe('SearchFacetSelectedOptionComponent', () => {
let comp: SearchFacetSelectedOptionComponent; let comp: SearchFacetSelectedOptionComponent;
@@ -106,6 +110,18 @@ describe('SearchFacetSelectedOptionComponent', () => {
let router; let router;
const page = observableOf(0); const page = observableOf(0);
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {},
getPageParam: 'p.page-id'
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule], imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule],
@@ -113,6 +129,7 @@ describe('SearchFacetSelectedOptionComponent', () => {
providers: [ providers: [
{ provide: SearchService, useValue: new SearchServiceStub(searchLink) }, { provide: SearchService, useValue: new SearchServiceStub(searchLink) },
{ provide: Router, useValue: new RouterStub() }, { provide: Router, useValue: new RouterStub() },
{ provide: PaginationService, useValue: paginationService },
{ {
provide: SearchConfigurationService, useValue: { provide: SearchConfigurationService, useValue: {
searchOptions: observableOf({}) searchOptions: observableOf({})
@@ -156,7 +173,7 @@ describe('SearchFacetSelectedOptionComponent', () => {
(comp as any).updateRemoveParams(selectedValues); (comp as any).updateRemoveParams(selectedValues);
expect(comp.removeQueryParams).toEqual({ expect(comp.removeQueryParams).toEqual({
[mockFilterConfig.paramName]: [value1], [mockFilterConfig.paramName]: [value1],
page: 1 ['p.page-id']: 1
}); });
}); });
}); });
@@ -172,7 +189,7 @@ describe('SearchFacetSelectedOptionComponent', () => {
(comp as any).updateRemoveParams(selectedAuthorityValues); (comp as any).updateRemoveParams(selectedAuthorityValues);
expect(comp.removeQueryParams).toEqual({ expect(comp.removeQueryParams).toEqual({
[mockAuthorityFilterConfig.paramName]: [`${value1},${operator}`], [mockAuthorityFilterConfig.paramName]: [`${value1},${operator}`],
page: 1 ['p.page-id']: 1
}); });
}); });
}); });

View File

@@ -11,6 +11,11 @@ import { SEARCH_CONFIG_SERVICE } from '../../../../+my-dspace-page/my-dspace-pag
import { SearchServiceStub } from '../../../testing/search-service.stub'; import { SearchServiceStub } from '../../../testing/search-service.stub';
import { SearchConfigurationServiceStub } from '../../../testing/search-configuration-service.stub'; import { SearchConfigurationServiceStub } from '../../../testing/search-configuration-service.stub';
import { SearchService } from '../../../../core/shared/search/search.service'; import { SearchService } from '../../../../core/shared/search/search.service';
import { PaginationComponentOptions } from '../../../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../../core/data/request.models';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
describe('SearchLabelComponent', () => { describe('SearchLabelComponent', () => {
let comp: SearchLabelComponent; let comp: SearchLabelComponent;
@@ -33,6 +38,18 @@ describe('SearchLabelComponent', () => {
filter2 filter2
]; ];
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
updateRouteWithUrl: {},
getPageParam: 'p.test-id'
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule], imports: [TranslateModule.forRoot(), NoopAnimationsModule, FormsModule],
@@ -40,6 +57,8 @@ describe('SearchLabelComponent', () => {
providers: [ providers: [
{ provide: SearchService, useValue: new SearchServiceStub(searchLink) }, { provide: SearchService, useValue: new SearchServiceStub(searchLink) },
{ provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }, { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() },
{ provide: SearchConfigurationService, useValue: new SearchConfigurationServiceStub() },
{ provide: PaginationService, useValue: paginationService },
{ provide: Router, useValue: {} } { provide: Router, useValue: {} }
// { provide: SearchConfigurationService, useValue: {getCurrentFrontendFilters : () => observableOf({})} } // { provide: SearchConfigurationService, useValue: {getCurrentFrontendFilters : () => observableOf({})} }
], ],

View File

@@ -16,6 +16,7 @@ import { take } from 'rxjs/operators';
import { SEARCH_CONFIG_SERVICE } from '../../../+my-dspace-page/my-dspace-page.component'; import { SEARCH_CONFIG_SERVICE } from '../../../+my-dspace-page/my-dspace-page.component';
import { SidebarService } from '../../sidebar/sidebar.service'; import { SidebarService } from '../../sidebar/sidebar.service';
import { SidebarServiceStub } from '../../testing/sidebar-service.stub'; import { SidebarServiceStub } from '../../testing/sidebar-service.stub';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('SearchSettingsComponent', () => { describe('SearchSettingsComponent', () => {
@@ -32,6 +33,8 @@ describe('SearchSettingsComponent', () => {
let scopeParam; let scopeParam;
let paginatedSearchOptions; let paginatedSearchOptions;
let paginationService;
let activatedRouteStub; let activatedRouteStub;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
@@ -62,6 +65,12 @@ describe('SearchSettingsComponent', () => {
}), }),
}; };
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
resetPage: {},
});
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([])], imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([])],
declarations: [SearchSettingsComponent, EnumKeysPipe, VarDirective], declarations: [SearchSettingsComponent, EnumKeysPipe, VarDirective],
@@ -77,6 +86,10 @@ describe('SearchSettingsComponent', () => {
provide: SearchFilterService, provide: SearchFilterService,
useValue: {}, useValue: {},
}, },
{
provide: PaginationService,
useValue: paginationService,
},
{ {
provide: SEARCH_CONFIG_SERVICE, provide: SEARCH_CONFIG_SERVICE,
useValue: { useValue: {

View File

@@ -11,12 +11,17 @@ import { StartsWithDateComponent } from './starts-with-date.component';
import { ActivatedRouteStub } from '../../testing/active-router.stub'; import { ActivatedRouteStub } from '../../testing/active-router.stub';
import { EnumKeysPipe } from '../../utils/enum-keys-pipe'; import { EnumKeysPipe } from '../../utils/enum-keys-pipe';
import { RouterStub } from '../../testing/router.stub'; import { RouterStub } from '../../testing/router.stub';
import { PaginationComponentOptions } from '../../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('StartsWithDateComponent', () => { describe('StartsWithDateComponent', () => {
let comp: StartsWithDateComponent; let comp: StartsWithDateComponent;
let fixture: ComponentFixture<StartsWithDateComponent>; let fixture: ComponentFixture<StartsWithDateComponent>;
let route: ActivatedRoute; let route: ActivatedRoute;
let router: Router; let router: Router;
let paginationService;
const options = [2019, 2018, 2017, 2016, 2015]; const options = [2019, 2018, 2017, 2016, 2015];
@@ -25,13 +30,25 @@ describe('StartsWithDateComponent', () => {
queryParams: observableOf({}) queryParams: observableOf({})
}); });
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [StartsWithDateComponent, EnumKeysPipe], declarations: [StartsWithDateComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: 'startsWithOptions', useValue: options }, { provide: 'startsWithOptions', useValue: options },
{ provide: 'paginationId', useValue: 'page-id' },
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: PaginationService, useValue: paginationService },
{ provide: Router, useValue: new RouterStub() } { provide: Router, useValue: new RouterStub() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

@@ -8,6 +8,11 @@ import { EnumKeysPipe } from '../../utils/enum-keys-pipe';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { StartsWithTextComponent } from './starts-with-text.component'; import { StartsWithTextComponent } from './starts-with-text.component';
import { PaginationComponentOptions } from '../../pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../../core/data/request.models';
import { of as observableOf } from 'rxjs';
import { PaginationService } from '../../../core/pagination/pagination.service';
describe('StartsWithTextComponent', () => { describe('StartsWithTextComponent', () => {
let comp: StartsWithTextComponent; let comp: StartsWithTextComponent;
@@ -17,12 +22,24 @@ describe('StartsWithTextComponent', () => {
const options = ['0-9', 'A', 'B', 'C']; const options = ['0-9', 'A', 'B', 'C'];
const pagination = Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 });
const sort = new SortOptions('score', SortDirection.DESC);
const findlistOptions = Object.assign(new FindListOptions(), { currentPage: 1, elementsPerPage: 20 });
const paginationService = jasmine.createSpyObj('PaginationService', {
getCurrentPagination: observableOf(pagination),
getCurrentSort: observableOf(sort),
getFindListOptions: observableOf(findlistOptions),
resetPage: {},
});
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [StartsWithTextComponent, EnumKeysPipe], declarations: [StartsWithTextComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: 'startsWithOptions', useValue: options } { provide: 'startsWithOptions', useValue: options },
{ provide: 'paginationId', useValue: 'page-id' },
{ provide: PaginationService, useValue: paginationService }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();

View File

@@ -2,6 +2,8 @@ import { BehaviorSubject, of as observableOf } from 'rxjs';
export class SearchConfigurationServiceStub { export class SearchConfigurationServiceStub {
public paginationID = 'test-id';
private searchOptions: BehaviorSubject<any> = new BehaviorSubject<any>({}); private searchOptions: BehaviorSubject<any> = new BehaviorSubject<any>({});
private paginatedSearchOptions: BehaviorSubject<any> = new BehaviorSubject<any>({}); private paginatedSearchOptions: BehaviorSubject<any> = new BehaviorSubject<any>({});

View File

@@ -115,15 +115,22 @@ describe('SubmissionImportExternalComponent test suite', () => {
spyOn(compAsAny.routeService, 'getQueryParameterValue').and.returnValues(observableOf('source'), observableOf('dummy')); spyOn(compAsAny.routeService, 'getQueryParameterValue').and.returnValues(observableOf('source'), observableOf('dummy'));
fixture.detectChanges(); fixture.detectChanges();
expect(compAsAny.retrieveExternalSources).toHaveBeenCalledWith('source', 'dummy'); expect(compAsAny.retrieveExternalSources).toHaveBeenCalled();
}); });
it('Should call \'getExternalSourceEntries\' properly', () => { it('Should call \'getExternalSourceEntries\' properly', () => {
comp.routeData = { sourceId: '', query: '' }; spyOn(routeServiceStub, 'getQueryParameterValue').and.callFake((param) => {
scheduler.schedule(() => compAsAny.retrieveExternalSources('orcidV2', 'test')); if (param === 'source') {
scheduler.flush(); return observableOf('orcidV2');
} else if (param === 'query') {
return observableOf('test');
}
return observableOf({});
});
fixture.detectChanges();
expect(comp.routeData).toEqual({ sourceId: 'orcidV2', query: 'test' });
expect(comp.isLoading$.value).toBe(false); expect(comp.isLoading$.value).toBe(false);
expect(compAsAny.externalService.getExternalSourceEntries).toHaveBeenCalled(); expect(compAsAny.externalService.getExternalSourceEntries).toHaveBeenCalled();
}); });

View File

@@ -20,7 +20,6 @@ import { fadeIn } from '../../shared/animations/fade';
import { PageInfo } from '../../core/shared/page-info.model'; import { PageInfo } from '../../core/shared/page-info.model';
import { hasValue, isNotEmpty } from '../../shared/empty.util'; import { hasValue, isNotEmpty } from '../../shared/empty.util';
import { getFinishedRemoteData } from '../../core/shared/operators'; import { getFinishedRemoteData } from '../../core/shared/operators';
import { PaginatedSearchOptions } from '../../shared/search/paginated-search-options.model';
/** /**
* This component allows to submit a new workspaceitem importing the data from an external source. * This component allows to submit a new workspaceitem importing the data from an external source.
@@ -46,7 +45,7 @@ export class SubmissionImportExternalComponent implements OnInit, OnDestroy {
*/ */
public isLoading$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); public isLoading$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public reload$: BehaviorSubject<{query: string, source: string}>; public reload$: BehaviorSubject<{query: string, source: string}> = new BehaviorSubject<{query: string; source: string}>({query: '', source: ''});
/** /**
* Configuration to use for the import buttons * Configuration to use for the import buttons
*/ */
@@ -122,9 +121,10 @@ export class SubmissionImportExternalComponent implements OnInit, OnDestroy {
]).pipe( ]).pipe(
take(1) take(1)
).subscribe(([source, query]: [string, string]) => { ).subscribe(([source, query]: [string, string]) => {
this.reload$ = new BehaviorSubject<{query: string; source: string}>({query: query, source: source}); this.reload$.next({query: query, source: source});
this.retrieveExternalSources(source, query); this.retrieveExternalSources();
})); }));
this.reload$.subscribe((v) => console.log('this.reload$', v));
} }
/** /**
@@ -167,8 +167,9 @@ export class SubmissionImportExternalComponent implements OnInit, OnDestroy {
* @param source The source tupe * @param source The source tupe
* @param query The query string to search * @param query The query string to search
*/ */
private retrieveExternalSources(sourcesss: string, querysss: string): void { private retrieveExternalSources(): void {
this.reload$.subscribe((sourceQueryObject: {source: string, query: string}) => { this.reload$.subscribe((sourceQueryObject: {source: string, query: string}) => {
console.log('ping?', sourceQueryObject);
const source = sourceQueryObject.source; const source = sourceQueryObject.source;
const query = sourceQueryObject.query; const query = sourceQueryObject.query;
if (isNotEmpty(source) && isNotEmpty(query)) { if (isNotEmpty(source) && isNotEmpty(query)) {
@@ -177,6 +178,7 @@ export class SubmissionImportExternalComponent implements OnInit, OnDestroy {
this.isLoading$.next(true); this.isLoading$.next(true);
this.subs.push( this.subs.push(
this.searchConfigService.paginatedSearchOptions.pipe( this.searchConfigService.paginatedSearchOptions.pipe(
tap((v) => console.log('searchpag?', v)),
filter((searchOptions) => searchOptions.query === query), filter((searchOptions) => searchOptions.query === query),
mergeMap((searchOptions) => this.externalService.getExternalSourceEntries(this.routeData.sourceId, searchOptions).pipe( mergeMap((searchOptions) => this.externalService.getExternalSourceEntries(this.routeData.sourceId, searchOptions).pipe(
getFinishedRemoteData(), getFinishedRemoteData(),