fixed tests after angular 10 upgrade

This commit is contained in:
Giuseppe Digilio
2020-12-03 19:45:05 +01:00
parent 9ed1c74f29
commit 10d0c2e518
212 changed files with 1461 additions and 1333 deletions

View File

@@ -26,7 +26,7 @@ describe('protractor SearchPage', () => {
page.getCurrentScope()
.then((s: string) => {
expect<string>(s).toEqual(scopeString);
})
});
});
});
@@ -41,9 +41,9 @@ describe('protractor SearchPage', () => {
browser.wait(() => {
return browser.getCurrentUrl().then((url: string) => {
return url.indexOf('scope=' + encodeURI(scopeString)) !== -1;
})
})
})
});
});
});
});
});

View File

@@ -52,7 +52,7 @@ describe('EPeopleRegistryComponent', () => {
searchByScope(scope: string, query: string, options: FindListOptions = {}): Observable<RemoteData<PaginatedList<EPerson>>> {
if (scope === 'email') {
const result = this.allEpeople.find((ePerson: EPerson) => {
return ePerson.email === query
return ePerson.email === query;
});
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [result]));
}
@@ -61,7 +61,7 @@ describe('EPeopleRegistryComponent', () => {
return createSuccessfulRemoteDataObject$(new PaginatedList(null, this.allEpeople));
}
const result = this.allEpeople.find((ePerson: EPerson) => {
return (ePerson.name.includes(query) || ePerson.email.includes(query))
return (ePerson.name.includes(query) || ePerson.email.includes(query));
});
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [result]));
}
@@ -132,7 +132,7 @@ describe('EPeopleRegistryComponent', () => {
expect(ePeopleIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === ePerson.uuid);
})).toBeTruthy();
})
});
});
describe('search', () => {
@@ -192,7 +192,7 @@ describe('EPeopleRegistryComponent', () => {
expect(component.isEPersonFormShown).toEqual(true);
}
})
});
});
it('EPerson search section is hidden', () => {
@@ -240,6 +240,6 @@ describe('EPeopleRegistryComponent', () => {
expect(deleteButton.nativeElement.disabled).toBe(true);
});
})
})
});
});
});

View File

@@ -1,7 +1,7 @@
import { Observable, of as observableOf } from 'rxjs';
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule, By } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@@ -39,7 +39,7 @@ describe('EPersonFormComponent', () => {
let authorizationService: AuthorizationDataService;
let groupsDataService: GroupDataService;
beforeEach(async(() => {
beforeEach(waitForAsync(() => {
mockEPeople = [EPersonMock, EPersonMock2];
ePersonDataServiceStub = {
activeEPerson: null,
@@ -53,7 +53,7 @@ describe('EPersonFormComponent', () => {
searchByScope(scope: string, query: string, options: FindListOptions = {}): Observable<RemoteData<PaginatedList<EPerson>>> {
if (scope === 'email') {
const result = this.allEpeople.find((ePerson: EPerson) => {
return ePerson.email === query
return ePerson.email === query;
});
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [result]));
}
@@ -62,7 +62,7 @@ describe('EPersonFormComponent', () => {
return createSuccessfulRemoteDataObject$(new PaginatedList(null, this.allEpeople));
}
const result = this.allEpeople.find((ePerson: EPerson) => {
return (ePerson.name.includes(query) || ePerson.email.includes(query))
return (ePerson.name.includes(query) || ePerson.email.includes(query));
});
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [result]));
}
@@ -75,7 +75,7 @@ describe('EPersonFormComponent', () => {
return observableOf(true);
},
create(ePerson: EPerson) {
this.allEpeople = [...this.allEpeople, ePerson]
this.allEpeople = [...this.allEpeople, ePerson];
},
editEPerson(ePerson: EPerson) {
this.activeEPerson = ePerson;
@@ -87,7 +87,7 @@ describe('EPersonFormComponent', () => {
// empty
},
tryToCreate(ePerson: EPerson): Observable<RestResponse> {
this.allEpeople = [...this.allEpeople, ePerson]
this.allEpeople = [...this.allEpeople, ePerson];
return observableOf(new RestResponse(true, 200, 'Success'));
},
updateEPerson(ePerson: EPerson): Observable<RestResponse> {
@@ -188,7 +188,7 @@ describe('EPersonFormComponent', () => {
fixture.detectChanges();
});
it('should emit a new eperson using the correct values', async(() => {
it('should emit a new eperson using the correct values', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.submitForm.emit).toHaveBeenCalledWith(expected);
});
@@ -200,6 +200,7 @@ describe('EPersonFormComponent', () => {
beforeEach(() => {
expectedWithId = Object.assign(new EPerson(), {
id: 'id',
metadata: {
'eperson.firstname': [
{
@@ -215,13 +216,14 @@ describe('EPersonFormComponent', () => {
email: email,
canLogIn: canLogIn,
requireCertificate: requireCertificate,
_links: undefined
});
spyOn(ePersonDataServiceStub, 'getActiveEPerson').and.returnValue(observableOf(expectedWithId));
component.onSubmit();
fixture.detectChanges();
});
it('should emit the existing eperson using the correct values', async(() => {
it('should emit the existing eperson using the correct values', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.submitForm.emit).toHaveBeenCalledWith(expectedWithId);
});
@@ -280,7 +282,7 @@ describe('EPersonFormComponent', () => {
spyOn(component.epersonService, 'getActiveEPerson').and.returnValue(observableOf(eperson));
modalService = (component as any).modalService;
spyOn(modalService, 'open').and.returnValue(Object.assign({ componentInstance: Object.assign({ response: observableOf(true) }) }));
fixture.detectChanges()
fixture.detectChanges();
});
@@ -291,7 +293,7 @@ describe('EPersonFormComponent', () => {
it ('the delete button should be disabled if the eperson cannot be deleted', () => {
component.canDelete$ = observableOf(false);
fixture.detectChanges()
fixture.detectChanges();
const deleteButton = fixture.debugElement.query(By.css('.delete-button'));
expect(deleteButton.nativeElement.disabled).toBe(true);
});
@@ -310,8 +312,8 @@ describe('EPersonFormComponent', () => {
const deleteButton = fixture.debugElement.query(By.css('.delete-button'));
expect(deleteButton.nativeElement.disabled).toBe(false);
deleteButton.triggerEventHandler('click', null);
fixture.detectChanges()
fixture.detectChanges();
expect(component.epersonService.deleteEPerson).toHaveBeenCalledWith(eperson);
});
})
});
});

View File

@@ -47,7 +47,7 @@ describe('GroupFormComponent', () => {
let expected;
beforeEach(async(() => {
groups = [GroupMock, GroupMock2]
groups = [GroupMock, GroupMock2];
groupName = 'testGroupName';
groupDescription = 'testDescription';
expected = Object.assign(new Group(), {
@@ -71,7 +71,7 @@ describe('GroupFormComponent', () => {
return '/admin/access-control/groups';
},
editGroup(group: Group) {
this.activeGroup = group
this.activeGroup = group;
},
cancelEditGroup(): void {
this.activeGroup = null;
@@ -80,11 +80,11 @@ describe('GroupFormComponent', () => {
return observableOf({ payload: null, hasSucceeded: true });
},
tryToCreate(group: Group): Observable<RestResponse> {
this.allGroups = [...this.allGroups, group]
this.allGroups = [...this.allGroups, group];
return observableOf(new RestResponse(true, 200, 'Success'));
},
searchGroups(query: string): Observable<RemoteData<PaginatedList<Group>>> {
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []))
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []));
}
};
builderService = getMockFormBuilderService();

View File

@@ -51,13 +51,13 @@ describe('MembersListComponent', () => {
epersonMembers: epersonMembers,
subgroupMembers: subgroupMembers,
findAllByHref(href: string): Observable<RemoteData<PaginatedList<EPerson>>> {
return createSuccessfulRemoteDataObject$(new PaginatedList<EPerson>(new PageInfo(), groupsDataServiceStub.getEPersonMembers()))
return createSuccessfulRemoteDataObject$(new PaginatedList<EPerson>(new PageInfo(), groupsDataServiceStub.getEPersonMembers()));
},
searchByScope(scope: string, query: string): Observable<RemoteData<PaginatedList<EPerson>>> {
if (query === '') {
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), allEPersons))
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), allEPersons));
}
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []))
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []));
},
clearEPersonRequests() {
// empty
@@ -82,9 +82,9 @@ describe('MembersListComponent', () => {
},
searchGroups(query: string): Observable<RemoteData<PaginatedList<Group>>> {
if (query === '') {
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), this.allGroups))
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), this.allGroups));
}
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []))
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []));
},
addMemberToGroup(parentGroup, eperson: EPerson): Observable<RestResponse> {
this.epersonMembers = [...this.epersonMembers, eperson];
@@ -106,7 +106,7 @@ describe('MembersListComponent', () => {
}
});
if (this.epersonMembers === undefined) {
this.epersonMembers = []
this.epersonMembers = [];
}
return observableOf(new RestResponse(true, 200, 'Success'));
}
@@ -189,8 +189,8 @@ describe('MembersListComponent', () => {
expect(addButton).toBeDefined();
}
}
})
})
});
});
});
});
@@ -211,7 +211,7 @@ describe('MembersListComponent', () => {
expect(addButton).toBeUndefined();
expect(deleteButton).toBeDefined();
}
})
});
});
});
@@ -231,7 +231,7 @@ describe('MembersListComponent', () => {
expect(deleteButton).toBeUndefined();
expect(addButton).toBeDefined();
}
})
});
});
});
});

View File

@@ -51,16 +51,16 @@ describe('SubgroupsListComponent', () => {
return this.activeGroup;
},
findAllByHref(href: string): Observable<RemoteData<PaginatedList<Group>>> {
return createSuccessfulRemoteDataObject$(new PaginatedList<Group>(new PageInfo(), this.subgroups))
return createSuccessfulRemoteDataObject$(new PaginatedList<Group>(new PageInfo(), this.subgroups));
},
getGroupEditPageRouterLink(group: Group): string {
return '/admin/access-control/groups/' + group.id;
},
searchGroups(query: string): Observable<RemoteData<PaginatedList<Group>>> {
if (query === '') {
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), allGroups))
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), allGroups));
}
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []))
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), []));
},
addSubGroupToGroup(parentGroup, subgroup: Group): Observable<RestResponse> {
this.subgroups = [...this.subgroups, subgroup];
@@ -126,7 +126,7 @@ describe('SubgroupsListComponent', () => {
expect(groupIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === group.uuid);
})).toBeTruthy();
})
});
});
describe('if first group delete button is pressed', () => {
@@ -164,7 +164,7 @@ describe('SubgroupsListComponent', () => {
expect(groupIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === group.uuid);
})).toBeTruthy();
})
});
});
describe('if group is already a subgroup', () => {
@@ -180,7 +180,7 @@ describe('SubgroupsListComponent', () => {
expect(addButton).toBeUndefined();
expect(deleteButton).toBeDefined();
}
})
});
} else {
getSubgroups.map((group: Group) => {
groupsFound.map((foundGroupRowElement) => {
@@ -196,8 +196,8 @@ describe('SubgroupsListComponent', () => {
expect(addButton).toBeDefined();
}
}
})
})
});
});
}
});
});

View File

@@ -72,7 +72,7 @@ describe('GroupRegistryComponent', () => {
return createSuccessfulRemoteDataObject$(new PaginatedList(null, this.allGroups));
}
const result = this.allGroups.find((group: Group) => {
return (group.id.includes(query))
return (group.id.includes(query));
});
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [result]));
}
@@ -115,7 +115,7 @@ describe('GroupRegistryComponent', () => {
expect(groupIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === group.uuid);
})).toBeTruthy();
})
});
});
describe('search', () => {

View File

@@ -67,8 +67,8 @@ describe('MetadataFieldFormComponent', () => {
afterEach(() => {
component = null;
registryService = null
})
registryService = null;
});
describe('when submitting the form', () => {
const element = 'fakeElement';

View File

@@ -62,5 +62,5 @@ describe('CollectionAdminSearchResultGridElementComponent', () => {
const a = fixture.debugElement.query(By.css('a.edit-link'));
const link = a.nativeElement.href;
expect(link).toContain(getCollectionEditRoute(id));
})
});
});

View File

@@ -66,5 +66,5 @@ describe('CommunityAdminSearchResultGridElementComponent', () => {
const a = fixture.debugElement.query(By.css('a.edit-link'));
const link = a.nativeElement.href;
expect(link).toContain(getCommunityEditRoute(id));
})
});
});

View File

@@ -117,5 +117,5 @@ describe('ItemAdminSearchResultGridElementComponent', () => {
const badge = fixture.debugElement.query(By.css('div.private-badge'));
expect(badge).not.toBeNull();
});
})
});
});

View File

@@ -56,5 +56,5 @@ describe('CollectionAdminSearchResultListElementComponent', () => {
const a = fixture.debugElement.query(By.css('a'));
const link = a.nativeElement.href;
expect(link).toContain(getCollectionEditRoute(id));
})
});
});

View File

@@ -56,5 +56,5 @@ describe('CommunityAdminSearchResultListElementComponent', () => {
const a = fixture.debugElement.query(By.css('a'));
const link = a.nativeElement.href;
expect(link).toContain(getCommunityEditRoute(id));
})
});
});

View File

@@ -97,5 +97,5 @@ describe('ItemAdminSearchResultListElementComponent', () => {
const badge = fixture.debugElement.query(By.css('div.private-badge'));
expect(badge).not.toBeNull();
});
})
});
});

View File

@@ -140,5 +140,5 @@ describe('ItemAdminSearchResultActionsComponent', () => {
const link = a.nativeElement.href;
expect(link).toContain(new URLCombiner(getItemEditRoute(id), ITEM_EDIT_PUBLIC_PATH).toString());
});
})
});
});

View File

@@ -72,7 +72,7 @@ describe('AdminSidebarComponent', () => {
it('should set the sidebarClosed to false', () => {
expect(comp.sidebarClosed).toBeFalsy();
})
});
});
describe('when collapsing', () => {
@@ -83,8 +83,8 @@ describe('AdminSidebarComponent', () => {
it('should set the sidebarOpen to false', () => {
expect(comp.sidebarOpen).toBeFalsy();
})
})
});
});
});
describe('finishSlide', () => {
@@ -96,7 +96,7 @@ describe('AdminSidebarComponent', () => {
it('should set the sidebarClosed to true', () => {
expect(comp.sidebarClosed).toBeTruthy();
})
});
});
describe('when collapsing', () => {
@@ -107,8 +107,8 @@ describe('AdminSidebarComponent', () => {
it('should set the sidebarOpen to true', () => {
expect(comp.sidebarOpen).toBeTruthy();
})
})
});
});
});
describe('when the collapse icon is clicked', () => {

View File

@@ -32,7 +32,7 @@ describe('WorkflowItemAdminWorkflowGridElementComponent', () => {
function init() {
itemRD$ = createSuccessfulRemoteDataObject$(new Item());
id = '780b2588-bda5-4112-a1cd-0b15000a5339';
object = new WorkflowItemSearchResult()
object = new WorkflowItemSearchResult();
wfi = new WorkflowItem();
wfi.item = itemRD$;
object.indexableObject = wfi;

View File

@@ -29,7 +29,7 @@ describe('WorkflowItemAdminWorkflowListElementComponent', () => {
function init() {
itemRD$ = createSuccessfulRemoteDataObject$(new Item());
id = '780b2588-bda5-4112-a1cd-0b15000a5339';
object = new WorkflowItemSearchResult()
object = new WorkflowItemSearchResult();
wfi = new WorkflowItem();
wfi.item = itemRD$;
object.indexableObject = wfi;

View File

@@ -238,7 +238,7 @@ describe('EditBitstreamPageComponent', () => {
});
describe('when navigateToItemEditBitstreams is called, and the component has an itemId', () => {
it('should redirect to the item edit page on the bitstreams tab with the itemId from the component', () => {
comp.itemId = 'some-uuid1'
comp.itemId = 'some-uuid1';
comp.navigateToItemEditBitstreams();
expect(routerStub.navigate).toHaveBeenCalledWith([getItemEditRoute('some-uuid1'), 'bitstreams']);
});

View File

@@ -126,7 +126,7 @@ describe('BrowseByMetadataPageComponent', () => {
comp.items$.subscribe((result) => {
expect(result.payload.page).toEqual(mockItems);
});
})
});
});
describe('when calling browseParamsToOptions', () => {
@@ -151,7 +151,7 @@ describe('BrowseByMetadataPageComponent', () => {
expect(result.sort.direction).toEqual(SortDirection.ASC);
expect(result.sort.field).toEqual('fake-field');
expect(result.scope).toEqual('fake-scope');
})
});
});
});

View File

@@ -108,15 +108,15 @@ describe('CollectionItemMapperComponent', () => {
return observableOf('');
},
getQueryParameterValue: () => {
return observableOf('')
return observableOf('');
},
getQueryParamsWithPrefix: () => {
return observableOf('')
return observableOf('');
}
};
const fixedFilterServiceStub = {
getQueryByFilterName: () => {
return observableOf('')
return observableOf('');
}
};
@@ -197,7 +197,7 @@ describe('CollectionItemMapperComponent', () => {
it('should build a solr query to exclude the provided collection', () => {
expect(result).toEqual(expected);
})
});
});
describe('onCancel', () => {

View File

@@ -44,6 +44,6 @@ describe('CreateCollectionPageComponent', () => {
describe('frontendURL', () => {
it('should have the right frontendURL set', () => {
expect((comp as any).frontendURL).toEqual('/collections/');
})
});
});
});

View File

@@ -36,6 +36,6 @@ describe('DeleteCollectionPageComponent', () => {
describe('frontendURL', () => {
it('should have the right frontendURL set', () => {
expect((comp as any).frontendURL).toEqual('/collections/');
})
});
});
});

View File

@@ -97,28 +97,33 @@ describe('CollectionRolesComponent', () => {
fixture.detectChanges();
});
it('should display a collection admin role component', () => {
it('should display a collection admin role component', (done) => {
expect(de.query(By.css('ds-comcol-role .collection-admin')))
.toBeTruthy();
done();
});
it('should display a submitters role component', () => {
it('should display a submitters role component', (done) => {
expect(de.query(By.css('ds-comcol-role .submitters')))
.toBeTruthy();
done();
});
it('should display a default item read role component', () => {
it('should display a default item read role component', (done) => {
expect(de.query(By.css('ds-comcol-role .item_read')))
.toBeTruthy();
done();
});
it('should display a default bitstream read role component', () => {
it('should display a default bitstream read role component', (done) => {
expect(de.query(By.css('ds-comcol-role .bitstream_read')))
.toBeTruthy();
done();
});
it('should display a test workflow role component', () => {
it('should display a test workflow role component', (done) => {
expect(de.query(By.css('ds-comcol-role .test')))
.toBeTruthy();
done();
});
});

View File

@@ -172,7 +172,7 @@ describe('CollectionSourceComponent', () => {
});
it('should send a field update', () => {
expect(objectUpdatesService.saveAddFieldUpdate).toHaveBeenCalledWith(router.url, comp.contentSource)
expect(objectUpdatesService.saveAddFieldUpdate).toHaveBeenCalledWith(router.url, comp.contentSource);
});
it('should display the form', () => {

View File

@@ -50,6 +50,6 @@ describe('EditCollectionPageComponent', () => {
describe('type', () => {
it('should have the right type set', () => {
expect((comp as any).type).toEqual('collection');
})
});
});
});

View File

@@ -40,6 +40,6 @@ describe('CreateCommunityPageComponent', () => {
describe('frontendURL', () => {
it('should have the right frontendURL set', () => {
expect((comp as any).frontendURL).toEqual('/communities/');
})
});
});
});

View File

@@ -36,6 +36,6 @@ describe('DeleteCommunityPageComponent', () => {
describe('frontendURL', () => {
it('should have the right frontendURL set', () => {
expect((comp as any).frontendURL).toEqual('/communities/');
})
});
});
});

View File

@@ -37,6 +37,6 @@ describe('CommunityMetadataComponent', () => {
describe('frontendURL', () => {
it('should have the right frontendURL set', () => {
expect((comp as any).frontendURL).toEqual('/communities/');
})
});
});
});

View File

@@ -50,6 +50,6 @@ describe('EditCommunityPageComponent', () => {
describe('type', () => {
it('should have the right type set', () => {
expect((comp as any).type).toEqual('community');
})
});
});
});

View File

@@ -97,7 +97,7 @@ describe('CommunityPageSubCollectionList Component', () => {
let currentPage = options.currentPage;
let elementsPerPage = options.elementsPerPage;
if (currentPage === undefined) {
currentPage = 1
currentPage = 1;
}
elementsPerPage = 5;
const startPageIndex = (currentPage - 1) * elementsPerPage;

View File

@@ -97,7 +97,7 @@ describe('CommunityPageSubCommunityListComponent Component', () => {
let currentPage = options.currentPage;
let elementsPerPage = options.elementsPerPage;
if (currentPage === undefined) {
currentPage = 1
currentPage = 1;
}
elementsPerPage = 5;

View File

@@ -87,7 +87,7 @@ describe('TopLevelCommunityList Component', () => {
let currentPage = options.currentPage;
let elementsPerPage = options.elementsPerPage;
if (currentPage === undefined) {
currentPage = 1
currentPage = 1;
}
elementsPerPage = 5;

View File

@@ -213,7 +213,7 @@ describe('ItemBitstreamsComponent', () => {
finish: () => {
done();
}
})
});
});
it('should send out a patch for the move operation', () => {

View File

@@ -107,13 +107,13 @@ describe('ItemEditBitstreamComponent', () => {
describe('when canRemove is called', () => {
it('should return true', () => {
expect(comp.canRemove()).toEqual(true)
expect(comp.canRemove()).toEqual(true);
});
});
describe('when canUndo is called', () => {
it('should return false', () => {
expect(comp.canUndo()).toEqual(false)
expect(comp.canUndo()).toEqual(false);
});
});
});

View File

@@ -190,7 +190,7 @@ describe('ItemCollectionMapperComponent', () => {
it('should build a solr query to exclude the provided collection', () => {
expect(result).toEqual(expected);
})
});
});
describe('onCancel', () => {

View File

@@ -269,7 +269,7 @@ describe('EditInPlaceFieldComponent', () => {
const expected = '(a|)';
scheduler.expectObservable(comp.canSetEditable()).toBe(expected, { a: false });
});
})
});
});
});
@@ -412,7 +412,7 @@ describe('EditInPlaceFieldComponent', () => {
const expected = '(a|)';
scheduler.expectObservable(comp.canRemove()).toBe(expected, { a: false });
});
})
});
});
describe('canUndo', () => {

View File

@@ -98,5 +98,5 @@ describe('VirtualMetadataComponent', () => {
true
);
});
})
});
});

View File

@@ -91,14 +91,14 @@ describe('FullFileSectionComponent', () => {
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(() => {
@@ -108,13 +108,13 @@ describe('FullFileSectionComponent', () => {
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

@@ -78,5 +78,5 @@ describe('FullItemPageComponent', () => {
for (const metadatum of mockItem.allMetadata([])) {
expect(table.nativeElement.innerHTML).toContain(metadatum.value);
}
})
});
});

View File

@@ -103,15 +103,15 @@ describe('FileSectionComponent', () => {
it('should call the service to retrieve more bitstreams', () => {
const viewMore = fixture.debugElement.query(By.css('.bitstream-view-more'));
viewMore.triggerEventHandler('click', null);
expect(bitstreamDataService.findAllByItemAndBundleName).toHaveBeenCalled()
})
expect(bitstreamDataService.findAllByItemAndBundleName).toHaveBeenCalled();
});
it('one bitstream should be on the page', () => {
const viewMore = fixture.debugElement.query(By.css('.bitstream-view-more'));
viewMore.triggerEventHandler('click', null);
const fileDownloadLink = fixture.debugElement.queryAll(By.css('ds-file-download-link'));
expect(fileDownloadLink.length).toEqual(1);
})
});
describe('when it is then clicked again', () => {
beforeEach(() => {
@@ -120,12 +120,12 @@ describe('FileSectionComponent', () => {
viewMore.triggerEventHandler('click', null);
fixture.detectChanges();
})
});
it('should contain another bitstream', () => {
const fileDownloadLink = fixture.debugElement.queryAll(By.css('ds-file-download-link'));
expect(fileDownloadLink.length).toEqual(2);
})
})
});
});
});
describe('when its the last page of bitstreams', () => {
@@ -139,12 +139,12 @@ describe('FileSectionComponent', () => {
it('should not contain a view more link', () => {
const viewMore = fixture.debugElement.query(By.css('.bitstream-view-more'));
expect(viewMore).toBeNull();
})
});
it('should contain a view less link', () => {
const viewLess = fixture.debugElement.query(By.css('.bitstream-collapse'));
expect(viewLess).toBeDefined();
})
});
it('clicking on the view less link should reset the pages and call getNextPage()', () => {
const pageInfo = Object.assign(new PageInfo(), {
@@ -166,7 +166,7 @@ describe('FileSectionComponent', () => {
expect(bitstreamDataService.findAllByItemAndBundleName).toHaveBeenCalled();
expect(comp.currentPage).toBe(1);
expect(comp.isLastPage).toBeFalse();
})
});
})
})
});
});

View File

@@ -94,7 +94,7 @@ export function getItemPageFieldsTest(mockItem: Item, component) {
expect(containsFieldInput(fields, key)).toBeTruthy();
});
}
}
};
}
/**

View File

@@ -41,7 +41,7 @@ describe('RelatedEntitiesSearchComponent', () => {
it('should create a configuration$', () => {
comp.configuration$.subscribe((configuration) => {
expect(configuration).toEqual(mockConfiguration);
})
});
});
});

View File

@@ -44,7 +44,7 @@ describe('LoginPageComponent', () => {
});
it('should create instance', () => {
expect(comp).toBeDefined()
expect(comp).toBeDefined();
});
});

View File

@@ -25,7 +25,7 @@ describe('LogoutPageComponent', () => {
});
it('should create instance', () => {
expect(comp).toBeDefined()
expect(comp).toBeDefined();
});
});

View File

@@ -22,7 +22,7 @@ describe('LookupGuard', () => {
}
};
guard.canActivate(scopedRoute as any, undefined);
expect(dsoService.findByIdAndIDType).toHaveBeenCalledWith('123456789/1234', IdentifierType.HANDLE)
expect(dsoService.findByIdAndIDType).toHaveBeenCalledWith('123456789/1234', IdentifierType.HANDLE);
});
it('should call findByIdAndIDType with handle params', () => {
@@ -33,7 +33,7 @@ describe('LookupGuard', () => {
}
};
guard.canActivate(scopedRoute as any, undefined);
expect(dsoService.findByIdAndIDType).toHaveBeenCalledWith('123456789%2F1234', IdentifierType.HANDLE)
expect(dsoService.findByIdAndIDType).toHaveBeenCalledWith('123456789%2F1234', IdentifierType.HANDLE);
});
it('should call findByIdAndIDType with UUID params', () => {
@@ -44,7 +44,7 @@ describe('LookupGuard', () => {
}
};
guard.canActivate(scopedRoute as any, undefined);
expect(dsoService.findByIdAndIDType).toHaveBeenCalledWith('34cfed7c-f597-49ef-9cbe-ea351f0023c2', IdentifierType.UUID)
expect(dsoService.findByIdAndIDType).toHaveBeenCalledWith('34cfed7c-f597-49ef-9cbe-ea351f0023c2', IdentifierType.UUID);
});
});

View File

@@ -40,7 +40,7 @@ describe('ObjectNotFoundComponent', () => {
});
it('should create instance', () => {
expect(comp).toBeDefined()
expect(comp).toBeDefined();
});
it('should have id and idType', () => {

View File

@@ -106,7 +106,7 @@ describe('CollectionSelectorComponent', () => {
// tslint:disable-next-line: max-classes-per-file
const collectionDataServiceMock = {
getAuthorizedCollection(query: string, options: FindListOptions = {}, ...linksToFollow: Array<FollowLinkConfig<Collection>>): Observable<RemoteData<PaginatedList<Collection>>> {
getAuthorizedCollection(query: string, options: FindListOptions = {}, ...linksToFollow: FollowLinkConfig<Collection>[]): Observable<RemoteData<PaginatedList<Collection>>> {
return hot( 'a|', {
a: createSuccessfulRemoteDataObject(
new PaginatedList(new PageInfo(), collections)

View File

@@ -137,7 +137,7 @@ describe('MyDSpaceConfigurationService', () => {
describe('when subscribeToSearchOptions is called', () => {
beforeEach(() => {
(service as any).subscribeToSearchOptions(defaults)
(service as any).subscribeToSearchOptions(defaults);
});
it('should call all getters it needs, but not call any others', () => {
expect(service.getCurrentPagination).not.toHaveBeenCalled();

View File

@@ -1,11 +1,11 @@
import { ChangeDetectorRef, Component, NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, inject, TestBed } from '@angular/core/testing';
import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { By } from '@angular/platform-browser';
import { Store } from '@ngrx/store';
import { of as observableOf } from 'rxjs';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { ScrollToService } from '@nicky-lenaers/ngx-scroll-to';
import { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
import { AuthServiceStub } from '../../shared/testing/auth-service.stub';
@@ -13,53 +13,34 @@ import { AuthService } from '../../core/auth/auth.service';
import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub';
import { createTestComponent } from '../../shared/testing/utils.test';
import { MyDSpaceNewSubmissionComponent } from './my-dspace-new-submission.component';
import { AppState } from '../../app.reducer';
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { SharedModule } from '../../shared/shared.module';
import { getMockScrollToService } from '../../shared/mocks/scroll-to-service.mock';
import { UploaderService } from '../../shared/uploader/uploader.service';
import { By } from '@angular/platform-browser';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { HostWindowService } from '../../shared/host-window.service';
import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub';
import { UploaderComponent } from 'src/app/shared/uploader/uploader.component';
import { UploaderComponent } from '../../shared/uploader/uploader.component';
describe('MyDSpaceNewSubmissionComponent test', () => {
const translateService: TranslateService = jasmine.createSpyObj('translateService', {
get: (key: string): any => { observableOf(key) },
instant: jasmine.createSpy('instant')
});
const uploader: any = jasmine.createSpyObj('uploader', {
clearQueue: jasmine.createSpy('clearQueue')
clearQueue: jasmine.createSpy('clearQueue').and.stub(),
onBuildItemForm: jasmine.createSpy('onBuildItemForm').and.stub(),
uploadAll: jasmine.createSpy('uploadAll').and.stub()
});
const modalService = {
open: () => {
return { result: new Promise((res, rej) => {/****/}) };
}
};
const store: Store<AppState> = jasmine.createSpyObj('store', {
/* tslint:disable:no-empty */
dispatch: {},
/* tslint:enable:no-empty */
pipe: observableOf(true)
});
beforeEach(async(() => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
SharedModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
})
}),
NgbModule,
RouterTestingModule
],
declarations: [
MyDSpaceNewSubmissionComponent,
@@ -70,9 +51,7 @@ describe('MyDSpaceNewSubmissionComponent test', () => {
{ provide: HALEndpointService, useValue: new HALEndpointServiceStub('workspaceitems') },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: ScrollToService, useValue: getMockScrollToService() },
{ provide: Store, useValue: store },
{ provide: TranslateService, useValue: translateService },
{ provide: NgbModal, useValue: modalService },
NgbModal,
ChangeDetectorRef,
MyDSpaceNewSubmissionComponent,
UploaderService,
@@ -119,20 +98,25 @@ describe('MyDSpaceNewSubmissionComponent test', () => {
comp.uploaderComponent.uploader = uploader;
});
it('should call app.openDialog', () => {
it('should call app.openDialog', (done) => {
spyOn(comp, 'openDialog');
const submissionButton = fixture.debugElement.query(By.css('button.btn-primary'));
submissionButton.triggerEventHandler('click', {
preventDefault: () => {/**/
}
submissionButton.triggerEventHandler('click', null);
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(comp.openDialog).toHaveBeenCalled();
done();
});
expect(comp.openDialog).toHaveBeenCalled();
});
it('should show a collection selector if only one file are uploaded', () => {
it('should show a collection selector if only one file are uploaded', (done) => {
spyOn((comp as any).modalService, 'open').and.returnValue({ result: new Promise((res, rej) => {/****/}) });
comp.afterFileLoaded(['']);
expect((comp as any).modalService.open).toHaveBeenCalled();
done();
});
});
});

View File

@@ -3,7 +3,7 @@ import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { ActivatedRoute } from '@angular/router';
import { By } from '@angular/platform-browser';
import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Store } from '@ngrx/store';
@@ -28,6 +28,7 @@ import { RoleDirective } from '../shared/roles/role.directive';
import { RoleService } from '../core/roles/role.service';
import { RoleServiceMock } from '../shared/mocks/role-service.mock';
import { createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils';
import { SidebarServiceStub } from '../shared/testing/SidebarServiceStub';
describe('MyDSpacePageComponent', () => {
let comp: MyDSpacePageComponent;
@@ -76,13 +77,7 @@ describe('MyDSpacePageComponent', () => {
})
};
const sidebarService = {
isCollapsed: observableOf(true),
collapse: () => this.isCollapsed = observableOf(true),
expand: () => this.isCollapsed = observableOf(false)
};
beforeEach(async(() => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([]), NoopAnimationsModule, NgbCollapseModule],
declarations: [MyDSpacePageComponent, RoleDirective],
@@ -107,7 +102,7 @@ describe('MyDSpacePageComponent', () => {
},
{
provide: SidebarService,
useValue: sidebarService
useValue: SidebarServiceStub
},
{
provide: SearchFilterService,

View File

@@ -53,6 +53,6 @@ describe('MyDSpaceResultsComponent', () => {
const linkDes = fixture.debugElement.queryAll(By.css('text-muted'));
expect(linkDes).toBeDefined()
expect(linkDes).toBeDefined();
});
});

View File

@@ -1,6 +1,6 @@
import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Store } from '@ngrx/store';
import { TranslateModule } from '@ngx-translate/core';
@@ -24,6 +24,7 @@ import { RouteService } from '../core/services/route.service';
import { SearchConfigurationServiceStub } from '../shared/testing/search-configuration-service.stub';
import { createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils';
import { PaginatedSearchOptions } from '../shared/search/paginated-search-options.model';
import { SidebarServiceStub } from '../shared/testing/SidebarServiceStub';
let comp: SearchComponent;
let fixture: ComponentFixture<SearchComponent>;
@@ -70,21 +71,16 @@ const activatedRouteStub = {
scope: scopeParam
})
};
const sidebarService = {
isCollapsed: observableOf(true),
collapse: () => this.isCollapsed = observableOf(true),
expand: () => this.isCollapsed = observableOf(false)
};
const routeServiceStub = {
getRouteParameterValue: () => {
return observableOf('');
},
getQueryParameterValue: () => {
return observableOf('')
return observableOf('');
},
getQueryParamsWithPrefix: () => {
return observableOf('')
return observableOf('');
}
};
@@ -113,7 +109,7 @@ export function configureSearchComponentTestingModule(compType) {
},
{
provide: SidebarService,
useValue: sidebarService
useValue: SidebarServiceStub
},
{
provide: SearchFilterService,
@@ -144,7 +140,7 @@ export function configureSearchComponentTestingModule(compType) {
}
describe('SearchComponent', () => {
beforeEach(async(() => {
beforeEach(waitForAsync(() => {
configureSearchComponentTestingModule(SearchComponent);
}));

View File

@@ -1,10 +1,9 @@
import * as ngrx from '@ngrx/store';
import { async, ComponentFixture, inject, TestBed } from '@angular/core/testing';
import { Store, StoreModule } from '@ngrx/store';
import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { Store, StoreModule } from '@ngrx/store';
import { Angulartics2GoogleAnalytics } from 'angulartics2/ga';
// Load the implementations that should be tested
@@ -32,22 +31,25 @@ import { Angulartics2DSpace } from './statistics/angulartics/dspace-provider';
import { storeModuleConfig } from './app.reducer';
import { LocaleService } from './core/locale/locale.service';
import { authReducer } from './core/auth/auth.reducer';
import { cold } from 'jasmine-marbles';
import { provideMockStore } from '@ngrx/store/testing';
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
const menuService = new MenuServiceStub();
const initialState = {
core: { auth: { loading: false } }
};
describe('App component', () => {
function getMockLocaleService(): LocaleService {
return jasmine.createSpyObj('LocaleService', {
setCurrentLanguageCode: jasmine.createSpy('setCurrentLanguageCode')
})
});
}
// async beforeEach
beforeEach(async(() => {
beforeEach(waitForAsync(() => {
return TestBed.configureTestingModule({
imports: [
CommonModule,
@@ -72,6 +74,7 @@ describe('App component', () => {
{ provide: CSSVariableService, useClass: CSSVariableServiceStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(800) },
{ provide: LocaleService, useValue: getMockLocaleService() },
provideMockStore({ initialState }),
AppComponent,
RouteService
],
@@ -81,16 +84,6 @@ describe('App component', () => {
// synchronous beforeEach
beforeEach(() => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => cold('a', {
a: {
core: { auth: { loading: false } }
}
})
};
});
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance; // component test instance
fixture.detectChanges();

View File

@@ -60,7 +60,7 @@ describe('BreadcrumbsComponent', () => {
expectedBreadcrumbs = [
new Breadcrumb(breadcrumbConfigA.key, breadcrumbConfigA.url),
new Breadcrumb(breadcrumbConfigB.key, breadcrumbConfigB.url)
]
];
}
@@ -109,7 +109,7 @@ describe('BreadcrumbsComponent', () => {
describe('resolveBreadcrumbs', () => {
it('should return the correct breadcrumbs', () => {
const breadcrumbs = component.resolveBreadcrumbs(route.root);
getTestScheduler().expectObservable(breadcrumbs).toBe('(a|)', { a: expectedBreadcrumbs })
})
})
getTestScheduler().expectObservable(breadcrumbs).toBe('(a|)', { a: expectedBreadcrumbs });
});
});
});

View File

@@ -130,7 +130,7 @@ describe('CommunityListService', () => {
let currentPage = options.currentPage;
const elementsPerPage = 3;
if (currentPage === undefined) {
currentPage = 1
currentPage = 1;
}
const startPageIndex = (currentPage - 1) * elementsPerPage;
let endPageIndex = (currentPage * elementsPerPage);
@@ -144,7 +144,7 @@ describe('CommunityListService', () => {
let currentPage = options.currentPage;
let elementsPerPage = options.elementsPerPage;
if (currentPage === undefined) {
currentPage = 1
currentPage = 1;
}
if (elementsPerPage === 0) {
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), (foundCom.subcommunities as [Community])));
@@ -169,7 +169,7 @@ describe('CommunityListService', () => {
let currentPage = options.currentPage;
let elementsPerPage = options.elementsPerPage;
if (currentPage === undefined) {
currentPage = 1
currentPage = 1;
}
if (elementsPerPage === 0) {
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), (foundCom.collections as [Collection])));
@@ -561,7 +561,7 @@ describe('CommunityListService', () => {
});
mockCollectionsPage2.map((collection) => {
expect(flatNodeList.find((flatnode) => (flatnode.id === collection.id))).toBeTruthy();
})
});
});
it('the collections of the test community are a level higher than the parent community', () => {
mockCollectionsPage1.map((collection) => {
@@ -569,7 +569,7 @@ describe('CommunityListService', () => {
});
mockCollectionsPage2.map((collection) => {
expect((flatNodeList.find((flatnode) => (flatnode.id === collection.id))).level).toEqual(flatNodeList[0].level + 1);
})
});
});
});
});

View File

@@ -288,7 +288,7 @@ describe('CommunityListComponent', () => {
expect(allNodes.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === subcom.name);
})).toBeTruthy();
})
});
});
});
});

View File

@@ -1,60 +1,91 @@
import { Store } from '@ngrx/store';
import * as ngrx from '@ngrx/store';
import { cold, getTestScheduler, initTestScheduler, resetTestScheduler } from 'jasmine-marbles/es6';
import { of as observableOf } from 'rxjs';
import { AppState } from '../../app.reducer';
import { TestBed, waitForAsync } from '@angular/core/testing';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { Store, StoreModule } from '@ngrx/store';
import { cold } from 'jasmine-marbles';
import { AppState, storeModuleConfig } from '../../app.reducer';
import { AuthBlockingGuard } from './auth-blocking.guard';
import { authReducer } from './auth.reducer';
describe('AuthBlockingGuard', () => {
let guard: AuthBlockingGuard;
beforeEach(() => {
guard = new AuthBlockingGuard(new Store<AppState>(undefined, undefined, undefined));
initTestScheduler();
});
let initialState;
let store: Store<AppState>;
let mockStore: MockStore<AppState>;
afterEach(() => {
getTestScheduler().flush();
resetTestScheduler();
initialState = {
core: {
auth: {
authenticated: false,
loaded: false,
blocking: undefined,
loading: false,
authMethods: []
}
}
};
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot(authReducer, storeModuleConfig),
],
providers: [
provideMockStore({ initialState }),
{ provide: AuthBlockingGuard, useValue: guard }
]
}).compileComponents();
}));
beforeEach(() => {
store = TestBed.inject(Store);
mockStore = store as MockStore<AppState>;
guard = new AuthBlockingGuard(store);
});
describe(`canActivate`, () => {
describe(`when authState.loading is undefined`, () => {
beforeEach(() => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(undefined);
};
})
});
it(`should not emit anything`, () => {
expect(guard.canActivate()).toBeObservable(cold('|'));
describe(`when authState.blocking is undefined`, () => {
it(`should not emit anything`, (done) => {
expect(guard.canActivate()).toBeObservable(cold('-'));
done();
});
});
describe(`when authState.loading is true`, () => {
describe(`when authState.blocking is true`, () => {
beforeEach(() => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(true);
};
})
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'auth': {
blocking: true
}
})
});
mockStore.setState(state);
});
it(`should not emit anything`, () => {
expect(guard.canActivate()).toBeObservable(cold('|'));
it(`should not emit anything`, (done) => {
expect(guard.canActivate()).toBeObservable(cold('-'));
done();
});
});
describe(`when authState.loading is false`, () => {
describe(`when authState.blocking is false`, () => {
beforeEach(() => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(false);
};
})
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'auth': {
blocking: false
}
})
});
mockStore.setState(state);
});
it(`should succeed`, () => {
it(`should succeed`, (done) => {
expect(guard.canActivate()).toBeObservable(cold('(a|)', { a: true }));
done();
});
});
});

View File

@@ -197,7 +197,7 @@ describe('AuthEffects', () => {
expect(authEffects.checkToken$).toBeObservable(expected);
});
})
});
});
describe('checkTokenCookie$', () => {
@@ -240,7 +240,7 @@ describe('AuthEffects', () => {
expect(authEffects.checkTokenCookie$).toBeObservable(expected);
});
})
});
});
describe('retrieveAuthenticatedEperson$', () => {
@@ -296,7 +296,7 @@ describe('AuthEffects', () => {
expect(authEffects.refreshToken$).toBeObservable(expected);
});
})
});
});
describe('retrieveToken$', () => {
@@ -354,7 +354,7 @@ describe('AuthEffects', () => {
expect(authEffects.logOut$).toBeObservable(expected);
});
})
});
});
describe('retrieveMethods$', () => {
@@ -379,7 +379,7 @@ describe('AuthEffects', () => {
expect(authEffects.retrieveMethods$).toBeObservable(expected);
});
})
});
});
describe('clearInvalidTokenOnRehydrate$', () => {

View File

@@ -104,6 +104,6 @@ describe(`AuthInterceptor`, () => {
httpMock.expectNone('dspace-spring-rest/api/submission/workspaceitems');
});
})
});
});

View File

@@ -29,7 +29,7 @@ describe('DSOBreadcrumbResolver', () => {
it('should resolve a breadcrumb config for the correct DSO', () => {
const resolvedConfig = resolver.resolve({ params: { id: uuid } } as any, { url: currentUrl } as any);
const expectedConfig = { provider: dsoBreadcrumbService, key: testCollection, url: breadcrumbUrl };
getTestScheduler().expectObservable(resolvedConfig).toBe('(a|)', { a: expectedConfig})
getTestScheduler().expectObservable(resolvedConfig).toBe('(a|)', { a: expectedConfig});
});
});
});

View File

@@ -85,7 +85,7 @@ describe('DSOBreadcrumbsService', () => {
}
);
dsoNameService = { getName: (dso) => getName(dso) }
dsoNameService = { getName: (dso) => getName(dso) };
}
beforeEach(async(() => {
@@ -113,10 +113,10 @@ describe('DSOBreadcrumbsService', () => {
new Breadcrumb(getName(testItem), getDSORoute(testItem)),
];
getTestScheduler().expectObservable(breadcrumbs).toBe('(a|)', { a: expectedCrumbs });
})
});
});
function getName(dso: DSpaceObject): string {
return dso.metadata['dc.title'][0].value
return dso.metadata['dc.title'][0].value;
}
});

View File

@@ -18,9 +18,9 @@ describe(`DSONameService`, () => {
mockPersonName = 'Doe, John';
mockPerson = Object.assign(new DSpaceObject(), {
firstMetadataValue(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): string {
return mockPersonName
return mockPersonName;
},
getRenderTypes(): Array<string | GenericConstructor<ListableObject>> {
getRenderTypes(): (string | GenericConstructor<ListableObject>)[] {
return ['Person', Item, DSpaceObject];
}
});
@@ -28,9 +28,9 @@ describe(`DSONameService`, () => {
mockOrgUnitName = 'Molecular Spectroscopy';
mockOrgUnit = Object.assign(new DSpaceObject(), {
firstMetadataValue(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): string {
return mockOrgUnitName
return mockOrgUnitName;
},
getRenderTypes(): Array<string | GenericConstructor<ListableObject>> {
getRenderTypes(): (string | GenericConstructor<ListableObject>)[] {
return ['OrgUnit', Item, DSpaceObject];
}
});
@@ -38,9 +38,9 @@ describe(`DSONameService`, () => {
mockDSOName = 'Lorem Ipsum';
mockDSO = Object.assign(new DSpaceObject(), {
firstMetadataValue(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): string {
return mockDSOName
return mockDSOName;
},
getRenderTypes(): Array<string | GenericConstructor<ListableObject>> {
getRenderTypes(): (string | GenericConstructor<ListableObject>)[] {
return [DSpaceObject];
}
});

View File

@@ -38,7 +38,7 @@ describe('I18nBreadcrumbResolver', () => {
it('should resolve throw an error when no breadcrumbKey is defined', () => {
expect(() => {
resolver.resolve({ data: {} } as any, undefined)
resolver.resolve({ data: {} } as any, undefined);
}).toThrow();
});
});

View File

@@ -26,6 +26,6 @@ describe('I18nBreadcrumbsService', () => {
it('should return a breadcrumb based on a string by adding the postfix', () => {
const breadcrumbs = service.getBreadcrumbs(exampleString, exampleURL);
getTestScheduler().expectObservable(breadcrumbs).toBe('(a|)', { a: [new Breadcrumb(exampleString + BREADCRUMB_MESSAGE_POSTFIX, exampleURL)] });
})
});
});
});

View File

@@ -82,7 +82,7 @@ describe('BrowseService', () => {
const getRequestEntry$ = (successful: boolean) => {
return observableOf({
response: { isSuccessful: successful, payload: browseDefinitions } as any
} as RequestEntry)
} as RequestEntry);
};
function initTestService() {
@@ -204,7 +204,7 @@ describe('BrowseService', () => {
it('should throw an Error', () => {
const definitionID = 'invalidID';
const expected = cold('--#-', undefined, new Error(`No metadata browse definition could be found for id '${definitionID}'`))
const expected = cold('--#-', undefined, new Error(`No metadata browse definition could be found for id '${definitionID}'`));
expect(service.getBrowseItemsFor(mockAuthorName, new BrowseEntrySearchOptions(definitionID))).toBeObservable(expected);
});

View File

@@ -17,7 +17,7 @@ class TestHALResource implements HALResource {
foo: HALLink;
};
bar?: any
bar?: any;
}
let testType;

View File

@@ -10,7 +10,7 @@ describe('IDToUUIDSerializer', () => {
describe('Serialize', () => {
it('should return undefined', () => {
expect(serializer.Serialize('some-uuid')).toBeUndefined()
expect(serializer.Serialize('some-uuid')).toBeUndefined();
});
});

View File

@@ -1,9 +1,12 @@
import * as ngrx from '@ngrx/store';
import { Store } from '@ngrx/store';
import { TestBed, waitForAsync } from '@angular/core/testing';
import { Store, StoreModule } from '@ngrx/store';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { Operation } from 'fast-json-patch';
import { of as observableOf } from 'rxjs';
import { first } from 'rxjs/operators';
import { CoreState } from '../core.reducers';
import { coreReducers, CoreState } from '../core.reducers';
import { RestRequestMethod } from '../data/rest-request-method';
import { Item } from '../shared/item.model';
import {
@@ -13,14 +16,16 @@ import {
RemoveFromObjectCacheAction
} from './object-cache.actions';
import { Patch } from './object-cache.reducer';
import { ObjectCacheService } from './object-cache.service';
import { AddToSSBAction } from './server-sync-buffer.actions';
import { storeModuleConfig } from '../../app.reducer';
describe('ObjectCacheService', () => {
let service: ObjectCacheService;
let store: Store<CoreState>;
let mockStore: MockStore<CoreState>;
let linkServiceStub;
let initialState: any;
const selfLink = 'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7';
const requestUUID = '4d3a4ce8-a375-4b98-859b-39f0a014d736';
@@ -48,12 +53,36 @@ describe('ObjectCacheService', () => {
timeAdded: timestamp,
msToLive: msToLive
};
invalidCacheEntry = Object.assign({}, cacheEntry, { msToLive: -1 })
invalidCacheEntry = Object.assign({}, cacheEntry, { msToLive: -1 });
initialState = {
core: {
'cache/object': { },
'cache/syncbuffer': { },
'cache/object-updates': { },
'data/request': { },
'index': { },
}
};
}
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot(coreReducers, storeModuleConfig)
],
providers: [
provideMockStore({ initialState }),
{ provide: ObjectCacheService, useValue: service }
]
}).compileComponents();
}));
beforeEach(() => {
init();
store = new Store<CoreState>(undefined, undefined, undefined);
store = TestBed.inject(Store);
mockStore = store as MockStore<CoreState>;
mockStore.setState(initialState);
linkServiceStub = {
removeResolvedLinks: (a) => a
};
@@ -83,11 +112,14 @@ describe('ObjectCacheService', () => {
describe('getBySelfLink', () => {
it('should return an observable of the cached object with the specified self link and type', () => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(cacheEntry);
};
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'cache/object': {
'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7': cacheEntry
}
})
});
mockStore.setState(state);
// due to the implementation of spyOn above, this subscribe will be synchronous
service.getObjectBySelfLink(selfLink).pipe(first()).subscribe((o) => {
@@ -99,11 +131,14 @@ describe('ObjectCacheService', () => {
});
it('should not return a cached object that has exceeded its time to live', () => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(invalidCacheEntry);
};
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'cache/object': {
'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7': invalidCacheEntry
}
})
});
mockStore.setState(state);
let getObsHasFired = false;
const subscription = service.getObjectBySelfLink(selfLink).subscribe((o) => getObsHasFired = true);
@@ -128,32 +163,38 @@ describe('ObjectCacheService', () => {
describe('has', () => {
it('should return true if the object with the supplied self link is cached and still valid', () => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(cacheEntry);
};
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'cache/object': {
'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7': cacheEntry
}
})
});
mockStore.setState(state);
expect(service.hasBySelfLink(selfLink)).toBe(true);
});
it('should return false if the object with the supplied self link isn\'t cached', () => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(undefined);
};
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'cache/object': {
'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7': undefined
}
})
});
mockStore.setState(state);
expect(service.hasBySelfLink(selfLink)).toBe(false);
});
it('should return false if the object with the supplied self link is cached but has exceeded its time to live', () => {
spyOnProperty(ngrx, 'select').and.callFake(() => {
return () => {
return () => observableOf(invalidCacheEntry);
};
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'cache/object': {
'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7': invalidCacheEntry
}
})
});
expect(service.hasBySelfLink(selfLink)).toBe(false);
});
});

View File

@@ -1,26 +1,26 @@
import { TestBed } from '@angular/core/testing';
import { provideMockActions } from '@ngrx/effects/testing';
import { Store, StoreModule } from '@ngrx/store';
import { cold, hot } from 'jasmine-marbles';
import { Observable, of as observableOf } from 'rxjs';
import * as operators from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { getMockRequestService } from '../../shared/mocks/request.service.mock';
import { StoreMock } from '../../shared/testing/store.mock';
import { spyOnOperator } from '../../shared/testing/utils.test';
import { RequestService } from '../data/request.service';
import { RestRequestMethod } from '../data/rest-request-method';
import { DSpaceObject } from '../shared/dspace-object.model';
import { ApplyPatchObjectCacheAction } from './object-cache.actions';
import { ObjectCacheService } from './object-cache.service';
import { CommitSSBAction, EmptySSBAction, ServerSyncBufferActionTypes } from './server-sync-buffer.actions';
import { ServerSyncBufferEffects } from './server-sync-buffer.effects';
import { storeModuleConfig } from '../../app.reducer';
describe('ServerSyncBufferEffects', () => {
let ssbEffects: ServerSyncBufferEffects;
let actions: Observable<any>;
let testScheduler: TestScheduler;
const testConfig = {
cache:
{
@@ -72,20 +72,25 @@ describe('ServerSyncBufferEffects', () => {
describe('setTimeoutForServerSync', () => {
beforeEach(() => {
spyOnOperator(operators, 'delay').and.returnValue((v) => v);
testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
});
it('should return a COMMIT action in response to an ADD action', () => {
actions = hot('a', {
a: {
type: ServerSyncBufferActionTypes.ADD,
payload: { href: selfLink, method: RestRequestMethod.PUT }
}
// tslint:disable-next-line:no-shadowed-variable
testScheduler.run(({ hot, expectObservable }) => {
actions = hot('a', {
a: {
type: ServerSyncBufferActionTypes.ADD,
payload: { href: selfLink, method: RestRequestMethod.PUT }
}
});
expectObservable(ssbEffects.setTimeoutForServerSync).toBe('b', {
b: new CommitSSBAction(RestRequestMethod.PUT)
});
});
const expected = cold('b', { b: new CommitSSBAction(RestRequestMethod.PUT) });
expect(ssbEffects.setTimeoutForServerSync).toBeObservable(expected);
});
});

View File

@@ -81,5 +81,5 @@ describe('serverSyncBufferReducer', () => {
href: newSelfLink, method: RestRequestMethod.PUT
})
;
})
});
});

View File

@@ -42,7 +42,7 @@ describe('BaseResponseParsingService', () => {
describe('cache', () => {
describe('when the object is undefined', () => {
it('should not throw an error', () => {
expect(() => { service.cache(obj, request, {}) }).not.toThrow();
expect(() => { service.cache(obj, request, {}); }).not.toThrow();
});
it('should not call objectCache add', () => {
@@ -82,7 +82,7 @@ describe('BaseResponseParsingService', () => {
});
it('should not throw an error', () => {
expect(() => { result = service.process(data, request) }).not.toThrow();
expect(() => { result = service.process(data, request); }).not.toThrow();
});
it('should return undefined', () => {

View File

@@ -79,6 +79,6 @@ describe('BundleDataService', () => {
it('should call findAllByHref with the item\'s bundles link', () => {
expect(service.findAllByHref).toHaveBeenCalledWith(bundleLink, undefined);
})
});
});
});

View File

@@ -95,7 +95,7 @@ describe('DataService', () => {
beforeEach(() => {
service = initTestService();
})
});
describe('getFindAllHref', () => {
@@ -146,7 +146,7 @@ describe('DataService', () => {
});
it('should include all provided options in href', () => {
const sortOptions = new SortOptions('field1', SortDirection.DESC)
const sortOptions = new SortOptions('field1', SortDirection.DESC);
options = {
currentPage: 6,
elementsPerPage: 10,

View File

@@ -53,7 +53,7 @@ describe('DSpaceObjectDataService', () => {
notificationsService,
http,
comparator
)
);
});
describe('findById', () => {

View File

@@ -31,6 +31,6 @@ describe('FilteredDiscoveryPageResponseParsingService', () => {
it('should return a FilteredDiscoveryQueryResponse containing the correct query', () => {
const response = service.parse(request, mockResponse);
expect((response as FilteredDiscoveryQueryResponse).filterQuery).toBe(mockResponse.payload['discovery-query']);
})
});
});
});

View File

@@ -51,7 +51,7 @@ describe('ItemTemplateDataService', () => {
const bs = {} as BrowseService;
const objectCache = {
getObjectBySelfLink(self) {
return observableOf({})
return observableOf({});
},
addPatch(self, operations) {
// Do nothing

View File

@@ -86,13 +86,13 @@ describe('LookupRelationService', () => {
it('should start with 0', () => {
result.pipe(take(1)).subscribe((amount) => {
expect(amount).toEqual(0)
expect(amount).toEqual(0);
});
});
it('should return the correct total amount', () => {
result.pipe(skip(1)).subscribe((amount) => {
expect(amount).toEqual(localResults.length)
expect(amount).toEqual(localResults.length);
});
});
@@ -110,13 +110,13 @@ describe('LookupRelationService', () => {
it('should start with 0', () => {
result.pipe(take(1)).subscribe((amount) => {
expect(amount).toEqual(0)
expect(amount).toEqual(0);
});
});
it('should return the correct total amount', () => {
result.pipe(skip(1)).subscribe((amount) => {
expect(amount).toEqual(totalExternal)
expect(amount).toEqual(totalExternal);
});
});
});

View File

@@ -77,7 +77,7 @@ describe('ObjectUpdatesEffects', () => {
beforeEach(() => {
infoNotification = new Notification('id', NotificationType.Info, 'info');
infoNotification.options.timeOut = 0;
removeAction = new RemoveObjectUpdatesAction(testURL)
removeAction = new RemoveObjectUpdatesAction(testURL);
});
it('should return a RemoveObjectUpdatesAction', () => {
actions = hot('a|', { a: new DiscardObjectUpdatesAction(testURL, infoNotification) });

View File

@@ -219,7 +219,7 @@ describe('ObjectUpdatesService', () => {
});
describe('when updates are emtpy', () => {
beforeEach(() => {
(service as any).getObjectEntry.and.returnValue(observableOf({}))
(service as any).getObjectEntry.and.returnValue(observableOf({}));
});
it('should return false when there are no updates', () => {

View File

@@ -100,7 +100,7 @@ describe('RelationshipTypeService', () => {
expected.subscribe((e) => {
expect(e).toBe(buildList);
done();
})
});
});
});
@@ -111,7 +111,7 @@ describe('RelationshipTypeService', () => {
expected.subscribe((e) => {
expect(e).toBe(relationshipType1);
done();
})
});
});
});

View File

@@ -77,7 +77,7 @@ describe('requestReducer', () => {
expect(newState[id1].requestPending).toEqual(false);
expect(newState[id1].responsePending).toEqual(true);
expect(newState[id1].completed).toEqual(state[id1].completed);
expect(newState[id1].response).toEqual(undefined)
expect(newState[id1].response).toEqual(undefined);
});
it('should leave \'requestPending\' untouched, set \'responsePending\' to false and \'completed\' to true for the given RestRequest in the state, in response to a COMPLETE action', () => {
@@ -93,7 +93,7 @@ describe('requestReducer', () => {
expect(newState[id1].completed).toEqual(true);
expect(newState[id1].response.isSuccessful).toEqual(response.isSuccessful);
expect(newState[id1].response.statusCode).toEqual(response.statusCode);
expect(newState[id1].response.timeAdded).toBeTruthy()
expect(newState[id1].response.timeAdded).toBeTruthy();
});
it('should leave \'requestPending\' untouched, should leave \'responsePending\' untouched and leave \'completed\' untouched, but update the response\'s timeAdded for the given RestRequest in the state, in response to a COMPLETE action', () => {

View File

@@ -1,13 +1,12 @@
import * as ngrx from '@ngrx/store';
import { ActionsSubject, Store } from '@ngrx/store';
import { cold, getTestScheduler, hot } from 'jasmine-marbles';
import { BehaviorSubject, EMPTY, of as observableOf } from 'rxjs';
import { Store, StoreModule } from '@ngrx/store';
import { cold, getTestScheduler } from 'jasmine-marbles';
import { EMPTY, of as observableOf } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
import { getMockObjectCacheService } from '../../shared/mocks/object-cache.service.mock';
import { defaultUUID, getMockUUIDService } from '../../shared/mocks/uuid.service.mock';
import { ObjectCacheService } from '../cache/object-cache.service';
import { CoreState } from '../core.reducers';
import { coreReducers, CoreState } from '../core.reducers';
import { UUIDService } from '../shared/uuid.service';
import { RequestConfigureAction, RequestExecuteAction } from './request.actions';
import {
@@ -22,7 +21,9 @@ import {
} from './request.models';
import { RequestEntry } from './request.reducer';
import { RequestService } from './request.service';
import { parseJsonSchemaToCommandDescription } from '@angular/cli/utilities/json-schema';
import { TestBed, waitForAsync } from '@angular/core/testing';
import { storeModuleConfig } from '../../app.reducer';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
describe('RequestService', () => {
let scheduler: TestScheduler;
@@ -31,6 +32,7 @@ describe('RequestService', () => {
let objectCache: ObjectCacheService;
let uuidService: UUIDService;
let store: Store<CoreState>;
let mockStore: MockStore<CoreState>;
const testUUID = '5f2a0d2a-effa-4d54-bd54-5663b960f9eb';
const testHref = 'https://rest.api/endpoint/selfLink';
@@ -41,7 +43,29 @@ describe('RequestService', () => {
const testOptionsRequest = new OptionsRequest(testUUID, testHref);
const testHeadRequest = new HeadRequest(testUUID, testHref);
const testPatchRequest = new PatchRequest(testUUID, testHref);
let selectSpy;
const initialState: any = {
core: {
'cache/object': { },
'cache/syncbuffer': { },
'cache/object-updates': { },
'data/request': { },
'index': { },
}
};
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot(coreReducers, storeModuleConfig)
],
providers: [
provideMockStore({ initialState }),
{ provide: RequestService, useValue: service }
]
}).compileComponents();
}));
beforeEach(() => {
scheduler = getTestScheduler();
@@ -51,14 +75,9 @@ describe('RequestService', () => {
uuidService = getMockUUIDService();
store = new Store<CoreState>(new BehaviorSubject({}), new ActionsSubject(), null);
selectSpy = spyOnProperty(ngrx, 'select');
selectSpy.and.callFake(() => {
return () => {
return () => cold('a', { a: undefined });
};
});
store = TestBed.inject(Store);
mockStore = store as MockStore<CoreState>;
mockStore.setState(initialState);
service = new RequestService(
objectCache,
uuidService,
@@ -109,7 +128,7 @@ describe('RequestService', () => {
beforeEach(() => {
spyOn(service, 'getByHref').and.returnValue(observableOf({
completed: false
} as RequestEntry))
} as RequestEntry));
});
it('should return true', () => {
@@ -140,23 +159,21 @@ describe('RequestService', () => {
describe('getByUUID', () => {
describe('if the request with the specified UUID exists in the store', () => {
beforeEach(() => {
let callCounter = 0;
const responses = [
cold('a', { // A direct hit in the request cache
a: {
completed: true
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'data/request': {
'5f2a0d2a-effa-4d54-bd54-5663b960f9eb': {
completed: true
}
},
'index': {
'get-request/configured-to-cache-uuid': {
'5f2a0d2a-effa-4d54-bd54-5663b960f9eb': '5f2a0d2a-effa-4d54-bd54-5663b960f9eb'
}
}
}),
cold('b', { b: undefined }), // No hit in the index
cold('c', { c: undefined }) // So no mapped hit in the request cache
];
selectSpy.and.callFake(() => {
return () => {
const response = responses[callCounter];
callCounter++;
return () => response;
};
})
});
mockStore.setState(state);
});
it('should return an Observable of the RequestEntry', () => {
@@ -173,57 +190,53 @@ describe('RequestService', () => {
describe(`if the request with the specified UUID doesn't exist in the store `, () => {
beforeEach(() => {
let callCounter = 0;
const responses = [
cold('a', { a: undefined }), // No direct hit in the request cache
cold('b', { b: undefined }), // No hit in the index
cold('c', { c: undefined }), // So no mapped hit in the request cache
];
selectSpy.and.callFake(() => {
return () => {
const response = responses[callCounter];
callCounter++;
return () => response;
};
});
// No direct hit in the request cache
// No hit in the index
// So no mapped hit in the request cache
mockStore.setState(initialState);
});
it('should return an Observable of undefined', () => {
const result = service.getByUUID(testUUID);
scheduler.expectObservable(result).toBe('a', { a: undefined });
const expected = cold('b', {
b: undefined
});
expect(result).toBeObservable(expected);
});
});
describe(`if the request with the specified UUID wasn't sent, because it was already cached`, () => {
beforeEach(() => {
let callCounter = 0;
const responses = [
cold('a', { a: undefined }), // No direct hit in the request cache with that UUID
cold('b', { b: 'otherRequestUUID' }), // A hit in the index, which returns the uuid of the cached request
cold('c', { // the call to retrieve the cached request using the UUID from the index
c: {
completed: true
// No direct hit in the request cache with that UUID
// A hit in the index, which returns the uuid of the cached request
// the call to retrieve the cached request using the UUID from the index
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'data/request': {
'otherRequestUUID': {
completed: true
}
},
'index': {
'get-request/configured-to-cache-uuid': {
'5f2a0d2a-effa-4d54-bd54-5663b960f9eb': 'otherRequestUUID'
}
}
})
];
selectSpy.and.callFake(() => {
return () => {
const response = responses[callCounter];
callCounter++;
return () => response;
};
});
mockStore.setState(state);
});
it(`it should return the cached request`, () => {
const result = service.getByUUID(testUUID);
scheduler.expectObservable(result).toBe('c', {
c: {
const expected = cold('b', {
b: {
completed: true
}
});
expect(result).toBeObservable(expected);
});
});
@@ -232,16 +245,24 @@ describe('RequestService', () => {
describe('getByHref', () => {
describe('when the request with the specified href exists in the store', () => {
beforeEach(() => {
selectSpy.and.callFake(() => {
return () => {
return () => hot('a', { a: testUUID });
};
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'data/request': {
'5f2a0d2a-effa-4d54-bd54-5663b960f9eb': {
completed: true
}
},
'index': {
'get-request/configured-to-cache-uuid': {
'5f2a0d2a-effa-4d54-bd54-5663b960f9eb': '5f2a0d2a-effa-4d54-bd54-5663b960f9eb'
},
'get-request/href-to-uuid': {
'https://rest.api/endpoint/selfLink': '5f2a0d2a-effa-4d54-bd54-5663b960f9eb'
}
}
})
});
spyOn(service, 'getByUUID').and.returnValue(cold('b', {
b: {
completed: true
}
}));
mockStore.setState(state);
});
it('should return an Observable of the RequestEntry', () => {
@@ -258,14 +279,10 @@ describe('RequestService', () => {
describe('when the request with the specified href doesn\'t exist in the store', () => {
beforeEach(() => {
selectSpy.and.callFake(() => {
return () => {
return () => hot('a', { a: undefined });
};
});
spyOn(service, 'getByUUID').and.returnValue(cold('b', {
b: undefined
}));
// No direct hit in the request cache
// No hit in the index
// So no mapped hit in the request cache
mockStore.setState(initialState);
});
it('should return an Observable of undefined', () => {
@@ -455,11 +472,7 @@ describe('RequestService', () => {
describe('when the request is added to the store', () => {
it('should stop tracking the request', () => {
selectSpy.and.callFake(() => {
return () => {
return () => observableOf({ request });
};
});
spyOn(serviceAsAny, 'getByHref').and.returnValue(observableOf({ request }));
serviceAsAny.trackRequestsOnTheirWayToTheStore(request);
expect(serviceAsAny.requestsOnTheirWayToTheStore.includes(request.href)).toBeFalsy();
});
@@ -475,7 +488,7 @@ describe('RequestService', () => {
});
it('return an observable emitting false', () => {
expect(valid).toBe(false);
})
});
});
describe('when the given entry has a value, but the request is not completed', () => {
@@ -487,7 +500,7 @@ describe('RequestService', () => {
});
it('return an observable emitting false', () => {
expect(valid).toBe(false);
})
});
});
describe('when the given entry has a value, but the response is not successful', () => {
@@ -499,7 +512,7 @@ describe('RequestService', () => {
});
it('return an observable emitting false', () => {
expect(valid).toBe(false);
})
});
});
describe('when the given UUID has a value, its response was successful, but the response is outdated', () => {
@@ -526,7 +539,7 @@ describe('RequestService', () => {
it('return an observable emitting false', () => {
expect(valid).toBe(false);
})
});
});
describe('when the given UUID has a value, a cached entry is found, its response was successful, and the response is not outdated', () => {
@@ -553,8 +566,8 @@ describe('RequestService', () => {
it('return an observable emitting true', () => {
expect(valid).toBe(true);
})
})
});
});
});
describe('hasByHref', () => {

View File

@@ -14,7 +14,7 @@ class TestModel implements HALResource {
_links: {
self: HALLink;
parents: HALLink;
}
};
}
const testModels = [

View File

@@ -65,7 +65,7 @@ describe('EPersonDataService', () => {
return observableOf({
completed: true,
response: { isSuccessful: successful, payload: epeople } as any
} as RequestEntry)
} as RequestEntry);
};
restEndpointURL = 'https://dspace.4science.it/dspace-spring-rest/api/eperson';
epersonsEndpoint = `${restEndpointURL}/epersons`;
@@ -257,14 +257,14 @@ describe('EPersonDataService', () => {
service.getActiveEPerson().subscribe((activeEPerson: EPerson) => {
expect(activeEPerson).toEqual(EPersonMock);
})
});
});
it('should retrieve the ePerson currently getting edited, null if none being edited', () => {
service.getActiveEPerson().subscribe((activeEPerson: EPerson) => {
expect(activeEPerson).toEqual(null);
})
})
});
});
});
describe('cancelEditEPerson', () => {

View File

@@ -48,7 +48,7 @@ describe('GroupDataService', () => {
return observableOf({
completed: true,
response: { isSuccessful: successful, payload: groups } as any
} as RequestEntry)
} as RequestEntry);
};
restEndpointURL = 'https://dspace.4science.it/dspace-spring-rest/api/eperson';
groupsEndpoint = `${restEndpointURL}/groups`;
@@ -85,7 +85,7 @@ describe('GroupDataService', () => {
halService,
null,
);
};
}
beforeEach(() => {
init();

View File

@@ -83,7 +83,7 @@ describe('JsonPatchOperationsService test suite', () => {
const getRequestEntry$ = (successful: boolean) => {
return observableOf({
response: { isSuccessful: successful, timeAdded: timestampResponse } as any
} as RequestEntry)
} as RequestEntry);
};
function initTestService(): TestService {

View File

@@ -18,7 +18,7 @@ describe(`LocaleInterceptor`, () => {
const mockLocaleService = jasmine.createSpyObj('LocaleService', {
getCurrentLanguageCode: jasmine.createSpy('getCurrentLanguageCode'),
getLanguageCodeList: of(languageList)
})
});
beforeEach(() => {
TestBed.configureTestingModule({
@@ -38,7 +38,7 @@ describe(`LocaleInterceptor`, () => {
httpMock = TestBed.inject(HttpTestingController);
localeService = TestBed.inject(LocaleService);
localeService.getCurrentLanguageCode.and.returnValue('en')
localeService.getCurrentLanguageCode.and.returnValue('en');
});
describe('', () => {

View File

@@ -21,7 +21,7 @@ export class LocaleInterceptor implements HttpInterceptor {
let newReq: HttpRequest<any>;
return this.localeService.getLanguageCodeList()
.pipe(
scan((acc: any, value: any) => [...acc, ...value], []),
scan((acc: any, value: any) => [...acc, value], []),
mergeMap((languages) => {
// Clone the request to add the new header.
newReq = req.clone({
@@ -30,6 +30,6 @@ export class LocaleInterceptor implements HttpInterceptor {
});
// Pass on the new request instead of the original request.
return next.handle(newReq);
}))
}));
}
}

View File

@@ -1,13 +1,12 @@
import { async, TestBed } from '@angular/core/testing';
import { TestBed, waitForAsync } from '@angular/core/testing';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { CookieService } from '../services/cookie.service';
import { CookieServiceMock } from '../../shared/mocks/cookie.service.mock';
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
import { LANG_COOKIE, LocaleService, LANG_ORIGIN } from './locale.service';
import { LANG_COOKIE, LANG_ORIGIN, LocaleService } from './locale.service';
import { AuthService } from '../auth/auth.service';
import { AuthServiceMock } from 'src/app/shared/mocks/auth.service.mock';
import { NativeWindowRef } from '../services/window.service';
describe('LocaleService test suite', () => {
@@ -15,14 +14,19 @@ describe('LocaleService test suite', () => {
let serviceAsAny: any;
let cookieService: CookieService;
let translateService: TranslateService;
let authService: AuthService;
let window;
let spyOnGet;
let spyOnSet;
let authService;
authService = jasmine.createSpyObj('AuthService', {
isAuthenticated: jasmine.createSpy('isAuthenticated'),
isAuthenticationLoaded: jasmine.createSpy('isAuthenticationLoaded')
});
const langList = ['en', 'it', 'de'];
beforeEach(async(() => {
beforeEach(waitForAsync(() => {
return TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
@@ -34,7 +38,7 @@ describe('LocaleService test suite', () => {
],
providers: [
{ provide: CookieService, useValue: new CookieServiceMock() },
{ provide: AuthService, userValue: AuthServiceMock }
{ provide: AuthService, userValue: authService }
]
});
}));
@@ -42,7 +46,6 @@ describe('LocaleService test suite', () => {
beforeEach(() => {
cookieService = TestBed.inject(CookieService);
translateService = TestBed.inject(TranslateService);
authService = TestBed.inject(AuthService);
window = new NativeWindowRef();
service = new LocaleService(window, cookieService, translateService, authService);
serviceAsAny = service;

View File

@@ -108,7 +108,7 @@ describe('MetadataService', () => {
requestService = new RequestService(objectCacheService, uuidService, store, undefined);
remoteDataBuildService = new RemoteDataBuildService(objectCacheService, undefined, requestService);
const mockBitstreamDataService = {
findAllByItemAndBundleName(item: Item, bundleName: string, options?: FindListOptions, ...linksToFollow: Array<FollowLinkConfig<Bitstream>>): Observable<RemoteData<PaginatedList<Bitstream>>> {
findAllByItemAndBundleName(item: Item, bundleName: string, options?: FindListOptions, ...linksToFollow: FollowLinkConfig<Bitstream>[]): Observable<RemoteData<PaginatedList<Bitstream>>> {
if (item.equals(ItemMock)) {
return createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [MockBitstream1, MockBitstream2]));
} else {
@@ -271,6 +271,6 @@ describe('MetadataService', () => {
}
] as MetadataValue[];
return publishedMockItem;
}
};
});

View File

@@ -30,7 +30,7 @@ describe('BrowserHardRedirectService', () => {
it('should update the location', () => {
expect(mockLocation.href).toEqual(redirect);
})
});
});
describe('when requesting the current route', () => {

View File

@@ -1,6 +1,6 @@
import { CookieService, ICookieService } from './cookie.service'
import { async, TestBed } from '@angular/core/testing'
import { REQUEST } from '@nguniversal/express-engine/tokens'
import { CookieService, ICookieService } from './cookie.service';
import { async, TestBed } from '@angular/core/testing';
import { REQUEST } from '@nguniversal/express-engine/tokens';
describe(CookieService.name, () => {
let service: ICookieService;
@@ -11,18 +11,18 @@ describe(CookieService.name, () => {
CookieService,
{provide: REQUEST, useValue: {}}
]
})
});
}));
beforeEach(() => {
service = TestBed.inject(CookieService)
service = TestBed.inject(CookieService);
});
afterEach(() => {
TestBed.resetTestingModule()
TestBed.resetTestingModule();
});
it('should construct', async(() => {
expect(service).toBeDefined()
}))
expect(service).toBeDefined();
}));
});

View File

@@ -33,7 +33,7 @@ describe('HardRedirectService', () => {
afterEach(() => {
environment.rewriteDownloadUrls = originalValue;
})
});
});
});

View File

@@ -150,7 +150,7 @@ describe('RouteService', () => {
service.getHistory().subscribe((history) => {
expect(history).toEqual(['url', 'newurl']);
})
})
})
});
});
});
});

View File

@@ -32,7 +32,7 @@ describe('ServerHardRedirectService', () => {
it('should update the response object', () => {
expect(mockResponse.redirect).toHaveBeenCalledWith(302, redirect);
expect(mockResponse.end).toHaveBeenCalled();
})
});
});
describe('when requesting the current route', () => {

View File

@@ -102,7 +102,7 @@ describe('HALEndpointService', () => {
describe('getEndpointAt', () => {
it('should throw an error when the list of hal endpoint names is empty', () => {
const endpointAtWithoutEndpointNames = () => {
(service as any).getEndpointAt('')
(service as any).getEndpointAt('');
};
expect(endpointAtWithoutEndpointNames).toThrow();
});

View File

@@ -56,7 +56,7 @@ const testMethod = (fn, resultKind, mapOrMaps, keyOrKeys, expected, filter?) =>
it('should return ' + shouldReturn, () => {
expect(result).toEqual(expected);
});
})
});
};
describe('Metadata', () => {

View File

@@ -178,7 +178,7 @@ describe('Core Module - RxJS Operators', () => {
e: testRCEs.e.response
});
expect(result).toBeObservable(expected)
expect(result).toBeObservable(expected);
});
});
@@ -247,7 +247,7 @@ describe('Core Module - RxJS Operators', () => {
e: testRCEs.e.response
});
expect(result).toBeObservable(expected)
expect(result).toBeObservable(expected);
});
});

View File

@@ -130,7 +130,7 @@ describe('SearchConfigurationService', () => {
describe('when subscribeToSearchOptions is called', () => {
beforeEach(() => {
(service as any).subscribeToSearchOptions(defaults)
(service as any).subscribeToSearchOptions(defaults);
});
it('should call all getters it needs, but not call any others', () => {
expect(service.getCurrentPagination).not.toHaveBeenCalled();

Some files were not shown because too many files have changed in this diff Show More