[ACS-7365] Optimise Search providers and unit tests (#9477)

refactor: optimise node selector imports and tests
This commit is contained in:
Denys Vuika
2024-03-27 08:19:37 -04:00
committed by GitHub
parent 77d9e7d6aa
commit f66342df2f
142 changed files with 1612 additions and 2188 deletions
@@ -18,7 +18,6 @@
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AspectListDialogComponent } from './aspect-list-dialog.component';
import { TranslateModule } from '@ngx-translate/core';
import { of, Subject } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module';
import { AspectListDialogComponentData } from './aspect-list-dialog-data.interface';
@@ -114,7 +113,7 @@ describe('AspectListDialogComponent', () => {
excludedAspects: []
};
await TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule, MatDialogModule],
imports: [ContentTestingModule, MatDialogModule],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: data },
{
@@ -310,8 +309,7 @@ describe('AspectListDialogComponent', () => {
data.excludedAspects = ['some aspect 1', 'some aspect 2'];
fixture.detectChanges();
expect(fixture.debugElement.query(By.directive(AspectListComponent)).componentInstance.excludedAspects)
.toBe(data.excludedAspects);
expect(fixture.debugElement.query(By.directive(AspectListComponent)).componentInstance.excludedAspects).toBe(data.excludedAspects);
});
});
});
@@ -18,7 +18,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NodesApiService } from '../common/services/nodes-api.service';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AspectListComponent } from './aspect-list.component';
import { AspectListService } from './services/aspect-list.service';
import { EMPTY, of } from 'rxjs';
@@ -120,7 +119,7 @@ describe('AspectListComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
providers: [AspectListService]
});
});
@@ -176,8 +175,8 @@ describe('AspectListComponent', () => {
});
it('should show all the aspects', async () => {
expect(await loader.hasHarness(MatExpansionPanelHarness.with({selector: '#aspect-list-FirstAspect'}))).toBe(true);
expect(await loader.hasHarness(MatExpansionPanelHarness.with({selector: '#aspect-list-SecondAspect'}))).toBe(true);
expect(await loader.hasHarness(MatExpansionPanelHarness.with({ selector: '#aspect-list-FirstAspect' }))).toBe(true);
expect(await loader.hasHarness(MatExpansionPanelHarness.with({ selector: '#aspect-list-SecondAspect' }))).toBe(true);
});
it('should show aspect id when name or title is not set', () => {
@@ -259,8 +258,7 @@ describe('AspectListComponent', () => {
component.excludedAspects = ['cst:nonamedAspect'];
fixture.detectChanges();
expect(fixture.nativeElement.querySelector(`#aspect-list-${component.excludedAspects[0].replace(':', '-')}`))
.toBeNull();
expect(fixture.nativeElement.querySelector(`#aspect-list-${component.excludedAspects[0].replace(':', '-')}`)).toBeNull();
});
});
});
@@ -15,7 +15,6 @@
* limitations under the License.
*/
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { DialogAspectListService } from './dialog-aspect-list.service';
import { AspectListDialogComponent } from '../aspect-list-dialog.component';
@@ -32,10 +31,7 @@ describe('DialogAspectListService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
dialogAspectListService = TestBed.inject(DialogAspectListService);
dialog = TestBed.inject(MatDialog);
@@ -17,7 +17,6 @@
import { Node } from '@alfresco/js-api';
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { NodesApiService } from '../../common/services/nodes-api.service';
import { EMPTY, of } from 'rxjs';
import { ContentTestingModule } from '../../testing/content.testing.module';
@@ -34,7 +33,7 @@ describe('NodeAspectService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
dialogAspectListService = TestBed.inject(DialogAspectListService);
nodeAspectService = TestBed.inject(NodeAspectService);
@@ -74,7 +73,7 @@ describe('NodeAspectService', () => {
it('should send and update node event once the node has been updated', () => {
let lastValue: Node;
nodeApiService.nodeUpdated.subscribe((nodeUpdated) => lastValue = nodeUpdated);
nodeApiService.nodeUpdated.subscribe((nodeUpdated) => (lastValue = nodeUpdated));
const fakeNode = new Node({ id: 'fake-node-id', aspectNames: ['a', 'b', 'c'] });
spyOn(dialogAspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c']));
spyOn(nodeApiService, 'updateNode').and.returnValue(of(fakeNode));
@@ -86,7 +85,7 @@ describe('NodeAspectService', () => {
it('should send and update node aspect once the node has been updated', () => {
let lastValue: Node;
cardViewContentUpdateService.updatedAspect$.subscribe((nodeUpdated) => lastValue = nodeUpdated);
cardViewContentUpdateService.updatedAspect$.subscribe((nodeUpdated) => (lastValue = nodeUpdated));
const fakeNode = new Node({ id: 'fake-node-id', aspectNames: ['a', 'b', 'c'] });
spyOn(dialogAspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c']));
spyOn(nodeApiService, 'updateNode').and.returnValue(of(fakeNode));
@@ -23,26 +23,21 @@ import { DocumentListComponent, DocumentListService } from '../document-list';
import { BreadcrumbComponent } from './breadcrumb.component';
import { ContentTestingModule } from '../testing/content.testing.module';
import { of } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
describe('Breadcrumb', () => {
let component: BreadcrumbComponent;
let fixture: ComponentFixture<BreadcrumbComponent>;
let documentListService: DocumentListService = jasmine.createSpyObj({
loadFolderByNodeId : of(''),
loadFolderByNodeId: of(''),
isCustomSourceService: false
});
let documentListComponent: DocumentListComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers : [{ provide: DocumentListService, useValue: documentListService }]
providers: [{ provide: DocumentListService, useValue: documentListService }]
});
fixture = TestBed.createComponent(BreadcrumbComponent);
component = fixture.componentInstance;
@@ -80,7 +75,6 @@ describe('Breadcrumb', () => {
});
describe('target', () => {
let folderNode: Node;
beforeEach(() => {
@@ -115,11 +109,13 @@ describe('Breadcrumb', () => {
component.onRoutePathClick(node, null);
expect(documentListService.loadFolderByNodeId).toHaveBeenCalledWith(node.id,
expect(documentListService.loadFolderByNodeId).toHaveBeenCalledWith(
node.id,
documentListComponent.DEFAULT_PAGINATION,
documentListComponent.includeFields,
documentListComponent.where,
documentListComponent.orderBy);
documentListComponent.orderBy
);
});
it('should build the path based on the document list node', () => {
@@ -186,9 +182,7 @@ describe('Breadcrumb', () => {
id: 'test-id',
name: 'test-name',
path: {
elements: [
{ id: 'element-id', name: 'element-name' }
]
elements: [{ id: 'element-id', name: 'element-name' }]
}
};
const route = component.parseRoute(node);
@@ -295,11 +289,11 @@ describe('Breadcrumb', () => {
]
}
};
component.transform = ((transformNode) => {
component.transform = (transformNode) => {
transformNode.id = 'test-id';
transformNode.name = 'test-name';
return transformNode;
});
};
component.folderNode = node;
component.ngOnChanges();
expect(component.route.length).toBe(4);
@@ -23,7 +23,6 @@ import { DocumentListComponent, DocumentListService } from '../document-list';
import { DropdownBreadcrumbComponent } from './dropdown-breadcrumb.component';
import { ContentTestingModule } from '../testing/content.testing.module';
import { of } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
describe('DropdownBreadcrumb', () => {
let component: DropdownBreadcrumbComponent;
@@ -33,7 +32,7 @@ describe('DropdownBreadcrumb', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [{ provide: DocumentListService, useValue: documentListService }]
});
@@ -21,7 +21,6 @@ import { Validators } from '@angular/forms';
import { MatError } from '@angular/material/form-field';
import { MatList } from '@angular/material/list';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { of, Subject } from 'rxjs';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { CategoriesManagementMode } from './categories-management-mode';
@@ -49,7 +48,7 @@ describe('CategoriesManagementComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [CategoriesManagementComponent],
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
providers: [
{
provide: CategoryService,
@@ -384,7 +383,7 @@ describe('CategoriesManagementComponent', () => {
flush();
}));
it ('should disable existing categories list if category already selected and multiSelect is false', fakeAsync(() => {
it('should disable existing categories list if category already selected and multiSelect is false', fakeAsync(() => {
component.multiSelect = false;
fixture.detectChanges();
typeCategory('test');
@@ -19,20 +19,15 @@ import { TestBed } from '@angular/core/testing';
import { ContentService } from './content.service';
import { AppConfigService, AuthenticationService, StorageService, CoreTestingModule } from '@alfresco/adf-core';
import { Node, PermissionsInfo } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core';
describe('ContentService', () => {
let contentService: ContentService;
let authService: AuthenticationService;
let storage: StorageService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
]
imports: [CoreTestingModule]
});
authService = TestBed.inject(AuthenticationService);
contentService = TestBed.inject(ContentService);
@@ -47,7 +42,6 @@ describe('ContentService', () => {
});
describe('AllowableOperations', () => {
it('should hasAllowableOperations be false if allowableOperation is not present in the node', () => {
const permissionNode = new Node({});
expect(contentService.hasAllowableOperations(permissionNode, 'create')).toBeFalsy();
@@ -59,7 +53,7 @@ describe('ContentService', () => {
expect(contentService.hasAllowableOperations(permissionNode, 'create')).toBeTruthy();
});
it('should hasAllowableOperations be false if allowableOperation is present but you don\'t have the permission for the request operation', () => {
it('should hasAllowableOperations be false if allowableOperation is present but you do not have the permission for the request operation', () => {
const permissionNode = new Node({ allowableOperations: ['delete', 'update', 'updatePermissions'] });
expect(contentService.hasAllowableOperations(permissionNode, 'create')).toBeFalsy();
});
@@ -81,30 +75,58 @@ describe('ContentService', () => {
});
describe('Permissions', () => {
it('should havePermission be false if allowableOperation is not present in the node', () => {
const permissionNode = new Node({});
expect(contentService.hasPermissions(permissionNode, 'manager')).toBeFalsy();
});
it('should havePermission be true if permissions is present and you have the permission for the request operation', () => {
const permissionNode = new Node({ permissions: { locallySet: [{ name: 'manager', authorityId: 'user1' }, { name: 'collaborator', authorityId: 'user2' }, { name: 'consumer', authorityId: 'user3' }] } });
const permissionNode = new Node({
permissions: {
locallySet: [
{ name: 'manager', authorityId: 'user1' },
{ name: 'collaborator', authorityId: 'user2' },
{ name: 'consumer', authorityId: 'user3' }
]
}
});
expect(contentService.hasPermissions(permissionNode, 'manager', 'user1')).toBeTruthy();
});
it('should havePermission be false if permissions is present but you don\'t have the permission for the request operation', () => {
const permissionNode = new Node({ permissions: { locallySet: [{ name: 'collaborator', authorityId: 'user1' }, { name: 'consumer', authorityId: 'user2' }] } });
it('should havePermission be false if permissions is present but you do not have the permission for the request operation', () => {
const permissionNode = new Node({
permissions: {
locallySet: [
{ name: 'collaborator', authorityId: 'user1' },
{ name: 'consumer', authorityId: 'user2' }
]
}
});
expect(contentService.hasPermissions(permissionNode, 'manager', 'user1')).toBeFalsy();
});
it('should havePermission works in the opposite way with negate value', () => {
const permissionNode = new Node({ permissions: { locallySet: [{ name: 'collaborator', authorityId: 'user1' }, { name: 'consumer', authorityId: 'user2' }] } });
const permissionNode = new Node({
permissions: {
locallySet: [
{ name: 'collaborator', authorityId: 'user1' },
{ name: 'consumer', authorityId: 'user2' }
]
}
});
expect(contentService.hasPermissions(permissionNode, '!manager', 'user1')).toBeTruthy();
});
it('should havePermission return false if no permission parameter are passed', () => {
const permissionNode = new Node({ permissions: { locallySet: [{ name: 'collaborator', authorityId: 'user1' }, { name: 'consumer', authorityId: 'user2' }] } });
const permissionNode = new Node({
permissions: {
locallySet: [
{ name: 'collaborator', authorityId: 'user1' },
{ name: 'consumer', authorityId: 'user2' }
]
}
});
expect(contentService.hasPermissions(permissionNode, null, 'user1')).toBeFalsy();
});
@@ -119,13 +141,27 @@ describe('ContentService', () => {
});
it('should havePermission be true if inherited permissions is present and you have the permission for the request operation', () => {
const permissionNode = new Node({ permissions: { inherited: [{ name: 'manager', authorityId: 'user1' }, { name: 'collaborator', authorityId: 'user2' } ] } });
const permissionNode = new Node({
permissions: {
inherited: [
{ name: 'manager', authorityId: 'user1' },
{ name: 'collaborator', authorityId: 'user2' }
]
}
});
expect(contentService.hasPermissions(permissionNode, 'manager', 'user1')).toBeTruthy();
});
it('should take current logged user id if userId undefined ', () => {
spyOn(authService, 'getEcmUsername').and.returnValue('user1');
const permissionNode = new Node({ permissions: { inherited: [{ name: 'manager', authorityId: 'user1' }, { name: 'collaborator', authorityId: 'user2' } ] } });
const permissionNode = new Node({
permissions: {
inherited: [
{ name: 'manager', authorityId: 'user1' },
{ name: 'collaborator', authorityId: 'user2' }
]
}
});
expect(contentService.hasPermissions(permissionNode, 'manager')).toBeTruthy();
});
});
@@ -15,20 +15,9 @@
* limitations under the License.
*/
import {
createNewPersonMock,
fakeEcmAdminUser,
fakeEcmUser,
fakeEcmUser2,
fakeEcmUserList
} from '../mocks/ecm-user.service.mock';
import {
AlfrescoApiService,
AlfrescoApiServiceMock,
CoreTestingModule
} from '@alfresco/adf-core';
import { createNewPersonMock, fakeEcmAdminUser, fakeEcmUser, fakeEcmUser2, fakeEcmUserList } from '../mocks/ecm-user.service.mock';
import { AlfrescoApiService, AlfrescoApiServiceMock, CoreTestingModule } from '@alfresco/adf-core';
import { PeopleContentQueryRequestModel, PeopleContentService } from './people-content.service';
import { TranslateModule } from '@ngx-translate/core';
import { TestBed } from '@angular/core/testing';
describe('PeopleContentService', () => {
@@ -36,13 +25,8 @@ describe('PeopleContentService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }
]
imports: [CoreTestingModule],
providers: [{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }]
});
peopleContentService = TestBed.inject(PeopleContentService);
@@ -68,7 +52,6 @@ describe('PeopleContentService', () => {
expect(pagination.totalItems).toEqual(2);
expect(pagination.hasMoreItems).toBeFalsy();
expect(pagination.skipCount).toEqual(0);
});
it('should call listPeople api with requested sorting params', async () => {
@@ -114,7 +97,9 @@ describe('PeopleContentService', () => {
});
it('Should make the api call to check if the user is a content admin only once', async () => {
const getCurrentPersonSpy = spyOn(peopleContentService.peopleApi, 'getPerson').and.returnValue(Promise.resolve({ entry: fakeEcmAdminUser } as any));
const getCurrentPersonSpy = spyOn(peopleContentService.peopleApi, 'getPerson').and.returnValue(
Promise.resolve({ entry: fakeEcmAdminUser } as any)
);
const user = await peopleContentService.getCurrentUserInfo().toPromise();
expect(user.id).toEqual('fake-id');
@@ -128,10 +113,12 @@ describe('PeopleContentService', () => {
});
it('should not change current user on every getPerson call', async () => {
const getCurrentPersonSpy = spyOn(peopleContentService.peopleApi, 'getPerson').and.returnValue(Promise.resolve({entry: fakeEcmAdminUser} as any));
const getCurrentPersonSpy = spyOn(peopleContentService.peopleApi, 'getPerson').and.returnValue(
Promise.resolve({ entry: fakeEcmAdminUser } as any)
);
await peopleContentService.getCurrentUserInfo().toPromise();
getCurrentPersonSpy.and.returnValue(Promise.resolve({entry: fakeEcmUser2} as any));
getCurrentPersonSpy.and.returnValue(Promise.resolve({ entry: fakeEcmUser2 } as any));
await peopleContentService.getPerson('fake-id').toPromise();
expect(getCurrentPersonSpy.calls.count()).toEqual(2);
@@ -20,7 +20,6 @@ import { TestBed } from '@angular/core/testing';
import { AppConfigModule, AppConfigService, CoreTestingModule } from '@alfresco/adf-core';
import { UploadService } from './upload.service';
import { RepositoryInfo } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core';
import { BehaviorSubject } from 'rxjs';
import { DiscoveryApiService } from '../../common/services/discovery-api.service';
import { FileModel, FileUploadStatus } from '../../common/models/file.model';
@@ -36,11 +35,7 @@ describe('UploadService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule,
AppConfigModule
],
imports: [CoreTestingModule, AppConfigModule],
providers: [
{
provide: DiscoveryApiService,
@@ -94,10 +89,7 @@ describe('UploadService', () => {
});
it('should add two elements in the queue and returns them', () => {
const filesFake = [
new FileModel({ name: 'fake-name', size: 10 } as File),
new FileModel({ name: 'fake-name2', size: 20 } as File)
];
const filesFake = [new FileModel({ name: 'fake-name', size: 10 } as File), new FileModel({ name: 'fake-name2', size: 20 } as File)];
service.addToQueue(...filesFake);
expect(service.getQueue().length).toEqual(2);
});
@@ -161,15 +153,14 @@ describe('UploadService', () => {
emitterDisposable.unsubscribe();
done();
});
const fileFake = new FileModel(
{ name: 'fake-name', size: 10 } as File,
{ parentId: '-root-', path: 'fake-dir' }
);
const fileFake = new FileModel({ name: 'fake-name', size: 10 } as File, { parentId: '-root-', path: 'fake-dir' });
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(emitter);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations');
expect(request.url).toBe(
'http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations'
);
expect(request.method).toBe('POST');
jasmine.Ajax.requests.mostRecent().respondWith({
@@ -187,14 +178,12 @@ describe('UploadService', () => {
emitterDisposable.unsubscribe();
done();
});
const fileFake = new FileModel(
{ name: 'fake-name', size: 10 } as File,
{ parentId: '-root-' }
);
const fileFake = new FileModel({ name: 'fake-name', size: 10 } as File, { parentId: '-root-' });
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(null, emitter);
expect(jasmine.Ajax.requests.mostRecent().url)
.toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations');
expect(jasmine.Ajax.requests.mostRecent().url).toBe(
'http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations'
);
jasmine.Ajax.requests.mostRecent().respondWith({
status: 404,
@@ -228,14 +217,16 @@ describe('UploadService', () => {
emitterDisposable.unsubscribe();
const deleteRequest = jasmine.Ajax.requests.mostRecent();
expect(deleteRequest.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/myNodeId?permanent=true');
expect(deleteRequest.url).toBe(
'http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/myNodeId?permanent=true'
);
expect(deleteRequest.method).toBe('DELETE');
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
contentType: 'text/plain',
responseText: 'File deleted'
});
});
done();
});
@@ -247,7 +238,9 @@ describe('UploadService', () => {
service.cancelUpload(...file);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations');
expect(request.url).toBe(
'http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations'
);
expect(request.method).toBe('POST');
jasmine.Ajax.requests.mostRecent().respondWith({
@@ -280,7 +273,7 @@ describe('UploadService', () => {
done();
});
const fileFake = new FileModel({name: 'fake-name', size: 10} as File, null, 'fakeId');
const fileFake = new FileModel({ name: 'fake-name', size: 10 } as File, null, 'fakeId');
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(emitter);
@@ -288,7 +281,9 @@ describe('UploadService', () => {
service.cancelUpload(...file);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/fakeId/content?include=allowableOperations');
expect(request.url).toBe(
'http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/fakeId/content?include=allowableOperations'
);
expect(request.method).toBe('PUT');
jasmine.Ajax.requests.mostRecent().respondWith({
@@ -307,10 +302,7 @@ describe('UploadService', () => {
it('If newVersion is set, name should be a param', () => {
const emitter = new EventEmitter();
const filesFake = new FileModel(
{ name: 'fake-name', size: 10 } as File,
{ newVersion: true }
);
const filesFake = new FileModel({ name: 'fake-name', size: 10 } as File, { newVersion: true });
service.addToQueue(filesFake);
service.uploadFilesInTheQueue(emitter);
@@ -321,7 +313,7 @@ describe('UploadService', () => {
},
undefined,
undefined,
{ newVersion: true, name: 'fake-name', nodeType: undefined },
{ newVersion: true, name: 'fake-name', nodeType: undefined },
{
renditions: 'doclib',
include: ['allowableOperations'],
@@ -341,15 +333,14 @@ describe('UploadService', () => {
emitterDisposable.unsubscribe();
done();
});
const filesFake = new FileModel(
{ name: 'fake-file-name', size: 10 } as File,
{ parentId: '123', path: 'fake-dir' }
);
const filesFake = new FileModel({ name: 'fake-file-name', size: 10 } as File, { parentId: '123', path: 'fake-dir' });
service.addToQueue(filesFake);
service.uploadFilesInTheQueue(emitter);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/123/children?autoRename=true&include=allowableOperations');
expect(request.url).toBe(
'http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/123/children?autoRename=true&include=allowableOperations'
);
expect(request.method).toBe('POST');
jasmine.Ajax.requests.mostRecent().respondWith({
@@ -361,10 +352,7 @@ describe('UploadService', () => {
describe('versioningEnabled', () => {
it('should upload with "versioningEnabled" parameter taken from file options', () => {
const model = new FileModel(
{ name: 'file-name', size: 10 } as File,
{ versioningEnabled: true }
);
const model = new FileModel({ name: 'file-name', size: 10 } as File, { versioningEnabled: true });
service.addToQueue(model);
service.uploadFilesInTheQueue();
@@ -378,7 +366,7 @@ describe('UploadService', () => {
undefined,
{ newVersion: false, name: 'file-name', nodeType: undefined },
{
include: [ 'allowableOperations' ],
include: ['allowableOperations'],
renditions: 'doclib',
versioningEnabled: true,
autoRename: true
@@ -387,10 +375,7 @@ describe('UploadService', () => {
});
it('should not use "versioningEnabled" if not explicitly provided', () => {
const model = new FileModel(
{ name: 'file-name', size: 10 } as File,
{}
);
const model = new FileModel({ name: 'file-name', size: 10 } as File, {});
service.addToQueue(model);
service.uploadFilesInTheQueue();
@@ -404,7 +389,7 @@ describe('UploadService', () => {
undefined,
{ newVersion: false, name: 'file-name', nodeType: undefined },
{
include: [ 'allowableOperations' ],
include: ['allowableOperations'],
renditions: 'doclib',
autoRename: true
}
@@ -413,15 +398,13 @@ describe('UploadService', () => {
});
it('should append the extra upload options to the request', () => {
const filesFake = new FileModel(
{ name: 'fake-name', size: 10 } as File,
{
parentId: '123',
path: 'fake-dir',
secondaryChildren: [{ assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [{ assocType: 'target-assoc', targetId: 'fake-target-id' }]
});
const filesFake = new FileModel({ name: 'fake-name', size: 10 } as File, {
parentId: '123',
path: 'fake-dir',
secondaryChildren: [{ assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [{ assocType: 'target-assoc', targetId: 'fake-target-id' }]
});
service.addToQueue(filesFake);
service.uploadFilesInTheQueue();
@@ -438,7 +421,7 @@ describe('UploadService', () => {
nodeType: undefined,
parentId: '123',
path: 'fake-dir',
secondaryChildren: [ { assocType: 'assoc-1', childId: 'child-id' }],
secondaryChildren: [{ assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [{ assocType: 'target-assoc', targetId: 'fake-target-id' }]
},
@@ -482,24 +465,24 @@ describe('UploadService', () => {
});
it('should skip files if they are in an excluded folder', () => {
const file1: any = { name: 'readmetoo.md', file : { webkitRelativePath: '/rollingPanda/' }};
const file2: any = { name: 'readme.md', file : { webkitRelativePath: '/test/' }};
const file1: any = { name: 'readmetoo.md', file: { webkitRelativePath: '/rollingPanda/' } };
const file2: any = { name: 'readme.md', file: { webkitRelativePath: '/test/' } };
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
});
it('should match the folder in case insensitive way', () => {
const file1: any = { name: 'readmetoo.md', file : { webkitRelativePath: '/rollingPanda/' }};
const file2: any = { name: 'readme.md', file : { webkitRelativePath: '/test/' }};
const file1: any = { name: 'readmetoo.md', file: { webkitRelativePath: '/rollingPanda/' } };
const file2: any = { name: 'readme.md', file: { webkitRelativePath: '/test/' } };
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
});
it('should skip files if they are in an excluded folder when path is in options', () => {
const file1: any = { name: 'readmetoo.md', file : {}, options: { path: '/rollingPanda/'}};
const file2: any = { name: 'readme.md', file : { webkitRelativePath: '/test/' }};
const file1: any = { name: 'readmetoo.md', file: {}, options: { path: '/rollingPanda/' } };
const file2: any = { name: 'readme.md', file: { webkitRelativePath: '/test/' } };
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
@@ -535,10 +518,7 @@ describe('UploadService', () => {
it('Should not pass rendition if it is disabled', () => {
mockProductInfo.next({ status: { isThumbnailGenerationEnabled: false } } as RepositoryInfo);
const filesFake = new FileModel(
{ name: 'fake-name', size: 10 } as File,
{ newVersion: true}
);
const filesFake = new FileModel({ name: 'fake-name', size: 10 } as File, { newVersion: true });
service.addToQueue(filesFake);
service.uploadFilesInTheQueue();
@@ -22,14 +22,12 @@ import { ContentMetadataCardComponent } from './content-metadata-card.component'
import { ContentMetadataComponent } from '../content-metadata/content-metadata.component';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { SimpleChange } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { NodeAspectService } from '../../../aspect-list/services/node-aspect.service';
import { ContentMetadataService } from '../../services/content-metadata.service';
import { AllowableOperationsEnum } from '../../../common/models/allowable-operations.enum';
import { of } from 'rxjs';
describe('ContentMetadataCardComponent', () => {
let component: ContentMetadataCardComponent;
let fixture: ComponentFixture<ContentMetadataCardComponent>;
let contentMetadataService: ContentMetadataService;
@@ -41,10 +39,7 @@ describe('ContentMetadataCardComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(ContentMetadataCardComponent);
contentMetadataService = TestBed.inject(ContentMetadataService);
@@ -157,11 +152,11 @@ describe('ContentMetadataCardComponent', () => {
it('should expand the card when custom display aspect is valid', () => {
expect(component.expanded).toBeFalsy();
let displayAspect = new SimpleChange(null , 'EXIF', true);
let displayAspect = new SimpleChange(null, 'EXIF', true);
component.ngOnChanges({ displayAspect });
expect(component.expanded).toBeTruthy();
displayAspect = new SimpleChange('EXIF' , null, false);
displayAspect = new SimpleChange('EXIF', null, false);
component.ngOnChanges({ displayAspect });
expect(component.expanded).toBeTruthy();
});
@@ -25,7 +25,6 @@ import { AppConfigService, CardViewBaseItemModel, CardViewComponent, Notificatio
import { NodesApiService } from '../../../common/services/nodes-api.service';
import { EMPTY, of, throwError } from 'rxjs';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { CardViewContentUpdateService } from '../../../common/services/card-view-content-update.service';
import { PropertyGroup } from '../../interfaces/property-group.interface';
import { PropertyDescriptorsService } from '../../services/property-descriptors.service';
@@ -100,8 +99,7 @@ describe('ContentMetadataComponent', () => {
fixture.detectChanges();
};
const clickOnGroupSave = () => fixture.debugElement.query(By.css('[data-automation-id="save-metadata"]'))
.nativeElement.click();
const clickOnGroupSave = () => fixture.debugElement.query(By.css('[data-automation-id="save-metadata"]')).nativeElement.click();
const findTagsCreator = (): TagsCreatorComponent => fixture.debugElement.query(By.directive(TagsCreatorComponent))?.componentInstance;
const getToggleEditButton = () => fixture.debugElement.query(By.css('[data-automation-id="meta-data-general-info-edit"]'));
@@ -129,20 +127,16 @@ describe('ContentMetadataComponent', () => {
fixture.detectChanges();
};
const getGeneralInfoPanelContent = (): CardViewComponent => fixture.debugElement.query(By.css(
'.adf-metadata-properties-expansion-panel'
)).componentInstance;
const getGeneralInfoPanelContent = (): CardViewComponent =>
fixture.debugElement.query(By.css('.adf-metadata-properties-expansion-panel')).componentInstance;
const getGroupPanelContent = (): CardViewComponent => fixture.debugElement.query(By.css(
'.adf-metadata-grouped-properties-container adf-card-view'
)).componentInstance;
const getGroupPanelContent = (): CardViewComponent =>
fixture.debugElement.query(By.css('.adf-metadata-grouped-properties-container adf-card-view')).componentInstance;
const getGeneralInfoPanel = (): MatExpansionPanel => fixture.debugElement.query(By.css(
'[data-automation-id="adf-metadata-group-properties"]'
))?.componentInstance;
const getGeneralInfoPanel = (): MatExpansionPanel =>
fixture.debugElement.query(By.css('[data-automation-id="adf-metadata-group-properties"]'))?.componentInstance;
const queryDom = (properties = 'properties') =>
fixture.debugElement.query(By.css(`[data-automation-id="adf-metadata-group-${properties}"]`));
const queryDom = (properties = 'properties') => fixture.debugElement.query(By.css(`[data-automation-id="adf-metadata-group-${properties}"]`));
/**
* Get metadata categories
@@ -164,7 +158,7 @@ describe('ContentMetadataComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
providers: [
{
provide: TagService,
@@ -274,11 +268,15 @@ describe('ContentMetadataComponent', () => {
}));
it('should save changedProperties on save click', fakeAsync(() => {
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{
editable: true,
title: 'test',
properties: []
}]));
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(
of([
{
editable: true,
title: 'test',
properties: []
}
])
);
updateService.itemUpdated$.next({
changed: {}
} as UpdateNotification);
@@ -458,11 +456,15 @@ describe('ContentMetadataComponent', () => {
beforeEach(() => {
showErrorSpy = spyOn(notificationService, 'showError').and.stub();
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{
editable: true,
title: 'test',
properties: []
}]));
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(
of([
{
editable: true,
title: 'test',
properties: []
}
])
);
component.displayCategories = true;
component.displayTags = true;
component.ngOnInit();
@@ -610,11 +612,15 @@ describe('ContentMetadataComponent', () => {
});
it('should reset group edit ability on reset click', () => {
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{
editable: true,
title: 'test',
properties: []
}]));
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(
of([
{
editable: true,
title: 'test',
properties: []
}
])
);
component.ngOnInit();
component.readOnly = false;
fixture.detectChanges();
@@ -773,11 +779,15 @@ describe('ContentMetadataComponent', () => {
});
it('should reload properties for group panel on cancel', () => {
const getGroupedPropertiesSpy = spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{
editable: true,
title: 'test',
properties: []
}]));
const getGroupedPropertiesSpy = spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(
of([
{
editable: true,
title: 'test',
properties: []
}
])
);
component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) });
component.readOnly = false;
fixture.detectChanges();
@@ -1181,8 +1191,7 @@ describe('ContentMetadataComponent', () => {
let tagPaging: TagPaging;
const expandTagsPanel = (): void => {
fixture.debugElement.query(By.css('[data-automation-id="adf-content-metadata-tags-panel"]'))
?.componentInstance.opened.emit();
fixture.debugElement.query(By.css('[data-automation-id="adf-content-metadata-tags-panel"]'))?.componentInstance.opened.emit();
fixture.detectChanges();
};
@@ -1398,8 +1407,7 @@ describe('ContentMetadataComponent', () => {
describe('Categories list', () => {
const expandCategoriesPanel = (): void => {
fixture.debugElement.query(By.css('[data-automation-id="adf-content-metadata-categories-panel"]'))
?.componentInstance.opened.emit();
fixture.debugElement.query(By.css('[data-automation-id="adf-content-metadata-categories-panel"]'))?.componentInstance.opened.emit();
fixture.detectChanges();
};
@@ -1530,7 +1538,7 @@ describe('ContentMetadataComponent', () => {
it('should enable discard and save buttons after emitting categories change event', () => {
categoriesManagementComponent.categoriesChange.emit([category1, category2]);
component.readOnly =false;
component.readOnly = false;
fixture.detectChanges();
expect(findCancelButton().disabled).toBeFalse();
expect(findSaveCategoriesButton().disabled).toBeFalse();
@@ -21,7 +21,6 @@ import { TestBed } from '@angular/core/testing';
import { ContentMetadataService } from './content-metadata.service';
import { of } from 'rxjs';
import { PropertyGroup } from '../interfaces/property-group.interface';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTypePropertiesService } from './content-type-property.service';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { PropertyDescriptorsService } from './property-descriptors.service';
@@ -42,14 +41,7 @@ const fakeContentNode: Node = {
id: 'fake-id',
nodeType: 'cm:content',
isFile: true,
aspectNames: [
'rn:renditioned',
'cm:versionable',
'cm:titled',
'cm:auditable',
'cm:author',
'cm:thumbnailModification'
],
aspectNames: ['rn:renditioned', 'cm:versionable', 'cm:titled', 'cm:auditable', 'cm:author', 'cm:thumbnailModification'],
createdByUser: { displayName: 'test-user' },
modifiedByUser: { displayName: 'test-user-modified' },
properties: []
@@ -148,13 +140,11 @@ describe('ContentMetaDataService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
service = TestBed.inject(ContentMetadataService);
contentPropertyService = TestBed.inject(ContentTypePropertiesService);
const propertyDescriptorsService = TestBed.inject(
PropertyDescriptorsService
);
const propertyDescriptorsService = TestBed.inject(PropertyDescriptorsService);
classesApi = propertyDescriptorsService['classesApi'];
appConfig = TestBed.inject(AppConfigService);
});
@@ -169,9 +159,7 @@ describe('ContentMetaDataService', () => {
});
it('should return the content type property', () => {
spyOn(contentPropertyService, 'getContentTypeCardItem').and.returnValue(
of({ label: 'hello i am a weird content type' } as any)
);
spyOn(contentPropertyService, 'getContentTypeCardItem').and.returnValue(of({ label: 'hello i am a weird content type' } as any));
service.getContentTypeProperty(fakeNode).subscribe((res: any) => {
expect(res).toBeDefined();
@@ -181,15 +169,10 @@ describe('ContentMetaDataService', () => {
});
it('should trigger the opening of the content type dialog', () => {
spyOn(
contentPropertyService,
'openContentTypeDialogConfirm'
).and.returnValue(of(true));
spyOn(contentPropertyService, 'openContentTypeDialogConfirm').and.returnValue(of(true));
service.openConfirmDialog(fakeNode).subscribe(() => {
expect(
contentPropertyService.openContentTypeDialogConfirm
).toHaveBeenCalledWith('fn:fakenode');
expect(contentPropertyService.openContentTypeDialogConfirm).toHaveBeenCalledWith('fn:fakenode');
});
});
@@ -197,9 +180,7 @@ describe('ContentMetaDataService', () => {
it('should return response with exif property', async () => {
setConfig('default', { 'exif:exif': '*' });
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(exifResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
const groupedProperties = await service.getGroupedProperties(fakeNode).toPromise();
@@ -213,9 +194,7 @@ describe('ContentMetaDataService', () => {
it('should filter the record options for node ', async () => {
setConfig('default', { 'exif:exif': '*', 'rma:record': '*' });
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(exifResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
const groupedProperties = await service.getGroupedProperties(fakeNode).toPromise();
@@ -315,9 +294,7 @@ describe('ContentMetaDataService', () => {
'exif:exif': ['exif:pixelXDimension', 'exif:pixelYDimension']
});
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(exifResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
const groupedProperties = await service.getGroupedProperties(fakeNode).toPromise();
@@ -337,9 +314,7 @@ describe('ContentMetaDataService', () => {
'exif:exif': ['exif:pixelXDimension', 'exif:pixelYDimension']
});
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(exifResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
const groupedProperties = await service.getGroupedProperties(fakeNode).toPromise();
@@ -379,17 +354,13 @@ describe('ContentMetaDataService', () => {
];
setConfig('custom', customLayoutOrientedScheme);
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(contentResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(contentResponse));
service
.getGroupedProperties(fakeContentNode, 'custom')
.subscribe((res) => {
expect(res.length).toEqual(1);
expect(res[0].title).toEqual('Properties');
done();
});
service.getGroupedProperties(fakeContentNode, 'custom').subscribe((res) => {
expect(res.length).toEqual(1);
expect(res[0].title).toEqual('Properties');
done();
});
expect(classesApi.getClass).toHaveBeenCalledTimes(1);
expect(classesApi.getClass).toHaveBeenCalledWith('cm_content');
@@ -422,17 +393,13 @@ describe('ContentMetaDataService', () => {
];
setConfig('custom', customLayoutOrientedScheme);
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(contentResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(contentResponse));
service
.getGroupedProperties(fakeContentNode, 'custom')
.subscribe((res) => {
expect(res.length).toEqual(1);
expect(res[0].title).toEqual('Properties');
done();
});
service.getGroupedProperties(fakeContentNode, 'custom').subscribe((res) => {
expect(res.length).toEqual(1);
expect(res[0].title).toEqual('Properties');
done();
});
expect(classesApi.getClass).toHaveBeenCalledTimes(1);
expect(classesApi.getClass).toHaveBeenCalledWith('cm_content');
@@ -456,16 +423,12 @@ describe('ContentMetaDataService', () => {
];
setConfig('custom', customLayoutOrientedScheme);
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(contentResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(contentResponse));
service
.getGroupedProperties(fakeContentNode, 'custom')
.subscribe((res) => {
expect(res.length).toEqual(0);
done();
});
service.getGroupedProperties(fakeContentNode, 'custom').subscribe((res) => {
expect(res.length).toEqual(0);
done();
});
expect(classesApi.getClass).toHaveBeenCalledTimes(1 + fakeContentNode.aspectNames.length);
expect(classesApi.getClass).toHaveBeenCalledWith('cm_content');
@@ -499,24 +462,15 @@ describe('ContentMetaDataService', () => {
}
];
spyOn(classesApi, 'getClass').and.returnValue(
Promise.resolve(contentResponse)
);
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(contentResponse));
service
.getGroupedProperties(
fakeContentNode,
customLayoutOrientedScheme
)
.subscribe((res) => {
expect(res.length).toEqual(1);
expect(res[0].title).toEqual('Properties');
expect(classesApi.getClass).toHaveBeenCalledTimes(1);
expect(classesApi.getClass).toHaveBeenCalledWith(
'cm_content'
);
done();
});
service.getGroupedProperties(fakeContentNode, customLayoutOrientedScheme).subscribe((res) => {
expect(res.length).toEqual(1);
expect(res[0].title).toEqual('Properties');
expect(classesApi.getClass).toHaveBeenCalledTimes(1);
expect(classesApi.getClass).toHaveBeenCalledWith('cm_content');
done();
});
});
});
});
@@ -19,21 +19,18 @@ import { TestBed } from '@angular/core/testing';
import { ContentTypePropertiesService } from './content-type-property.service';
import { CardViewItem, CardViewSelectItemModel, CardViewTextItemModel } from '@alfresco/adf-core';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTypeService } from '../../content-type';
import { of } from 'rxjs';
import { Node, TypeEntry } from '@alfresco/js-api';
import { VersionCompatibilityService } from '../../version-compatibility/version-compatibility.service';
describe('ContentTypePropertyService', () => {
let service: ContentTypePropertiesService;
let versionCompatibilityService: VersionCompatibilityService;
let contentTypeService: ContentTypeService;
const mockContent: any = {
entry:
{
entry: {
associations: [],
isArchive: true,
includedInSupertypeQuery: true,
@@ -42,14 +39,24 @@ describe('ContentTypePropertyService', () => {
id: 'fk:nodeType',
title: 'Content',
model: { namespacePrefix: 'fk' },
properties: [{ id: 'cm:name', title: 'Name', description: 'Name', dataType: 'd:text', isMultiValued: false, isMandatory: true, isMandatoryEnforced: true, isProtected: false }],
properties: [
{
id: 'cm:name',
title: 'Name',
description: 'Name',
dataType: 'd:text',
isMultiValued: false,
isMandatory: true,
isMandatoryEnforced: true,
isProtected: false
}
],
parentId: 'cm:cmobject'
}
};
const mockContentWithProperties: any = {
entry:
{
entry: {
associations: [],
isArchive: true,
includedInSupertypeQuery: true,
@@ -79,7 +86,8 @@ describe('ContentTypePropertyService', () => {
defaultValue: 'default',
isMandatoryEnforced: true,
isProtected: false
}],
}
],
parentId: 'cm:cmobject'
}
};
@@ -99,16 +107,18 @@ describe('ContentTypePropertyService', () => {
},
id: 'e2e:test',
title: 'Test type',
properties: [{
id: 'cm:name',
title: 'Name',
description: 'Name',
dataType: 'd:text',
isMultiValued: false,
isMandatory: true,
isMandatoryEnforced: true,
isProtected: false
}],
properties: [
{
id: 'cm:name',
title: 'Name',
description: 'Name',
dataType: 'd:text',
isMultiValued: false,
isMandatory: true,
isMandatoryEnforced: true,
isProtected: false
}
],
parentId: 'cm:content'
}
}
@@ -116,10 +126,7 @@ describe('ContentTypePropertyService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
service = TestBed.inject(ContentTypePropertiesService);
versionCompatibilityService = TestBed.inject(VersionCompatibilityService);
@@ -214,7 +221,7 @@ describe('ContentTypePropertyService', () => {
nodeType: 'fn:fakenode',
createdByUser: { displayName: 'test-user' },
modifiedByUser: { displayName: 'test-user-modified' },
properties: {'fk:brendonstare': 'i keep staring i do not know why'}
properties: { 'fk:brendonstare': 'i keep staring i do not know why' }
} as Node;
spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(true);
spyOn(contentTypeService, 'getContentTypeByPrefix').and.returnValue(of(mockContentWithProperties));
@@ -235,5 +242,4 @@ describe('ContentTypePropertyService', () => {
done();
});
});
});
@@ -20,19 +20,14 @@ import { PropertyDescriptorsService } from './property-descriptors.service';
import { ClassesApi } from '@alfresco/js-api';
import { PropertyGroup } from '../interfaces/content-metadata.interfaces';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('PropertyDescriptorLoaderService', () => {
let service: PropertyDescriptorsService;
let classesApi: ClassesApi;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
service = TestBed.inject(PropertyDescriptorsService);
classesApi = service['classesApi'];
@@ -41,8 +36,7 @@ describe('PropertyDescriptorLoaderService', () => {
it('should load the groups passed by paramter', () => {
spyOn(classesApi, 'getClass');
service.load(['exif:exif', 'cm:content', 'custom:custom'])
.subscribe(() => {});
service.load(['exif:exif', 'cm:content', 'custom:custom']).subscribe(() => {});
expect(classesApi.getClass).toHaveBeenCalledTimes(3);
expect(classesApi.getClass).toHaveBeenCalledWith('exif_exif');
@@ -51,7 +45,6 @@ describe('PropertyDescriptorLoaderService', () => {
});
it('should merge the forked values', (done) => {
const exifResponse: PropertyGroup = {
name: 'exif:exif',
title: '',
@@ -69,18 +62,17 @@ describe('PropertyDescriptorLoaderService', () => {
}
};
const apiResponses = [ exifResponse, contentResponse ];
const apiResponses = [exifResponse, contentResponse];
let counter = 0;
spyOn(classesApi, 'getClass').and.callFake(() => Promise.resolve(apiResponses[counter++]));
service.load(['exif:exif', 'cm:content'])
.subscribe({
next: (data) => {
expect(data['exif:exif']).toBe(exifResponse);
expect(data['cm:content']).toBe(contentResponse);
},
complete: () => done()
});
service.load(['exif:exif', 'cm:content']).subscribe({
next: (data) => {
expect(data['exif:exif']).toBe(exifResponse);
expect(data['cm:content']).toBe(contentResponse);
},
complete: () => done()
});
});
});
@@ -32,11 +32,9 @@ import {
LogService
} from '@alfresco/adf-core';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { Constraint, Definition, Property as PropertyBase } from '@alfresco/js-api';
describe('PropertyGroupTranslatorService', () => {
let service: PropertyGroupTranslatorService;
let propertyGroups: OrganisedPropertyGroup[];
let propertyGroup: OrganisedPropertyGroup;
@@ -46,10 +44,7 @@ describe('PropertyGroupTranslatorService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
logService = TestBed.inject(LogService);
service = TestBed.inject(PropertyGroupTranslatorService);
@@ -76,59 +71,64 @@ describe('PropertyGroupTranslatorService', () => {
});
describe('General transformation', () => {
it('should translate EVERY properties in ONE group properly', () => {
propertyGroup.properties = [{
name: 'FAS:PLAGUE',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultValue',
mandatory: false,
multiValued: false,
editable: true
},
{
name: 'FAS:ALOY',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultValue',
mandatory: false,
multiValued: false
}];
propertyGroup.properties = [
{
name: 'FAS:PLAGUE',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultValue',
mandatory: false,
multiValued: false,
editable: true
},
{
name: 'FAS:ALOY',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultValue',
mandatory: false,
multiValued: false
}
];
propertyGroups.push(propertyGroup);
propertyValues = { 'FAS:PLAGUE': 'The Chariot Line' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null)[0];
expect(cardViewGroup.properties.length).toBe(2);
expect(cardViewGroup.properties[0] instanceof CardViewTextItemModel).toBeTruthy('First property should be instance of CardViewTextItemModel');
expect(cardViewGroup.properties[1] instanceof CardViewTextItemModel).toBeTruthy('Second property should be instance of CardViewTextItemModel');
expect(cardViewGroup.properties[0] instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewGroup.properties[1] instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewGroup.editable).toBeTrue();
});
it('should translate EVERY property in EVERY group properly', () => {
propertyGroups.push(
Object.assign({}, propertyGroup, {
properties: [{
name: 'FAS:PLAGUE',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultvalue',
mandatory: false,
multiValued: false,
editable: false
}]
properties: [
{
name: 'FAS:PLAGUE',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultvalue',
mandatory: false,
multiValued: false,
editable: false
}
]
}),
Object.assign({}, propertyGroup, {
properties: [{
name: 'FAS:ALOY',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultvalue',
mandatory: false,
multiValued: false,
editable: false
}]
properties: [
{
name: 'FAS:ALOY',
title: 'title',
dataType: 'd:text',
defaultValue: 'defaultvalue',
mandatory: false,
multiValued: false,
editable: false
}
]
})
);
@@ -137,8 +137,8 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroups = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
expect(cardViewGroups.length).toBe(2);
const firstCardViewGroup = cardViewGroups[0];
expect(firstCardViewGroup.properties[0] instanceof CardViewTextItemModel).toBeTruthy('First group\'s property should be instance of CardViewTextItemModel');
expect(cardViewGroups[1].properties[0] instanceof CardViewTextItemModel).toBeTruthy('Second group\'s property should be instance of CardViewTextItemModel');
expect(firstCardViewGroup.properties[0] instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewGroups[1].properties[0] instanceof CardViewTextItemModel).toBeTruthy();
expect(firstCardViewGroup.editable).toBeFalse();
});
@@ -172,7 +172,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy();
});
it('should not edit the protected fields', () => {
@@ -190,13 +190,12 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewProperty.editable).toBe(false);
});
});
describe('Different types attributes', () => {
beforeEach(() => {
propertyGroups.push(propertyGroup);
});
@@ -215,7 +214,7 @@ describe('PropertyGroupTranslatorService', () => {
expect(cardViewProperty.label).toBe(property.title);
expect(cardViewProperty.key).toBe('properties.prefix:name');
expect(cardViewProperty.default).toBe(property.defaultValue);
expect(cardViewProperty.editable).toBeTruthy('Property should be editable');
expect(cardViewProperty.editable).toBeTruthy();
});
});
@@ -226,9 +225,9 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe('The Chariot Line');
expect(cardViewProperty.multiline).toBeFalsy('Property should be singleline');
expect(cardViewProperty.multiline).toBeFalsy();
});
it('should translate properly the multiline and value attributes for d:mltext', () => {
@@ -238,9 +237,9 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe('The Chariot Line');
expect(cardViewProperty.multiline).toBeTruthy('Property should be multiline');
expect(cardViewProperty.multiline).toBeTruthy();
});
it('should translate properly the value attribute for d:date', () => {
@@ -251,7 +250,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewDateItemModel = cardViewGroup[0].properties[0] as CardViewDateItemModel;
expect(cardViewProperty instanceof CardViewDateItemModel).toBeTruthy('Property should be instance of CardViewDateItemModel');
expect(cardViewProperty instanceof CardViewDateItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(expectedValue);
});
@@ -263,7 +262,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewDatetimeItemModel = cardViewGroup[0].properties[0] as CardViewDatetimeItemModel;
expect(cardViewProperty instanceof CardViewDatetimeItemModel).toBeTruthy('Property should be instance of CardViewDatetimeItemModel');
expect(cardViewProperty instanceof CardViewDatetimeItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(expectedValue);
});
@@ -274,7 +273,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewIntItemModel = cardViewGroup[0].properties[0] as CardViewIntItemModel;
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel');
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(1024);
});
@@ -285,7 +284,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewIntItemModel = cardViewGroup[0].properties[0] as CardViewIntItemModel;
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel');
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(0);
});
@@ -296,7 +295,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewIntItemModel = cardViewGroup[0].properties[0] as CardViewIntItemModel;
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel');
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(1024);
});
@@ -307,7 +306,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewFloatItemModel = cardViewGroup[0].properties[0] as CardViewFloatItemModel;
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel');
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(1024.24);
});
@@ -318,7 +317,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewFloatItemModel = cardViewGroup[0].properties[0] as CardViewFloatItemModel;
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel');
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(0);
});
@@ -329,7 +328,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewFloatItemModel = cardViewGroup[0].properties[0] as CardViewFloatItemModel;
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel');
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(1024.24);
});
@@ -340,30 +339,32 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewBoolItemModel = cardViewGroup[0].properties[0] as CardViewBoolItemModel;
expect(cardViewProperty instanceof CardViewBoolItemModel).toBeTruthy('Property should be instance of CardViewBoolItemModel');
expect(cardViewProperty instanceof CardViewBoolItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe(true);
});
it('should translate property for type LIST constraint', () => {
const definition: Definition = {
properties: [{
id: 'FAS:PLAGUE',
constraints: [
{
type: 'LIST',
parameters: {
allowedValues: ['one', 'two', 'three']
properties: [
{
id: 'FAS:PLAGUE',
constraints: [
{
type: 'LIST',
parameters: {
allowedValues: ['one', 'two', 'three']
}
}
}
]
} as Constraint]
]
} as Constraint
]
};
property.dataType = 'd:text';
propertyValues = { 'FAS:PLAGUE': 'two' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, definition);
const cardViewProperty = cardViewGroup[0].properties[0] as CardViewSelectItemModel<CardViewSelectItemProperties<string>>;
expect(cardViewProperty instanceof CardViewSelectItemModel).toBeTruthy('Property should be instance of CardViewBoolItemModel');
expect(cardViewProperty instanceof CardViewSelectItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe('two');
});
@@ -382,7 +383,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewProperty = service.translateProperty(propertyBase, 'Scary Brandon and the DuckTales', true);
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe('Scary Brandon and the DuckTales');
expect(cardViewProperty.key).toBe('properties.fk:brendonstare');
});
@@ -422,7 +423,7 @@ describe('PropertyGroupTranslatorService', () => {
const cardViewProperty = service.translateProperty(propertyBase, null, true);
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy();
expect(cardViewProperty.value).toBe('default');
expect(cardViewProperty.key).toBe('properties.fk:emperor');
expect(cardViewProperty.editable).toBe(false);
@@ -23,7 +23,6 @@ import { ContentNodeDialogService } from './content-node-dialog.service';
import { MatDialog } from '@angular/material/dialog';
import { Subject, of } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { NodeAction } from '../document-list/models/node-action.enum';
import { SitesService } from '../common/services/sites.service';
@@ -61,7 +60,6 @@ const fakeSiteList: SitePaging = new SitePaging({
});
describe('ContentNodeDialogService', () => {
let service: ContentNodeDialogService;
let documentListService: DocumentListService;
let sitesService: SitesService;
@@ -71,10 +69,7 @@ describe('ContentNodeDialogService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
const appConfig: AppConfigService = TestBed.inject(AppConfigService);
appConfig.config.ecmHost = 'http://localhost:9876/ecm';
@@ -99,10 +94,12 @@ describe('ContentNodeDialogService', () => {
isFile: false
} as Node;
service.openLockNodeDialog(testNode).subscribe(() => {
}, (error) => {
expect(error).toBe('OPERATION.FAIL.NODE.NO_PERMISSION');
});
service.openLockNodeDialog(testNode).subscribe(
() => {},
(error) => {
expect(error).toBe('OPERATION.FAIL.NODE.NO_PERMISSION');
}
);
});
it('should be able to open the dialog when node has permission', () => {
@@ -116,7 +113,8 @@ describe('ContentNodeDialogService', () => {
(error) => {
expect(spyOnDialogOpen).not.toHaveBeenCalled();
expect(JSON.parse(error.message).error.statusCode).toBe(403);
});
}
);
});
it('should be able to open the dialog using a folder id', fakeAsync(() => {
@@ -26,7 +26,6 @@ import { DocumentListService } from '../document-list/services/document-list.ser
import { DocumentListComponent } from '../document-list/components/document-list.component';
import { CustomResourcesService } from '../document-list/services/custom-resources.service';
import { NodeEntryEvent, ShareDataRow } from '../document-list';
import { TranslateModule } from '@ngx-translate/core';
import { SearchQueryBuilderService } from '../search';
import { mockSearchRequest } from '../mock/search-query.mock';
import { SitesService } from '../common/services/sites.service';
@@ -70,12 +69,13 @@ describe('ContentNodeSelectorPanelComponent', () => {
};
const triggerSearchResults = (searchResults: ResultSetPaging) => {
component.queryBuilderService.executed.next(searchResults);
const service = fixture.debugElement.injector.get(SearchQueryBuilderService);
service.executed.next(searchResults);
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
});
@@ -89,8 +89,8 @@ describe('ContentNodeSelectorPanelComponent', () => {
nodeService = TestBed.inject(NodesApiService);
sitesService = TestBed.inject(SitesService);
searchQueryBuilderService = component.queryBuilderService;
component.queryBuilderService.resetToDefaults();
searchQueryBuilderService = fixture.debugElement.injector.get(SearchQueryBuilderService);
searchQueryBuilderService.resetToDefaults();
spyOn(nodeService, 'getNode').and.returnValue(
of(
@@ -416,7 +416,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
spyOn(customResourcesService, 'hasCorrespondingNodeIds').and.returnValue(true);
const showingSearchSpy = spyOn(component.showingSearch, 'emit');
await component.queryBuilderService.execute({ query: { query: 'search' } });
await searchQueryBuilderService.execute({ query: { query: 'search' } });
triggerSearchResults(fakeResultSetPaging);
fixture.detectChanges();
@@ -460,7 +460,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
searchQueryBuilderService.update();
getCorrespondingNodeIdsSpy.and.throwError('Failed');
const showingSearchSpy = spyOn(component.showingSearch, 'emit');
await component.queryBuilderService.execute({ query: { query: 'search' } });
await searchQueryBuilderService.execute({ query: { query: 'search' } });
triggerSearchResults(fakeResultSetPaging);
fixture.detectChanges();
@@ -471,7 +471,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
});
it('should the query restrict the search to the site and not to the currentFolderId in case is changed', async () => {
component.queryBuilderService.userQuery = 'search-term*';
searchQueryBuilderService.userQuery = 'search-term*';
component.currentFolderId = 'my-root-id';
component.restrictRootToCurrentFolderId = true;
component.siteChanged({ entry: { guid: 'my-site-id' } } as SiteEntry);
@@ -730,7 +730,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
expect(component.searchTerm).toBe('');
expect(component.infiniteScroll).toBeTruthy();
expect(component.queryBuilderService.paging.maxItems).toBe(45);
expect(searchQueryBuilderService.paging.maxItems).toBe(45);
expect(searchSpy).not.toHaveBeenCalled();
});
@@ -771,7 +771,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
it('Should set the scope to nodes when the component inits', () => {
const expectedScope: RequestScope = { locations: 'nodes' };
const setScopeSpy = spyOn(component.queryBuilderService, 'setScope');
const setScopeSpy = spyOn(searchQueryBuilderService, 'setScope');
component.ngOnInit();
expect(setScopeSpy).toHaveBeenCalledWith(expectedScope);
@@ -32,7 +32,6 @@ import { ContentTestingModule } from '../testing/content.testing.module';
import { DocumentListService } from '../document-list/services/document-list.service';
import { DropdownSitesComponent } from '../site-dropdown/sites-dropdown.component';
import { NodeEntryEvent, ShareDataRow, ShareDataTableAdapter } from '../document-list';
import { TranslateModule } from '@ngx-translate/core';
import { SearchQueryBuilderService } from '../search';
import { ContentNodeSelectorPanelService } from './content-node-selector-panel.service';
import { mockContentModelTextProperty } from '../mock/content-model.mock';
@@ -71,12 +70,13 @@ describe('ContentNodeSelectorPanelComponent', () => {
let contentService: ContentService;
const triggerSearchResults = (searchResults: ResultSetPaging) => {
component.queryBuilderService.executed.next(searchResults);
const service = fixture.debugElement.injector.get(SearchQueryBuilderService);
service.executed.next(searchResults);
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
});
@@ -94,8 +94,8 @@ describe('ContentNodeSelectorPanelComponent', () => {
contentService = TestBed.inject(ContentService);
thumbnailService = TestBed.inject(ThumbnailService);
searchQueryBuilderService = component.queryBuilderService;
component.queryBuilderService.resetToDefaults();
searchQueryBuilderService = fixture.debugElement.injector.get(SearchQueryBuilderService);
searchQueryBuilderService.resetToDefaults();
spyOn(nodeService, 'getNode').and.returnValue(
of(
@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { Component, EventEmitter, Input, OnInit, Output, ViewChild, ViewEncapsulation, OnDestroy, Inject } from '@angular/core';
import { Component, EventEmitter, Input, OnInit, Output, ViewChild, ViewEncapsulation, OnDestroy } from '@angular/core';
import {
HighlightDirective,
UserPreferencesService,
@@ -38,7 +38,6 @@ import { debounceTime, takeUntil } from 'rxjs/operators';
import { CustomResourcesService } from '../document-list/services/custom-resources.service';
import { ShareDataRow } from '../document-list/data/share-data-row.model';
import { Subject } from 'rxjs';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../search/search-query-service.token';
import { SearchQueryBuilderService } from '../search/services/search-query-builder.service';
import { ContentNodeSelectorPanelService } from './content-node-selector-panel.service';
import { NodeEntryEvent } from '../document-list/components/node.event';
@@ -54,12 +53,7 @@ export const defaultValidation = () => true;
styleUrls: ['./content-node-selector-panel.component.scss'],
encapsulation: ViewEncapsulation.None,
host: { class: 'adf-content-node-selector-panel' },
providers: [
{
provide: SEARCH_QUERY_SERVICE_TOKEN,
useClass: SearchQueryBuilderService
}
]
providers: [SearchQueryBuilderService]
})
export class ContentNodeSelectorPanelComponent implements OnInit, OnDestroy {
// eslint-disable-next-line @typescript-eslint/naming-convention
@@ -276,7 +270,7 @@ export class ContentNodeSelectorPanelComponent implements OnInit, OnDestroy {
constructor(
private customResourcesService: CustomResourcesService,
@Inject(SEARCH_QUERY_SERVICE_TOKEN) public queryBuilderService: SearchQueryBuilderService,
private queryBuilderService: SearchQueryBuilderService,
private userPreferencesService: UserPreferencesService,
private nodesApiService: NodesApiService,
private uploadService: UploadService,
@@ -28,7 +28,6 @@ import { of } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module';
import { DocumentListService } from '../document-list/services/document-list.service';
import { DocumentListComponent } from '../document-list/components/document-list.component';
import { TranslateModule } from '@ngx-translate/core';
import { UploadModule } from '../upload';
import { ContentNodeSelectorPanelComponent } from './content-node-selector-panel.component';
import { NodeAction } from '../document-list/models/node-action.enum';
@@ -61,7 +60,7 @@ describe('ContentNodeSelectorComponent', () => {
};
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule, MatDialogModule, UploadModule],
imports: [ContentTestingModule, MatDialogModule, UploadModule],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: data },
{
@@ -24,7 +24,6 @@ import { RenditionService } from '../common/services/rendition.service';
import { SharedLinksApiService } from './services/shared-links-api.service';
import { ShareDialogComponent } from './content-node-share.dialog';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { format, endOfDay } from 'date-fns';
import { By } from '@angular/platform-browser';
import { NodeEntry } from '@alfresco/js-api';
@@ -59,7 +58,7 @@ describe('ShareDialogComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
providers: [
{ provide: NotificationService, useValue: notificationServiceMock },
{
@@ -300,8 +299,9 @@ describe('ShareDialogComponent', () => {
};
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('[data-automation-id="adf-content-share-expiration-field"]'))
.componentInstance.floatLabel).toBe('never');
expect(fixture.debugElement.query(By.css('[data-automation-id="adf-content-share-expiration-field"]')).componentInstance.floatLabel).toBe(
'never'
);
});
it('should not display floating label for public link field', () => {
@@ -311,8 +311,9 @@ describe('ShareDialogComponent', () => {
};
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('[data-automation-id="adf-content-share-public-link-field"]'))
.componentInstance.floatLabel).toBe('never');
expect(fixture.debugElement.query(By.css('[data-automation-id="adf-content-share-public-link-field"]')).componentInstance.floatLabel).toBe(
'never'
);
});
describe('datetimepicker type', () => {
@@ -22,7 +22,6 @@ import { DOCUMENT } from '@angular/common';
import { ContentTestingModule } from '../testing/content.testing.module';
import { CoreModule } from '@alfresco/adf-core';
import { ContentNodeShareModule } from './content-node-share.module';
import { TranslateModule } from '@ngx-translate/core';
@Component({
selector: 'adf-node-share-test-component',
@@ -32,8 +31,8 @@ import { TranslateModule } from '@ngx-translate/core';
#shareRef="adfShare"
[baseShareUrl]="baseShareUrl"
[adf-share]="documentList.selection[0]"
[title]="shareRef.isShared ? 'Shared' : 'Not Shared'">
</button>
[title]="shareRef.isShared ? 'Shared' : 'Not Shared'"
></button>
`
})
class NodeShareTestComponent {
@@ -52,15 +51,8 @@ describe('NodeSharedDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreModule.forRoot(),
ContentTestingModule,
ContentNodeShareModule
],
declarations: [
NodeShareTestComponent
]
imports: [CoreModule.forRoot(), ContentTestingModule, ContentNodeShareModule],
declarations: [NodeShareTestComponent]
});
fixture = TestBed.createComponent(NodeShareTestComponent);
document = TestBed.inject(DOCUMENT);
@@ -17,7 +17,6 @@
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { of, Subject } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module';
import { ContentTypeDialogComponent } from './content-type-dialog.component';
@@ -98,11 +97,7 @@ describe('Content Type Dialog Component', () => {
};
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule,
MatDialogModule
],
imports: [ContentTestingModule, MatDialogModule],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: data },
{
@@ -141,11 +136,14 @@ describe('Content Type Dialog Component', () => {
const confirmMessage = fixture.nativeElement.querySelector('[data-automation-id="content-type-dialog-confirm-message"]');
expect(confirmMessage).not.toBeNull();
expect(confirmMessage.innerText).toBe(data.confirmMessage);
});
it('should complete the select stream Cancel button is clicked', (done) => {
data.select.subscribe(() => { }, () => { }, () => done());
data.select.subscribe(
() => {},
() => {},
() => done()
);
const cancelButton: HTMLButtonElement = fixture.nativeElement.querySelector('#content-type-dialog-actions-cancel');
expect(cancelButton).toBeDefined();
cancelButton.click();
@@ -161,13 +159,16 @@ describe('Content Type Dialog Component', () => {
});
it('should emit true when apply is clicked', (done) => {
data.select.subscribe((value) => {
expect(value).toBe(true);
}, () => { }, () => done());
data.select.subscribe(
(value) => {
expect(value).toBe(true);
},
() => {},
() => done()
);
const applyButton: HTMLButtonElement = fixture.nativeElement.querySelector('#content-type-dialog-apply-button');
expect(applyButton).toBeDefined();
applyButton.click();
fixture.detectChanges();
});
});
@@ -19,14 +19,12 @@ import { CoreTestingModule, IdentityUserModel, InitialUsernamePipe, UserInfoMode
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatMenuModule } from '@angular/material/menu';
import { By, DomSanitizer } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { fakeEcmEditedUser, fakeEcmUser, fakeEcmUserNoImage } from '../common/mocks/ecm-user.service.mock';
import { ContentTestingModule } from '../testing/content.testing.module';
import { ContentUserInfoComponent } from './content-user-info.component';
class FakeSanitizer extends DomSanitizer {
constructor() {
super();
}
@@ -81,12 +79,7 @@ describe('ContentUserInfoComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule,
ContentTestingModule,
MatMenuModule
]
imports: [CoreTestingModule, ContentTestingModule, MatMenuModule]
});
fixture = TestBed.createComponent(ContentUserInfoComponent);
component = fixture.componentInstance;
@@ -111,14 +104,12 @@ describe('ContentUserInfoComponent', () => {
});
describe('when user is logged on ecm', () => {
beforeEach(() => {
component.ecmUser = fakeEcmUser as any;
component.isLoggedIn = true;
});
describe('ui', () => {
it('should show ecm only last name when user first name is null ', async () => {
component.ecmUser = fakeEcmEditedUser as any;
await whenFixtureReady();
@@ -156,7 +147,6 @@ describe('ContentUserInfoComponent', () => {
});
describe('and has image', () => {
beforeEach(async () => {
component.ecmUser = fakeEcmUser as any;
component.isLoggedIn = true;
@@ -199,8 +189,7 @@ describe('ContentUserInfoComponent', () => {
});
describe('and has no image', () => {
beforeEach( async () => {
beforeEach(async () => {
component.ecmUser = fakeEcmUserNoImage as any;
component.isLoggedIn = true;
await whenFixtureReady();
@@ -233,7 +222,6 @@ describe('ContentUserInfoComponent', () => {
});
describe('when identity user is logged in', () => {
beforeEach(() => {
component.ecmUser = fakeEcmUser as any;
component.identityUser = identityUserMock as unknown as IdentityUserModel;
@@ -20,7 +20,6 @@ import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ConfirmDialogComponent } from './confirm.dialog';
import { ContentTestingModule } from '../testing/content.testing.module';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
describe('Confirm Dialog Component', () => {
let fixture: ComponentFixture<ConfirmDialogComponent>;
@@ -39,10 +38,7 @@ describe('Confirm Dialog Component', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
providers: [
{ provide: MatDialogRef, useValue: dialogRef },
{ provide: MAT_DIALOG_DATA, useValue: data }
@@ -70,33 +66,25 @@ describe('Confirm Dialog Component', () => {
});
it('should render the title', () => {
const titleElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-title"]')
);
const titleElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-title"]'));
expect(titleElement).not.toBeNull();
expect(titleElement.nativeElement.innerText).toBe('Fake Title');
});
it('should render the message', () => {
const messageElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-base-message"]')
);
const messageElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-base-message"]'));
expect(messageElement).not.toBeNull();
expect(messageElement.nativeElement.innerText).toBe('Base Message');
});
it('should render the YES label', () => {
const messageElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-confirmation"]')
);
const messageElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-confirmation"]'));
expect(messageElement).not.toBeNull();
expect(messageElement.nativeElement.innerText).toBe('TAKE THIS');
});
it('should render the NO label', () => {
const messageElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-reject"]')
);
const messageElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-reject"]'));
expect(messageElement).not.toBeNull();
expect(messageElement.nativeElement.innerText).toBe('MAYBE NO');
});
@@ -109,57 +97,42 @@ describe('Confirm Dialog Component', () => {
});
it('should render the title', () => {
const titleElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-title"]')
);
const titleElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-title"]'));
expect(titleElement).not.toBeNull();
expect(titleElement.nativeElement.innerText).toBe('Fake Title');
});
it('should render the custom html', () => {
const customElement = fixture.nativeElement.querySelector(
'[data-automation-id="adf-confirm-dialog-custom-content"] div'
);
const customElement = fixture.nativeElement.querySelector('[data-automation-id="adf-confirm-dialog-custom-content"] div');
expect(customElement).not.toBeNull();
expect(customElement.innerText).toBe(
'I am about to do to you what Limp Bizkit did to music in the late 90s.'
);
expect(customElement.innerText).toBe('I am about to do to you what Limp Bizkit did to music in the late 90s.');
});
it('should render the YES label', () => {
const messageElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-confirmation"]')
);
const messageElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-confirmation"]'));
expect(messageElement).not.toBeNull();
expect(messageElement.nativeElement.innerText).toBe('TAKE THIS');
});
it('should render the NO label', () => {
const messageElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-reject"]')
);
const messageElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-reject"]'));
expect(messageElement).not.toBeNull();
expect(messageElement.nativeElement.innerText).toBe('MAYBE NO');
});
});
describe('thirdOptionLabel is given', () => {
it('should NOT render the thirdOption if is thirdOptionLabel is not passed', () => {
component.thirdOptionLabel = undefined;
fixture.detectChanges();
const thirdOptionElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-confirm-all"]')
);
const thirdOptionElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-confirm-all"]'));
expect(thirdOptionElement).toBeFalsy();
});
it('should render the thirdOption if thirdOptionLabel is passed', () => {
component.thirdOptionLabel = 'Yes All';
fixture.detectChanges();
const thirdOptionElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-confirm-dialog-confirm-all"]')
);
const thirdOptionElement = fixture.debugElement.query(By.css('[data-automation-id="adf-confirm-dialog-confirm-all"]'));
expect(thirdOptionElement).not.toBeNull();
expect(thirdOptionElement.nativeElement.innerText.toUpperCase()).toBe('YES ALL');
});
@@ -21,10 +21,8 @@ import { DownloadZipDialogComponent } from './download-zip.dialog';
import { CoreTestingModule } from '@alfresco/adf-core';
import { DownloadZipService } from './services/download-zip.service';
import { Observable } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
describe('DownloadZipDialogComponent', () => {
let fixture: ComponentFixture<DownloadZipDialogComponent>;
let component: DownloadZipDialogComponent;
let element: HTMLElement;
@@ -34,17 +32,12 @@ describe('DownloadZipDialogComponent', () => {
};
const dataMock = {
nodeIds: [
'123'
]
nodeIds: ['123']
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
],
imports: [CoreTestingModule],
providers: [
{ provide: MatDialogRef, useValue: dialogRef },
{ provide: MAT_DIALOG_DATA, useValue: dataMock }
@@ -91,10 +84,13 @@ describe('DownloadZipDialogComponent', () => {
});
it('should call cancelDownload when CANCEL button is clicked', () => {
spyOn(downloadZipService, 'createDownload').and.callFake(() => new Observable((observer) => {
observer.next();
observer.complete();
}));
spyOn(downloadZipService, 'createDownload').and.callFake(
() =>
new Observable((observer) => {
observer.next();
observer.complete();
})
);
fixture.detectChanges();
spyOn(component, 'cancelDownload');
@@ -106,20 +102,26 @@ describe('DownloadZipDialogComponent', () => {
});
it('should call createDownload when component is initialize', () => {
const createDownloadSpy = spyOn(downloadZipService, 'createDownload').and.callFake(() => new Observable((observer) => {
observer.next();
observer.complete();
}));
const createDownloadSpy = spyOn(downloadZipService, 'createDownload').and.callFake(
() =>
new Observable((observer) => {
observer.next();
observer.complete();
})
);
fixture.detectChanges();
expect(createDownloadSpy).toHaveBeenCalled();
});
it('should close dialog when download is completed', () => {
spyOn(downloadZipService, 'createDownload').and.callFake(() => new Observable((observer) => {
observer.next();
observer.complete();
}));
spyOn(downloadZipService, 'createDownload').and.callFake(
() =>
new Observable((observer) => {
observer.next();
observer.complete();
})
);
component.download('fakeUrl', 'fileName');
spyOn(component, 'cancelDownload');
@@ -128,10 +130,13 @@ describe('DownloadZipDialogComponent', () => {
});
it('should close dialog when download is cancelled', () => {
spyOn(downloadZipService, 'createDownload').and.callFake(() => new Observable((observer) => {
observer.next();
observer.complete();
}));
spyOn(downloadZipService, 'createDownload').and.callFake(
() =>
new Observable((observer) => {
observer.next();
observer.complete();
})
);
fixture.detectChanges();
component.download('url', 'filename');
@@ -23,7 +23,6 @@ import { FolderDialogComponent } from './folder.dialog';
import { of, throwError } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
describe('FolderDialogComponent', () => {
let fixture: ComponentFixture<FolderDialogComponent>;
@@ -35,7 +34,7 @@ describe('FolderDialogComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
providers: [{ provide: MatDialogRef, useValue: dialogRef }]
});
dialogRef.close.calls.reset();
@@ -20,7 +20,6 @@ import { TestBed, fakeAsync, tick, flush, ComponentFixture, flushMicrotasks } fr
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { of, throwError } from 'rxjs';
import { delay } from 'rxjs/operators';
import { SiteEntry } from '@alfresco/js-api';
@@ -40,13 +39,8 @@ describe('LibraryDialogComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
providers: [
{ provide: MatDialogRef, useValue: dialogRef }
],
imports: [ContentTestingModule],
providers: [{ provide: MatDialogRef, useValue: dialogRef }],
schemas: [NO_ERRORS_SCHEMA]
});
fixture = TestBed.createComponent(LibraryDialogComponent);
@@ -122,9 +116,7 @@ describe('LibraryDialogComponent', () => {
it('should create site when form is valid', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'createSite').and.returnValue(
of({entry: {id: 'fake-id'}} as SiteEntry).pipe(delay(100))
);
spyOn(sitesService, 'createSite').and.returnValue(of({ entry: { id: 'fake-id' } } as SiteEntry).pipe(delay(100)));
spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
fixture.detectChanges();
@@ -174,9 +166,7 @@ describe('LibraryDialogComponent', () => {
it('should notify when library title is already used', fakeAsync(() => {
spyOn(sitesService, 'getSite').and.returnValue(of(null));
findSitesSpy.and.returnValue(Promise.resolve(
{ list: { entries: [{ entry: { title: 'TEST', id: 'library-id' } }] } }
));
findSitesSpy.and.returnValue(Promise.resolve({ list: { entries: [{ entry: { title: 'TEST', id: 'library-id' } }] } }));
fixture.detectChanges();
component.form.controls.title.setValue('test');
@@ -19,11 +19,9 @@ import { TestBed, fakeAsync, tick, ComponentFixture } from '@angular/core/testin
import { MatDialogRef } from '@angular/material/dialog';
import { NodeLockDialogComponent } from './node-lock.dialog';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { addMinutes } from 'date-fns';
describe('NodeLockDialogComponent', () => {
let fixture: ComponentFixture<NodeLockDialogComponent>;
let component: NodeLockDialogComponent;
let expiryDate: Date;
@@ -34,13 +32,8 @@ describe('NodeLockDialogComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
providers: [
{ provide: MatDialogRef, useValue: dialogRef }
]
imports: [ContentTestingModule],
providers: [{ provide: MatDialogRef, useValue: dialogRef }]
});
fixture = TestBed.createComponent(NodeLockDialogComponent);
component = fixture.componentInstance;
@@ -51,7 +44,6 @@ describe('NodeLockDialogComponent', () => {
});
describe('Node lock dialog component', () => {
beforeEach(() => {
jasmine.clock().mockDate(new Date());
expiryDate = addMinutes(new Date(), 1);
@@ -66,8 +58,7 @@ describe('NodeLockDialogComponent', () => {
['cm:expiryDate']: expiryDate
}
},
onError: () => {
}
onError: () => {}
};
fixture.detectChanges();
});
@@ -20,7 +20,6 @@ import { CoreTestingModule } from '@alfresco/adf-core';
import { ContentService } from '../common/services/content.service';
import { CheckAllowableOperationDirective } from './check-allowable-operation.directive';
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { NodeAllowableOperationSubject } from '../interfaces/node-allowable-operation-subject.interface';
@Component({
@@ -36,10 +35,7 @@ describe('CheckAllowableOperationDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
]
imports: [CoreTestingModule]
});
changeDetectorMock = { detectChanges: () => {} } as ChangeDetectorRef;
});
@@ -126,7 +122,6 @@ describe('CheckAllowableOperationDirective', () => {
});
describe('Angular component as subject', () => {
it('disables decorated component', () => {
const contentService = TestBed.inject(ContentService);
spyOn(contentService, 'hasAllowableOperations').and.returnValue(false);
@@ -19,7 +19,6 @@ import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { LibraryMembershipDirective } from './library-membership.directive';
import { NO_ERRORS_SCHEMA, SimpleChange } from '@angular/core';
import { of, throwError, Subject } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, CoreModule, CoreTestingModule } from '@alfresco/adf-core';
import { ContentDirectiveModule } from './content-directive.module';
import { SitesService } from '../common/services/sites.service';
@@ -38,12 +37,7 @@ describe('LibraryMembershipDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentDirectiveModule,
CoreModule.forRoot(),
CoreTestingModule
],
imports: [ContentDirectiveModule, CoreModule.forRoot(), CoreTestingModule],
schemas: [NO_ERRORS_SCHEMA]
});
@@ -70,7 +64,9 @@ describe('LibraryMembershipDirective', () => {
describe('markMembershipRequest', () => {
beforeEach(() => {
getMembershipSpy = spyOn(directive.sitesApi, 'getSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
getMembershipSpy = spyOn(directive.sitesApi, 'getSiteMembershipRequestForPerson').and.returnValue(
Promise.resolve({ entry: requestedMembershipResponse })
);
});
it('should not check membership requests if no entry is selected', fakeAsync(() => {
@@ -111,8 +107,12 @@ describe('LibraryMembershipDirective', () => {
describe('toggleMembershipRequest', () => {
beforeEach(() => {
mockSupportedVersion = false;
getMembershipSpy = spyOn(directive.sitesApi, 'getSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
addMembershipSpy = spyOn(directive.sitesApi, 'createSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
getMembershipSpy = spyOn(directive.sitesApi, 'getSiteMembershipRequestForPerson').and.returnValue(
Promise.resolve({ entry: requestedMembershipResponse })
);
addMembershipSpy = spyOn(directive.sitesApi, 'createSiteMembershipRequestForPerson').and.returnValue(
Promise.resolve({ entry: requestedMembershipResponse })
);
deleteMembershipSpy = spyOn(directive.sitesApi, 'deleteSiteMembershipRequestForPerson').and.returnValue(Promise.resolve());
});
@@ -20,14 +20,10 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NodeDeleteDirective } from './node-delete.directive';
import { CoreTestingModule } from '@alfresco/adf-core';
import { TranslateModule } from '@ngx-translate/core';
import { ContentDirectiveModule } from './content-directive.module';
@Component({
template: `
<div id="delete-component" [adf-delete]="selection"
(delete)="onDelete()">
</div>`
template: ` <div id="delete-component" [adf-delete]="selection" (delete)="onDelete()"></div>`
})
class TestComponent {
selection = [];
@@ -35,16 +31,11 @@ class TestComponent {
@ViewChild(NodeDeleteDirective, { static: true })
deleteDirective: NodeDeleteDirective;
onDelete() {
}
onDelete() {}
}
@Component({
template: `
<div id="delete-component" [adf-check-allowable-operation]="selection"
[adf-delete]="selection"
(delete)="onDelete($event)">
</div>`
template: ` <div id="delete-component" [adf-check-allowable-operation]="selection" [adf-delete]="selection" (delete)="onDelete($event)"></div>`
})
class TestWithPermissionsComponent {
selection = [];
@@ -56,13 +47,8 @@ class TestWithPermissionsComponent {
}
@Component({
template: `
delete permanent
<div id="delete-permanent"
[adf-delete]="selection"
[permanent]="permanent"
(delete)="onDelete($event)">
</div>`
template: ` delete permanent
<div id="delete-permanent" [adf-delete]="selection" [permanent]="permanent" (delete)="onDelete($event)"></div>`
})
class TestDeletePermanentComponent {
selection = [];
@@ -90,16 +76,8 @@ describe('NodeDeleteDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule,
ContentDirectiveModule
],
declarations: [
TestComponent,
TestWithPermissionsComponent,
TestDeletePermanentComponent
]
imports: [CoreTestingModule, ContentDirectiveModule],
declarations: [TestComponent, TestWithPermissionsComponent, TestDeletePermanentComponent]
});
fixture = TestBed.createComponent(TestComponent);
fixtureWithPermissions = TestBed.createComponent(TestWithPermissionsComponent);
@@ -114,8 +92,9 @@ describe('NodeDeleteDirective', () => {
deleteNodeSpy = spyOn(component.deleteDirective.nodesApi, 'deleteNode').and.returnValue(Promise.resolve());
deleteNodePermanentSpy = spyOn(componentWithPermanentDelete.deleteDirective.nodesApi, 'deleteNode').and.returnValue(Promise.resolve());
purgeDeletedNodePermanentSpy = spyOn(componentWithPermanentDelete.deleteDirective.trashcanApi, 'deleteDeletedNode').and.returnValue(Promise.resolve());
purgeDeletedNodePermanentSpy = spyOn(componentWithPermanentDelete.deleteDirective.trashcanApi, 'deleteDeletedNode').and.returnValue(
Promise.resolve()
);
});
afterEach(() => {
@@ -126,7 +105,6 @@ describe('NodeDeleteDirective', () => {
});
describe('Delete', () => {
it('should do nothing if selection is empty', () => {
component.selection = [];
@@ -141,9 +119,7 @@ describe('NodeDeleteDirective', () => {
fixture.detectChanges();
disposableDelete = component.deleteDirective.delete.subscribe((message) => {
expect(message).toBe(
'CORE.DELETE_NODE.SINGULAR'
);
expect(message).toBe('CORE.DELETE_NODE.SINGULAR');
});
element.nativeElement.click();
@@ -158,9 +134,7 @@ describe('NodeDeleteDirective', () => {
fixture.detectChanges();
disposableDelete = component.deleteDirective.delete.subscribe((message) => {
expect(message).toBe(
'CORE.DELETE_NODE.ERROR_SINGULAR'
);
expect(message).toBe('CORE.DELETE_NODE.ERROR_SINGULAR');
});
element.nativeElement.click();
@@ -169,16 +143,11 @@ describe('NodeDeleteDirective', () => {
});
it('should notify nodes deletion', async () => {
component.selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }
];
component.selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }];
fixture.detectChanges();
disposableDelete = component.deleteDirective.delete.subscribe((message) => {
expect(message).toBe(
'CORE.DELETE_NODE.PLURAL'
);
expect(message).toBe('CORE.DELETE_NODE.PLURAL');
});
element.nativeElement.click();
@@ -189,16 +158,11 @@ describe('NodeDeleteDirective', () => {
it('should notify failed nodes deletion', async () => {
deleteNodeSpy.and.returnValue(Promise.reject(new Error('error')));
component.selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }
];
component.selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }];
fixture.detectChanges();
disposableDelete = component.deleteDirective.delete.subscribe((message) => {
expect(message).toBe(
'CORE.DELETE_NODE.ERROR_PLURAL'
);
expect(message).toBe('CORE.DELETE_NODE.ERROR_PLURAL');
});
element.nativeElement.click();
@@ -215,16 +179,11 @@ describe('NodeDeleteDirective', () => {
}
});
component.selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }
];
component.selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }];
fixture.detectChanges();
disposableDelete = component.deleteDirective.delete.subscribe((message) => {
expect(message).toBe(
'CORE.DELETE_NODE.PARTIAL_SINGULAR'
);
expect(message).toBe('CORE.DELETE_NODE.PARTIAL_SINGULAR');
});
element.nativeElement.click();
@@ -249,9 +208,7 @@ describe('NodeDeleteDirective', () => {
fixture.detectChanges();
disposableDelete = component.deleteDirective.delete.subscribe((message) => {
expect(message).toBe(
'CORE.DELETE_NODE.PARTIAL_PLURAL'
);
expect(message).toBe('CORE.DELETE_NODE.PARTIAL_PLURAL');
});
element.nativeElement.click();
@@ -317,13 +274,10 @@ describe('NodeDeleteDirective', () => {
});
describe('Permanent', () => {
it('should call the api with permanent delete option if permanent directive input is true', () => {
fixtureWithPermanentComponent.detectChanges();
componentWithPermanentDelete.selection = [
{ entry: { id: '1', name: 'name1' } }
];
componentWithPermanentDelete.selection = [{ entry: { id: '1', name: 'name1' } }];
fixtureWithPermanentComponent.detectChanges();
elementWithPermanentDelete.nativeElement.click();
@@ -334,9 +288,7 @@ describe('NodeDeleteDirective', () => {
it('should call the trashcan api if permanent directive input is true and the file is already in the trashcan ', () => {
fixtureWithPermanentComponent.detectChanges();
componentWithPermanentDelete.selection = [
{ entry: { id: '1', name: 'name1', archivedAt: 'archived' } }
];
componentWithPermanentDelete.selection = [{ entry: { id: '1', name: 'name1', archivedAt: 'archived' } }];
fixtureWithPermanentComponent.detectChanges();
elementWithPermanentDelete.nativeElement.click();
@@ -21,7 +21,6 @@ import { MatDialog } from '@angular/material/dialog';
import { Component, DebugElement, ViewChild } from '@angular/core';
import { AlfrescoApiService, CoreTestingModule } from '@alfresco/adf-core';
import { NodeDownloadDirective } from './node-download.directive';
import { TranslateModule } from '@ngx-translate/core';
import { ContentDirectiveModule } from '@alfresco/adf-content-services';
@Component({
@@ -53,14 +52,8 @@ describe('NodeDownloadDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
ContentDirectiveModule,
TranslateModule.forRoot(),
CoreTestingModule
],
declarations: [
TestComponent
]
imports: [ContentDirectiveModule, CoreTestingModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
@@ -108,7 +101,7 @@ describe('NodeDownloadDirective', () => {
}
};
spyOn(contentService, 'getVersionContentUrl');
const node = {entry: {id: 'node-id', isFile: true}};
const node = { entry: { id: 'node-id', isFile: true } };
component.selection = [node];
fixture.detectChanges();
@@ -136,7 +129,7 @@ describe('NodeDownloadDirective', () => {
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: [ 'node-1', 'node-2' ] });
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: ['node-1', 'node-2'] });
});
it('should download selected shared files nodes as zip', () => {
@@ -147,7 +140,7 @@ describe('NodeDownloadDirective', () => {
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: [ 'shared-node-1', 'shared-node-2' ] });
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: ['shared-node-1', 'shared-node-2'] });
});
it('should download selected folder node as zip', () => {
@@ -157,7 +150,7 @@ describe('NodeDownloadDirective', () => {
fixture.detectChanges();
element.triggerEventHandler('click', null);
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: [ 'node-id' ] });
expect(dialogSpy.calls.argsFor(0)[1].data).toEqual({ nodeIds: ['node-id'] });
});
it('should create link element to download file node', () => {
@@ -18,23 +18,18 @@
import { SimpleChange } from '@angular/core';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { NodeFavoriteDirective } from './node-favorite.directive';
import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, CoreTestingModule } from '@alfresco/adf-core';
describe('NodeFavoriteDirective', () => {
let directive: NodeFavoriteDirective;
let alfrescoApiService: AlfrescoApiService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
]
imports: [CoreTestingModule]
});
alfrescoApiService = TestBed.inject(AlfrescoApiService);
directive = new NodeFavoriteDirective( alfrescoApiService);
directive = new NodeFavoriteDirective(alfrescoApiService);
});
describe('selection input change event', () => {
@@ -42,7 +37,7 @@ describe('NodeFavoriteDirective', () => {
spyOn(directive, 'markFavoritesNodes');
const change = new SimpleChange(null, [], true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
expect(directive.markFavoritesNodes).not.toHaveBeenCalledWith();
});
@@ -53,17 +48,14 @@ describe('NodeFavoriteDirective', () => {
let selection = [{ entry: { id: '1', name: 'name1' } }];
let change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
expect(directive.markFavoritesNodes).toHaveBeenCalledWith(selection);
selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }
];
selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }];
change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
expect(directive.markFavoritesNodes).toHaveBeenCalledWith(selection);
});
@@ -71,18 +63,16 @@ describe('NodeFavoriteDirective', () => {
it('should reset favorites if selection is empty', fakeAsync(() => {
spyOn(directive.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve(null));
const selection = [
{ entry: { id: '1', name: 'name1' } }
];
const selection = [{ entry: { id: '1', name: 'name1' } }];
let change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.hasFavorites()).toBe(true);
change = new SimpleChange(null, [], true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.hasFavorites()).toBe(false);
@@ -97,26 +87,20 @@ describe('NodeFavoriteDirective', () => {
});
it('should check each selected node if it is a favorite', fakeAsync(() => {
const selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }
];
const selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }];
const change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(favoritesApiSpy.calls.count()).toBe(2);
}));
it('should not check processed node when another is unselected', fakeAsync(() => {
let selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }
];
let selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }];
let change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.favorites.length).toBe(2);
@@ -124,12 +108,10 @@ describe('NodeFavoriteDirective', () => {
favoritesApiSpy.calls.reset();
selection = [
{ entry: { id: '2', name: 'name2' } }
];
selection = [{ entry: { id: '2', name: 'name2' } }];
change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.favorites.length).toBe(1);
@@ -137,13 +119,10 @@ describe('NodeFavoriteDirective', () => {
}));
it('should not check processed nodes when another is selected', fakeAsync(() => {
let selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }
];
let selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }];
let change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
@@ -152,14 +131,10 @@ describe('NodeFavoriteDirective', () => {
favoritesApiSpy.calls.reset();
selection = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } },
{ entry: { id: '3', name: 'name3' } }
];
selection = [{ entry: { id: '1', name: 'name1' } }, { entry: { id: '2', name: 'name2' } }, { entry: { id: '3', name: 'name3' } }];
change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.favorites.length).toBe(3);
@@ -183,7 +158,7 @@ describe('NodeFavoriteDirective', () => {
it('should not perform action if favorites collection is empty', fakeAsync(() => {
const change = new SimpleChange(null, [], true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
directive.toggleFavorite();
@@ -225,10 +200,7 @@ describe('NodeFavoriteDirective', () => {
it('should call removeFavoriteSite() if all are favorites', () => {
removeFavoriteSpy.and.returnValue(Promise.resolve());
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: true } },
{ entry: { id: '2', name: 'name2', isFavorite: true } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: true } }, { entry: { id: '2', name: 'name2', isFavorite: true } }];
directive.toggleFavorite();
@@ -239,9 +211,7 @@ describe('NodeFavoriteDirective', () => {
removeFavoriteSpy.and.returnValue(Promise.resolve());
spyOn(directive.toggle, 'emit');
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: true } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: true } }];
directive.toggleFavorite();
tick();
@@ -253,9 +223,7 @@ describe('NodeFavoriteDirective', () => {
addFavoriteSpy.and.returnValue(Promise.resolve());
spyOn(directive.toggle, 'emit');
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: false } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: false } }];
directive.toggleFavorite();
tick();
@@ -268,9 +236,7 @@ describe('NodeFavoriteDirective', () => {
removeFavoriteSpy.and.returnValue(Promise.reject(error));
spyOn(directive.error, 'emit');
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: true } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: true } }];
directive.toggleFavorite();
tick();
@@ -283,9 +249,7 @@ describe('NodeFavoriteDirective', () => {
addFavoriteSpy.and.returnValue(Promise.reject(error));
spyOn(directive.error, 'emit');
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: false } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: false } }];
directive.toggleFavorite();
tick();
@@ -296,9 +260,7 @@ describe('NodeFavoriteDirective', () => {
it('should set isFavorites items to false', fakeAsync(() => {
removeFavoriteSpy.and.returnValue(Promise.resolve());
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: true } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: true } }];
directive.toggleFavorite();
tick();
@@ -309,9 +271,7 @@ describe('NodeFavoriteDirective', () => {
it('should set isFavorites items to true', fakeAsync(() => {
addFavoriteSpy.and.returnValue(Promise.resolve());
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: false } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: false } }];
directive.toggleFavorite();
tick();
@@ -321,16 +281,13 @@ describe('NodeFavoriteDirective', () => {
});
describe('getFavorite()', () => {
it('should not hit server when using 6.x api', fakeAsync(() => {
spyOn(directive.favoritesApi, 'getFavorite').and.callThrough();
const selection = [
{ entry: { id: '1', name: 'name1', isFavorite: true } }
];
const selection = [{ entry: { id: '1', name: 'name1', isFavorite: true } }];
const change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.favorites[0].entry.isFavorite).toBe(true);
@@ -340,12 +297,10 @@ describe('NodeFavoriteDirective', () => {
it('should process node as favorite', fakeAsync(() => {
spyOn(directive.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve(null));
const selection = [
{ entry: { id: '1', name: 'name1' } }
];
const selection = [{ entry: { id: '1', name: 'name1' } }];
const change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.favorites[0].entry.isFavorite).toBe(true);
@@ -354,12 +309,10 @@ describe('NodeFavoriteDirective', () => {
it('should not process node as favorite', fakeAsync(() => {
spyOn(directive.favoritesApi, 'getFavorite').and.returnValue(Promise.reject(new Error('error')));
const selection = [
{ entry: { id: '1', name: 'name1' } }
];
const selection = [{ entry: { id: '1', name: 'name1' } }];
const change = new SimpleChange(null, selection, true);
directive.ngOnChanges({selection: change});
directive.ngOnChanges({ selection: change });
tick();
expect(directive.favorites[0].entry.isFavorite).toBe(false);
@@ -376,10 +329,7 @@ describe('NodeFavoriteDirective', () => {
});
it('should return false when some are not favorite', () => {
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: true } },
{ entry: { id: '2', name: 'name2', isFavorite: false } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: true } }, { entry: { id: '2', name: 'name2', isFavorite: false } }];
const hasFavorites = directive.hasFavorites();
@@ -387,10 +337,7 @@ describe('NodeFavoriteDirective', () => {
});
it('return true when all are favorite', () => {
directive.favorites = [
{ entry: { id: '1', name: 'name1', isFavorite: true } },
{ entry: { id: '2', name: 'name2', isFavorite: true } }
];
directive.favorites = [{ entry: { id: '1', name: 'name1', isFavorite: true } }, { entry: { id: '2', name: 'name2', isFavorite: true } }];
const hasFavorites = directive.hasFavorites();
@@ -22,7 +22,6 @@ import { NodeLockDirective } from './node-lock.directive';
import { Node } from '@alfresco/js-api';
import { ContentNodeDialogService } from '../content-node-selector/content-node-dialog.service';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
const fakeNode = {
id: 'fake',
@@ -45,13 +44,8 @@ describe('NodeLock Directive', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
declarations: [
TestComponent
]
imports: [ContentTestingModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
@@ -19,15 +19,11 @@ import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NodeRestoreDirective } from './node-restore.directive';
import { TranslateModule } from '@ngx-translate/core';
import { TranslationService, CoreTestingModule } from '@alfresco/adf-core';
import { ContentDirectiveModule } from './content-directive.module';
@Component({
template: `
<div [adf-restore]="selection"
(restore)="doneSpy()">
</div>`
template: ` <div [adf-restore]="selection" (restore)="doneSpy()"></div>`
})
class TestComponent {
selection = [];
@@ -46,14 +42,8 @@ describe('NodeRestoreDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule,
ContentDirectiveModule
],
declarations: [
TestComponent
]
imports: [CoreTestingModule, ContentDirectiveModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
@@ -63,9 +53,11 @@ describe('NodeRestoreDirective', () => {
trashcanApi = directiveInstance['trashcanApi'];
restoreNodeSpy = spyOn(trashcanApi, 'restoreDeletedNode').and.returnValue(Promise.resolve());
spyOn(trashcanApi, 'listDeletedNodes').and.returnValue(Promise.resolve({
list: { entries: [] }
}));
spyOn(trashcanApi, 'listDeletedNodes').and.returnValue(
Promise.resolve({
list: { entries: [] }
})
);
translationService = TestBed.inject(TranslationService);
spyOn(translationService, 'instant').and.callFake((key) => key);
@@ -146,7 +138,6 @@ describe('NodeRestoreDirective', () => {
});
describe('notification', () => {
it('should notify on multiple fails', (done) => {
const error = { message: '{ "error": {} }' };
@@ -184,9 +175,7 @@ describe('NodeRestoreDirective', () => {
restoreNodeSpy.and.returnValue(Promise.reject(error));
component.selection = [
{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }
];
component.selection = [{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }];
fixture.detectChanges();
element.triggerEventHandler('click', null);
@@ -203,9 +192,7 @@ describe('NodeRestoreDirective', () => {
done();
});
component.selection = [
{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }
];
component.selection = [{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }];
fixture.detectChanges();
element.triggerEventHandler('click', null);
@@ -221,16 +208,13 @@ describe('NodeRestoreDirective', () => {
done();
});
component.selection = [
{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }
];
component.selection = [{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }];
fixture.detectChanges();
element.triggerEventHandler('click', null);
});
it('should notify success when restore multiple nodes', (done) => {
directiveInstance.restore.subscribe((event: any) => {
expect(event.message).toEqual('CORE.RESTORE_NODE.PLURAL');
@@ -246,7 +230,6 @@ describe('NodeRestoreDirective', () => {
fixture.detectChanges();
element.triggerEventHandler('click', null);
});
it('should notify success on restore selected node', (done) => {
@@ -256,13 +239,10 @@ describe('NodeRestoreDirective', () => {
done();
});
component.selection = [
{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }
];
component.selection = [{ entry: { id: '1', name: 'name1', path: ['somewhere-over-the-rainbow'] } }];
fixture.detectChanges();
element.triggerEventHandler('click', null);
});
});
});
});
@@ -21,22 +21,17 @@ import { ContentActionModel } from './../../models/content-action.model';
import { DocumentListComponent } from './../document-list.component';
import { ContentActionListComponent } from './content-action-list.component';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('ContentColumnList', () => {
let documentList: DocumentListComponent;
let actionList: ContentActionListComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
documentList = (TestBed.createComponent(DocumentListComponent).componentInstance as DocumentListComponent);
documentList = TestBed.createComponent(DocumentListComponent).componentInstance as DocumentListComponent;
actionList = new ContentActionListComponent(documentList);
});
@@ -26,7 +26,6 @@ import { DocumentListComponent } from './../document-list.component';
import { ContentActionListComponent } from './content-action-list.component';
import { ContentActionComponent } from './content-action.component';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { ContentService } from '../../../common/services/content.service';
describe('ContentAction', () => {
@@ -40,10 +39,7 @@ describe('ContentAction', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
contentService = TestBed.inject(ContentService);
@@ -51,7 +47,7 @@ describe('ContentAction', () => {
documentActions = new DocumentActionsService(nodeActionsService, null, null, null);
folderActions = new FolderActionsService(nodeActionsService, null, contentService, null);
documentList = (TestBed.createComponent(DocumentListComponent).componentInstance as DocumentListComponent);
documentList = TestBed.createComponent(DocumentListComponent).componentInstance as DocumentListComponent;
actionList = new ContentActionListComponent(documentList);
});
@@ -246,7 +242,7 @@ describe('ContentAction', () => {
expect(action.getSystemHandler('unknown', 'name')).toBeNull();
expect(folderActions.getHandler).not.toHaveBeenCalled();
expect(documentActions.getHandler).not.toHaveBeenCalled();
});
});
it('should wire model with custom event handler', (done) => {
const action = new ContentActionComponent(actionList, documentActions, folderActions);
@@ -54,7 +54,6 @@ import { ContentTestingModule } from '../../testing/content.testing.module';
import { FavoritePaging, NodeEntry, NodePaging, Node, FavoritePagingList } from '@alfresco/js-api';
import { By } from '@angular/platform-browser';
import { DocumentListModule } from '../document-list.module';
import { TranslateModule } from '@ngx-translate/core';
import { ShareDataRow } from '../data/share-data-row.model';
import { DocumentLoaderNode } from '../models/document-folder.model';
import { matIconRegistryMock } from '../../testing/mat-icon-registry-mock';
@@ -89,7 +88,7 @@ describe('DocumentList', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [{ provide: MatDialog, useValue: mockDialog }]
});
@@ -896,7 +895,10 @@ describe('DocumentList', () => {
});
it('should emit new columns order on columnOrderChanged', () => {
const newColumnsOrder = [{key: 'key', type: 'text', id: 'tag'}, {key: 'key1', type: 'text', id: 'name'}];
const newColumnsOrder = [
{ key: 'key', type: 'text', id: 'tag' },
{ key: 'key1', type: 'text', id: 'name' }
];
spyOn(documentList.columnsOrderChanged, 'emit');
spyOn(documentList, 'onColumnOrderChange').and.callThrough();
documentList.dataTable.columnOrderChanged.emit(newColumnsOrder as DataColumn[]);
@@ -906,21 +908,27 @@ describe('DocumentList', () => {
});
it('should emit new columns width on columnsWidthChanged', () => {
const newColumnWidth = [{key: 'key', type: 'text', id: 'tag', width: 65}, {key: 'key1', type: 'text', id: 'name', width: 77}];
const newColumnWidth = [
{ key: 'key', type: 'text', id: 'tag', width: 65 },
{ key: 'key1', type: 'text', id: 'name', width: 77 }
];
spyOn(documentList.columnsWidthChanged, 'emit');
spyOn(documentList, 'onColumnsWidthChange').and.callThrough();
documentList.dataTable.columnsWidthChanged.emit(newColumnWidth as DataColumn[]);
expect(documentList.onColumnsWidthChange).toHaveBeenCalledWith(newColumnWidth);
expect(documentList.columnsWidthChanged.emit).toHaveBeenCalledWith({tag: 65, name: 77});
expect(documentList.columnsWidthChanged.emit).toHaveBeenCalledWith({ tag: 65, name: 77 });
});
it('should emit new columns visibility', () => {
const newColumnsVisibility = [{key: 'key', type: 'text', id: 'tag', isHidden: true}, {key: 'key1', type: 'text', id: 'name'}];
const newColumnsVisibility = [
{ key: 'key', type: 'text', id: 'tag', isHidden: true },
{ key: 'key1', type: 'text', id: 'name' }
];
spyOn(documentList.columnsVisibilityChanged, 'emit');
documentList.onColumnsVisibilityChange(newColumnsVisibility as DataColumn[]);
expect(documentList.columnsVisibilityChanged.emit).toHaveBeenCalledWith({tag: false});
expect(documentList.columnsVisibilityChanged.emit).toHaveBeenCalledWith({ tag: false });
});
it('should perform folder navigation on single click', () => {
@@ -1863,7 +1871,7 @@ describe('DocumentListComponent rendering', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [CustomTemplateComponent],
imports: [TranslateModule.forRoot(), ContentTestingModule, DataTableModule, DocumentListModule]
imports: [ContentTestingModule, DataTableModule, DocumentListModule]
});
fixture = TestBed.createComponent(CustomTemplateComponent);
component = fixture.componentInstance;
@@ -21,7 +21,6 @@ import { FileAutoDownloadComponent } from './file-auto-download.component';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { By } from '@angular/platform-browser';
import { CoreTestingModule } from '@alfresco/adf-core';
import { TranslateModule } from '@ngx-translate/core';
import { NO_ERRORS_SCHEMA } from '@angular/core';
const mockDialog = {
@@ -36,10 +35,7 @@ describe('FileAutoDownloadComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [FileAutoDownloadComponent],
imports: [
TranslateModule.forRoot(),
CoreTestingModule
],
imports: [CoreTestingModule],
schemas: [NO_ERRORS_SCHEMA],
providers: [
{ provide: MatDialogRef, useValue: mockDialog },
@@ -17,13 +17,11 @@
import { Subject, BehaviorSubject } from 'rxjs';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { DataTableComponent, DataSorting } from '@alfresco/adf-core';
import { SearchService } from '../../../search/services/search.service';
import { SearchService } from '../../../search/services/search.service';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { SimpleChange } from '@angular/core';
import { SearchHeaderQueryBuilderService } from './../../../search/services/search-header-query-builder.service';
import { SEARCH_QUERY_SERVICE_TOKEN } from './../../../search/search-query-service.token';
import { DocumentListComponent } from './../document-list.component';
import { FilterHeaderComponent } from './filter-header.component';
import { Pagination } from '@alfresco/js-api';
@@ -50,14 +48,10 @@ describe('FilterHeaderComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
providers: [
{ provide: ADF_DOCUMENT_PARENT_COMPONENT, useExisting: DocumentListComponent },
{ provide: SearchService, useValue: searchMock },
{ provide: SEARCH_QUERY_SERVICE_TOKEN, useClass: SearchHeaderQueryBuilderService },
{ provide: DocumentListComponent, useValue: documentListMock },
DataTableComponent
]
@@ -149,5 +143,4 @@ describe('FilterHeaderComponent', () => {
fixture.detectChanges();
fixture.whenStable();
});
});
@@ -17,7 +17,6 @@
import { Component, Inject, OnInit, OnChanges, SimpleChanges, Input, Output, EventEmitter, OnDestroy } from '@angular/core';
import { PaginationModel, DataSorting } from '@alfresco/adf-core';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../../search/search-query-service.token';
import { SearchHeaderQueryBuilderService } from '../../../search/services/search-header-query-builder.service';
import { FilterSearch } from './../../../search/models/filter-search.interface';
import { Subject } from 'rxjs';
@@ -26,8 +25,7 @@ import { ADF_DOCUMENT_PARENT_COMPONENT } from '../document-list.token';
@Component({
selector: 'adf-filter-header',
templateUrl: './filter-header.component.html',
providers: [{ provide: SEARCH_QUERY_SERVICE_TOKEN, useClass: SearchHeaderQueryBuilderService }]
templateUrl: './filter-header.component.html'
})
export class FilterHeaderComponent implements OnInit, OnChanges, OnDestroy {
/** (optional) Initial filter value to sort . */
@@ -45,10 +43,7 @@ export class FilterHeaderComponent implements OnInit, OnChanges, OnDestroy {
isFilterServiceActive: boolean;
private onDestroy$ = new Subject<boolean>();
constructor(
@Inject(ADF_DOCUMENT_PARENT_COMPONENT) private documentList: any,
@Inject(SEARCH_QUERY_SERVICE_TOKEN) private searchFilterQueryBuilder: SearchHeaderQueryBuilderService
) {
constructor(@Inject(ADF_DOCUMENT_PARENT_COMPONENT) private documentList: any, private searchFilterQueryBuilder: SearchHeaderQueryBuilderService) {
this.isFilterServiceActive = this.searchFilterQueryBuilder.isFilterServiceActive();
}
@@ -19,7 +19,6 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { LibraryNameColumnComponent } from './library-name-column.component';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('LibraryNameColumnComponent', () => {
let fixture: ComponentFixture<LibraryNameColumnComponent>;
@@ -28,10 +27,7 @@ describe('LibraryNameColumnComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
});
node = {
@@ -70,9 +66,7 @@ describe('LibraryNameColumnComponent', () => {
it('sets title with id when duplicate nodes title exists in list', () => {
node.title = 'title';
const rows = [
{ node: { entry: { id: 'some-id', title: 'title' } } }
] as any[];
const rows = [{ node: { entry: { id: 'some-id', title: 'title' } } }] as any[];
const title = component.makeLibraryTitle(node, rows);
expect(title).toContain('nodeId');
@@ -19,7 +19,6 @@ import { LibraryRoleColumnComponent } from './library-role-column.component';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('LibraryRoleColumnComponent', () => {
let fixture: ComponentFixture<LibraryRoleColumnComponent>;
@@ -27,10 +26,7 @@ describe('LibraryRoleColumnComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
});
fixture = TestBed.createComponent(LibraryRoleColumnComponent);
@@ -43,7 +39,7 @@ describe('LibraryRoleColumnComponent', () => {
};
let value = '';
component.displayText$.subscribe((val) => value = val);
component.displayText$.subscribe((val) => (value = val));
fixture.detectChanges();
expect(value).toBe('LIBRARY.ROLE.MANAGER');
@@ -55,7 +51,7 @@ describe('LibraryRoleColumnComponent', () => {
};
let value = '';
component.displayText$.subscribe((val) => value = val);
component.displayText$.subscribe((val) => (value = val));
fixture.detectChanges();
expect(value).toBe('LIBRARY.ROLE.COLLABORATOR');
@@ -67,7 +63,7 @@ describe('LibraryRoleColumnComponent', () => {
};
let value = '';
component.displayText$.subscribe((val) => value = val);
component.displayText$.subscribe((val) => (value = val));
fixture.detectChanges();
expect(value).toBe('LIBRARY.ROLE.CONTRIBUTOR');
@@ -79,7 +75,7 @@ describe('LibraryRoleColumnComponent', () => {
};
let value = '';
component.displayText$.subscribe((val) => value = val);
component.displayText$.subscribe((val) => (value = val));
fixture.detectChanges();
expect(value).toBe('LIBRARY.ROLE.CONSUMER');
@@ -91,7 +87,7 @@ describe('LibraryRoleColumnComponent', () => {
};
let value = '';
component.displayText$.subscribe((val) => value = val);
component.displayText$.subscribe((val) => (value = val));
fixture.detectChanges();
expect(value).toBe('LIBRARY.ROLE.NONE');
@@ -17,7 +17,6 @@
import { NameColumnComponent } from './name-column.component';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { skip } from 'rxjs/operators';
@@ -28,17 +27,14 @@ describe('NameColumnComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(NameColumnComponent);
context = {
row: {
node: {entry: {}},
node: { entry: {} },
getValue: (key) => key
}
};
@@ -48,24 +44,20 @@ describe('NameColumnComponent', () => {
});
it('should set the display value based on default key', (done) => {
component.displayText$
.pipe(skip(1))
.subscribe(value => {
expect(value).toBe('name');
done();
});
component.displayText$.pipe(skip(1)).subscribe((value) => {
expect(value).toBe('name');
done();
});
component.ngOnInit();
});
it('should set the display value based on the custom key', (done) => {
component.key = 'title';
component.displayText$
.pipe(skip(1))
.subscribe(value => {
expect(value).toBe('title');
done();
});
component.displayText$.pipe(skip(1)).subscribe((value) => {
expect(value).toBe('title');
done();
});
component.ngOnInit();
});
@@ -21,20 +21,15 @@ import { ERR_OBJECT_NOT_FOUND, ShareDataRow } from './share-data-row.model';
import { ERR_COL_NOT_FOUND, ERR_ROW_NOT_FOUND, ShareDataTableAdapter } from './share-datatable-adapter';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ContentService } from '../../common/services/content.service';
describe('ShareDataTableAdapter', () => {
let thumbnailService: ThumbnailService;
let contentService: ContentService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
const imageUrl: string = 'http://<addresss>';
@@ -320,9 +315,9 @@ describe('ShareDataTableAdapter', () => {
]);
const sorted = adapter.getRows();
expect((sorted[0]).node).toBe(folder);
expect((sorted[1]).node).toBe(file1);
expect((sorted[2]).node).toBe(file2);
expect(sorted[0].node).toBe(folder);
expect(sorted[1].node).toBe(file1);
expect(sorted[2].node).toBe(file2);
});
it('should sort by dates up to ms', () => {
@@ -335,20 +330,17 @@ describe('ShareDataTableAdapter', () => {
const col = { key: 'dateProp' } as DataColumn;
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]);
adapter.setRows([
new ShareDataRow(file2, contentService, null),
new ShareDataRow(file1, contentService, null)
]);
adapter.setRows([new ShareDataRow(file2, contentService, null), new ShareDataRow(file1, contentService, null)]);
adapter.sort('dateProp', 'asc');
const rows = adapter.getRows();
expect((rows[0]).node).toBe(file1);
expect((rows[1]).node).toBe(file2);
expect(rows[0].node).toBe(file1);
expect(rows[1].node).toBe(file2);
adapter.sort('dateProp', 'desc');
expect((rows[0]).node).toBe(file2);
expect((rows[1]).node).toBe(file1);
expect(rows[0].node).toBe(file2);
expect(rows[1].node).toBe(file1);
});
it('should sort by file size', () => {
@@ -375,16 +367,16 @@ describe('ShareDataTableAdapter', () => {
adapter.sort('content.sizeInBytes', 'asc');
const rows = adapter.getRows();
expect((rows[0]).node).toBe(file1);
expect((rows[1]).node).toBe(file2);
expect((rows[2]).node).toBe(file3);
expect((rows[3]).node).toBe(file4);
expect(rows[0].node).toBe(file1);
expect(rows[1].node).toBe(file2);
expect(rows[2].node).toBe(file3);
expect(rows[3].node).toBe(file4);
adapter.sort('content.sizeInBytes', 'desc');
expect((rows[0]).node).toBe(file4);
expect((rows[1]).node).toBe(file3);
expect((rows[2]).node).toBe(file2);
expect((rows[3]).node).toBe(file1);
expect(rows[0].node).toBe(file4);
expect(rows[1].node).toBe(file3);
expect(rows[2].node).toBe(file2);
expect(rows[3].node).toBe(file1);
});
it('should sort by name', () => {
@@ -410,24 +402,23 @@ describe('ShareDataTableAdapter', () => {
adapter.sort('name', 'asc');
const rows = adapter.getRows();
expect((rows[0]).node).toBe(file5);
expect((rows[1]).node).toBe(file6);
expect((rows[2]).node).toBe(file1);
expect((rows[3]).node).toBe(file2);
expect((rows[4]).node).toBe(file4);
expect((rows[5]).node).toBe(file3);
expect(rows[0].node).toBe(file5);
expect(rows[1].node).toBe(file6);
expect(rows[2].node).toBe(file1);
expect(rows[3].node).toBe(file2);
expect(rows[4].node).toBe(file4);
expect(rows[5].node).toBe(file3);
adapter.sort('name', 'desc');
expect((rows[0]).node).toBe(file3);
expect((rows[1]).node).toBe(file4);
expect((rows[2]).node).toBe(file2);
expect((rows[3]).node).toBe(file1);
expect((rows[4]).node).toBe(file6);
expect((rows[5]).node).toBe(file5);
expect(rows[0].node).toBe(file3);
expect(rows[1].node).toBe(file4);
expect(rows[2].node).toBe(file2);
expect(rows[3].node).toBe(file1);
expect(rows[4].node).toBe(file6);
expect(rows[5].node).toBe(file5);
});
describe('ShareDataRow', () => {
it('should wrap node', () => {
const file = new FileNode();
const row = new ShareDataRow(file, contentService, null);
@@ -492,12 +483,15 @@ describe('ShareDataTableAdapter', () => {
it('should return the row of the requested node id', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const fakeFiles = [new FileNode('fake-file-1', 'text/plain', 'fake-node-id-1'), new FileNode('fake-file-2', 'text/plain', 'fake-node-id-2')];
const fakeFiles = [
new FileNode('fake-file-1', 'text/plain', 'fake-node-id-1'),
new FileNode('fake-file-2', 'text/plain', 'fake-node-id-2')
];
const fakeShareDataRows = [new ShareDataRow(fakeFiles[0], contentService, null), new ShareDataRow(fakeFiles[1], contentService, null)];
adapter.setRows(fakeShareDataRows);
expect(adapter.getRowByNodeId('fake-node-id-1')).toEqual(fakeShareDataRows[0]);
expect(adapter.getRowByNodeId('fake-node-id-2')).toEqual(fakeShareDataRows[1]);
});
});
});
});
@@ -22,20 +22,15 @@ import { DocumentListService } from './document-list.service';
import { of } from 'rxjs';
import { TestBed } from '@angular/core/testing';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { PermissionModel } from '../models/permissions.model';
describe('DocumentActionsService', () => {
let service: DocumentActionsService;
let documentListService: DocumentListService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
documentListService = TestBed.inject(DocumentListService);
service = TestBed.inject(DocumentActionsService);
@@ -99,7 +94,7 @@ describe('DocumentActionsService', () => {
spyOn(documentListService, 'deleteNode').and.returnValue(of(true));
let lastValue: PermissionModel;
service.permissionEvent.subscribe((permission) => lastValue = permission);
service.permissionEvent.subscribe((permission) => (lastValue = permission));
const file = new FileNode();
service.getHandler('delete')(file);
@@ -107,7 +102,7 @@ describe('DocumentActionsService', () => {
expect(lastValue).toBeDefined();
expect(lastValue.type).toEqual('content');
expect(lastValue.action).toEqual('delete');
});
});
it('should call the error on the returned Observable if there are no permissions', async () => {
spyOn(documentListService, 'deleteNode').and.returnValue(of(true));
@@ -138,7 +133,7 @@ describe('DocumentActionsService', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
let lastValue: PermissionModel;
service.permissionEvent.subscribe((permissionBack) => lastValue = permissionBack);
service.permissionEvent.subscribe((permissionBack) => (lastValue = permissionBack));
const permission = 'delete';
const file = new FileNode();
@@ -207,7 +202,7 @@ describe('DocumentActionsService', () => {
it('should emit success event upon node deletion', () => {
let lastValue: string;
service.success.subscribe((message) => lastValue = message);
service.success.subscribe((message) => (lastValue = message));
spyOn(documentListService, 'deleteNode').and.returnValue(of(true));
const target = jasmine.createSpyObj('obj', ['reload']);
@@ -217,5 +212,5 @@ describe('DocumentActionsService', () => {
fileWithPermission.entry.allowableOperations = [permission];
service.getHandler('delete')(fileWithPermission, target, permission);
expect(lastValue).toEqual('CORE.DELETE_NODE.SINGULAR');
});
});
});
@@ -18,54 +18,57 @@
import { DocumentListService } from './document-list.service';
import { fakeAsync, TestBed } from '@angular/core/testing';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
declare let jasmine: any;
describe('DocumentListService', () => {
let service: DocumentListService;
const fakeFolder = {
list: {
pagination: { count: 1, hasMoreItems: false, totalItems: 1, skipCount: 0, maxItems: 20 },
entries: [{
entry: {
createdAt: '2016-12-06T13:03:14.880+0000',
path: {
name: '/Company Home/Sites/swsdp/documentLibrary/empty',
isComplete: true,
elements: [{
id: 'ed7ab80e-b398-4bed-b38d-139ae4cc592a',
name: 'Company Home'
}, { id: '99e1368f-e816-47fc-a8bf-3b358feaf31e', name: 'Sites' }, {
id: 'b4cff62a-664d-4d45-9302-98723eac1319',
name: 'swsdp'
}, {
id: '8f2105b4-daaf-4874-9e8a-2152569d109b',
name: 'documentLibrary'
}, { id: '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32', name: 'empty' }]
},
isFolder: true,
isFile: false,
createdByUser: { id: 'admin', displayName: 'Administrator' },
modifiedAt: '2016-12-06T13:03:14.880+0000',
modifiedByUser: { id: 'admin', displayName: 'Administrator' },
name: 'fake-name',
id: 'aac546f6-1525-46ff-bf6b-51cb85f3cda7',
nodeType: 'cm:folder',
parentId: '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32'
entries: [
{
entry: {
createdAt: '2016-12-06T13:03:14.880+0000',
path: {
name: '/Company Home/Sites/swsdp/documentLibrary/empty',
isComplete: true,
elements: [
{
id: 'ed7ab80e-b398-4bed-b38d-139ae4cc592a',
name: 'Company Home'
},
{ id: '99e1368f-e816-47fc-a8bf-3b358feaf31e', name: 'Sites' },
{
id: 'b4cff62a-664d-4d45-9302-98723eac1319',
name: 'swsdp'
},
{
id: '8f2105b4-daaf-4874-9e8a-2152569d109b',
name: 'documentLibrary'
},
{ id: '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32', name: 'empty' }
]
},
isFolder: true,
isFile: false,
createdByUser: { id: 'admin', displayName: 'Administrator' },
modifiedAt: '2016-12-06T13:03:14.880+0000',
modifiedByUser: { id: 'admin', displayName: 'Administrator' },
name: 'fake-name',
id: 'aac546f6-1525-46ff-bf6b-51cb85f3cda7',
nodeType: 'cm:folder',
parentId: '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32'
}
}
}]
]
}
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
service = TestBed.inject(DocumentListService);
jasmine.Ajax.install();
@@ -76,16 +79,14 @@ describe('DocumentListService', () => {
});
it('should return the folder info', fakeAsync(() => {
service.getFolder('/fake-root/fake-name').subscribe(
(res) => {
expect(res).toBeDefined();
expect(res.list).toBeDefined();
expect(res.list.entries).toBeDefined();
expect(res.list.entries.length).toBe(1);
expect(res.list.entries[0].entry.isFolder).toBeTruthy();
expect(res.list.entries[0].entry.name).toEqual('fake-name');
}
);
service.getFolder('/fake-root/fake-name').subscribe((res) => {
expect(res).toBeDefined();
expect(res.list).toBeDefined();
expect(res.list.entries).toBeDefined();
expect(res.list.entries.length).toBe(1);
expect(res.list.entries[0].entry.isFolder).toBeTruthy();
expect(res.list.entries[0].entry.name).toEqual('fake-name');
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
@@ -135,18 +136,15 @@ describe('DocumentListService', () => {
service.getFolderNode('test-id', ['allowableOperations']);
expect(spyGetNodeInfo).toHaveBeenCalledWith('test-id', {
includeSource: true,
include: ['path', 'properties', 'allowableOperations', 'permissions', 'aspectNames']
}
);
includeSource: true,
include: ['path', 'properties', 'allowableOperations', 'permissions', 'aspectNames']
});
});
it('should delete the folder', fakeAsync(() => {
service.deleteNode('fake-id').subscribe(
(res) => {
expect(res).toBe('');
}
);
service.deleteNode('fake-id').subscribe((res) => {
expect(res).toBe('');
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 204,
@@ -23,20 +23,15 @@ import { ContentActionHandler } from '../models/content-action.model';
import { DocumentListService } from './document-list.service';
import { FolderActionsService } from './folder-actions.service';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { PermissionModel } from '../models/permissions.model';
describe('FolderActionsService', () => {
let service: FolderActionsService;
let documentListService: DocumentListService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
const appConfig: AppConfigService = TestBed.inject(AppConfigService);
appConfig.config.ecmHost = 'http://localhost:9876/ecm';
@@ -92,20 +87,23 @@ describe('FolderActionsService', () => {
spyOn(documentListService, 'deleteNode').and.callThrough();
let lastValue: PermissionModel;
service.permissionEvent.subscribe((permission) => lastValue = permission);
service.permissionEvent.subscribe((permission) => (lastValue = permission));
const folder = new FolderNode();
service.getHandler('delete')(folder);
expect(lastValue).toBeDefined();
expect(lastValue.type).toEqual('folder');
expect(lastValue.action).toEqual('delete');
});
});
it('should delete the folder node if there is the delete permission', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
const permission = 'delete';
const folder = new FolderNode();
@@ -118,13 +116,16 @@ describe('FolderActionsService', () => {
});
it('should not delete the folder node if there is no delete permission', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
let lastValue: PermissionModel;
service.permissionEvent.subscribe((permission) => lastValue = permission);
service.permissionEvent.subscribe((permission) => (lastValue = permission));
const folder = new FolderNode();
const folderWithPermission: any = folder;
@@ -136,10 +137,13 @@ describe('FolderActionsService', () => {
});
it('should call the error on the returned Observable if there is no delete permission', async () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
const folder = new FolderNode();
const folderWithPermission: any = folder;
@@ -151,13 +155,16 @@ describe('FolderActionsService', () => {
expect(error.message).toEqual('No permission to delete');
}
});
});
});
it('should delete the folder node if there is the delete and others permission ', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
const permission = 'delete';
const folder = new FolderNode();
@@ -169,10 +176,13 @@ describe('FolderActionsService', () => {
});
it('should support deletion only folder node', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
const permission = 'delete';
const file = new FileNode();
@@ -187,10 +197,13 @@ describe('FolderActionsService', () => {
});
it('should require node id to delete', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
const folder = new FolderNode();
folder.entry.id = null;
@@ -200,10 +213,13 @@ describe('FolderActionsService', () => {
});
it('should reload target upon node deletion', async () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
const permission = 'delete';
const target = jasmine.createSpyObj('obj', ['reload']);
@@ -221,13 +237,16 @@ describe('FolderActionsService', () => {
});
it('should emit success event upon node deletion', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
observer.next();
observer.complete();
}));
spyOn(documentListService, 'deleteNode').and.callFake(
() =>
new Observable<any>((observer) => {
observer.next();
observer.complete();
})
);
let lastValue: string;
service.success.subscribe((nodeId) => lastValue = nodeId);
service.success.subscribe((nodeId) => (lastValue = nodeId));
const permission = 'delete';
const target = jasmine.createSpyObj('obj', ['reload']);
@@ -19,11 +19,9 @@ import { TestBed } from '@angular/core/testing';
import { LockService } from './lock.service';
import { CoreTestingModule, AuthenticationService } from '@alfresco/adf-core';
import { Node } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core';
import { addDays, subDays } from 'date-fns';
describe('PeopleProcessService', () => {
let service: LockService;
let authenticationService: AuthenticationService;
@@ -33,10 +31,7 @@ describe('PeopleProcessService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
]
imports: [CoreTestingModule]
});
service = TestBed.inject(LockService);
authenticationService = TestBed.inject(AuthenticationService);
@@ -59,37 +54,34 @@ describe('PeopleProcessService', () => {
name: 'readonly-lock-node',
isLocked: true,
isFile: true,
properties:
{
'cm:lockType': 'READ_ONLY_LOCK',
'cm:lockLifetime': 'PERSISTENT'
}
properties: {
'cm:lockType': 'READ_ONLY_LOCK',
'cm:lockLifetime': 'PERSISTENT'
}
} as Node;
const nodeReadOnlyWithExpiredDate: Node = {
name: 'readonly-lock-node',
isLocked: true,
isFile: true,
properties:
{
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': subDays(new Date(), 4)
}
properties: {
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': subDays(new Date(), 4)
}
} as Node;
const nodeReadOnlyWithActiveExpiration: Node = {
name: 'readonly-lock-node',
isLocked: true,
isFile: true,
properties:
{
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': addDays(new Date(), 4)
}
properties: {
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': addDays(new Date(), 4)
}
} as Node;
it('should return true when readonly lock is active', () => {
@@ -110,38 +102,35 @@ describe('PeopleProcessService', () => {
name: 'readonly-lock-node',
isLocked: true,
isFile: true,
properties:
{
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' }
}
properties: {
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' }
}
} as Node;
const nodeOwnerAllowedLockWithExpiredDate: Node = {
name: 'readonly-lock-node',
isLocked: true,
isFile: true,
properties:
{
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': subDays(new Date(), 4)
}
properties: {
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': subDays(new Date(), 4)
}
} as Node;
const nodeOwnerAllowedLockWithActiveExpiration: Node = {
name: 'readonly-lock-node',
isLocked: true,
isFile: true,
properties:
{
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': addDays(new Date(), 4)
}
properties: {
'cm:lockType': 'WRITE_LOCK',
'cm:lockLifetime': 'PERSISTENT',
'cm:lockOwner': { id: 'lock-owner-user' },
'cm:expiryDate': addDays(new Date(), 4)
}
} as Node;
it('should return false when the user is the lock owner', () => {
@@ -163,5 +152,5 @@ describe('PeopleProcessService', () => {
spyOn(authenticationService, 'getEcmUsername').and.returnValue('banana-user');
expect(service.isLocked(nodeOwnerAllowedLockWithActiveExpiration)).toBeTruthy();
});
});
});
});
@@ -24,7 +24,6 @@ import { ContentNodeDialogService } from '../../content-node-selector/content-no
import { of, throwError } from 'rxjs';
import { MatDialogRef } from '@angular/material/dialog';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { delay } from 'rxjs/operators';
const fakeNode: Node = {
@@ -32,7 +31,6 @@ const fakeNode: Node = {
} as Node;
describe('NodeActionsService', () => {
let service: NodeActionsService;
let documentListService: DocumentListService;
let contentDialogService: ContentNodeDialogService;
@@ -42,13 +40,8 @@ describe('NodeActionsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
providers: [
{ provide: MatDialogRef, useValue: dialogRef }
]
imports: [ContentTestingModule],
providers: [{ provide: MatDialogRef, useValue: dialogRef }]
});
const appConfig: AppConfigService = TestBed.inject(AppConfigService);
appConfig.config.ecmHost = 'http://localhost:9876/ecm';
@@ -103,10 +96,12 @@ describe('NodeActionsService', () => {
it('should be able to propagate the dialog error', fakeAsync(() => {
spyOn(documentListService, 'copyNode').and.returnValue(throwError('FAKE-KO'));
service.copyFolder(fakeNode, '!allowed').subscribe(() => {
}, (error) => {
expect(error).toBe('FAKE-KO');
});
service.copyFolder(fakeNode, '!allowed').subscribe(
() => {},
(error) => {
expect(error).toBe('FAKE-KO');
}
);
tick(100);
}));
@@ -23,17 +23,10 @@ import { Subject, of } from 'rxjs';
import { FolderCreateDirective } from './folder-create.directive';
import { Node } from '@alfresco/js-api';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { ContentService } from '../common/services/content.service';
@Component({
template: `
<div
[adf-create-folder]="parentNode"
(success)="success($event)"
title="create-title"
[nodeType]="'cm:my-little-pony'">
</div>`
template: ` <div [adf-create-folder]="parentNode" (success)="success($event)" title="create-title" [nodeType]="'cm:my-little-pony'"></div>`
})
class TestTypeComponent {
parentNode = '';
@@ -63,14 +56,8 @@ describe('FolderCreateDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
declarations: [
TestTypeComponent,
TestComponent
]
imports: [ContentTestingModule],
declarations: [TestTypeComponent, TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
element = fixture.debugElement.query(By.directive(FolderCreateDirective));
@@ -78,7 +65,7 @@ describe('FolderCreateDirective', () => {
contentService = TestBed.inject(ContentService);
dialogRefMock = {
afterClosed: (val) => of(val),
afterClosed: (val) => of(val),
componentInstance: {
error: new Subject<any>(),
success: new Subject<Node>()
@@ -134,7 +121,6 @@ describe('FolderCreateDirective', () => {
});
describe('Without overrides', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
element = fixture.debugElement.query(By.directive(FolderCreateDirective));
@@ -23,7 +23,6 @@ import { Subject, of } from 'rxjs';
import { FolderEditDirective } from './folder-edit.directive';
import { Node } from '@alfresco/js-api';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { ContentService } from '../common/services/content.service';
@Component({
@@ -52,13 +51,8 @@ describe('FolderEditDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
declarations: [
TestComponent
]
imports: [ContentTestingModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
element = fixture.debugElement.query(By.directive(FolderEditDirective));
@@ -66,7 +60,7 @@ describe('FolderEditDirective', () => {
contentService = TestBed.inject(ContentService);
dialogRefMock = {
afterClosed: (val) => of(val),
afterClosed: (val) => of(val),
componentInstance: {
error: new Subject<any>(),
success: new Subject<Node>()
@@ -20,7 +20,6 @@ import { ScrollingModule } from '@angular/cdk/scrolling';
import { Component, OnInit } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { from, Observable } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module';
import { InfiniteScrollDatasource } from './infinite-scroll-datasource';
@@ -96,11 +95,11 @@ describe('InfiniteScrollDatasource', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
const getRenderedItems = (): HTMLDivElement[] => fixture.debugElement.queryAll(By.css('.test-item')).map(element => element.nativeElement);
const getRenderedItems = (): HTMLDivElement[] => fixture.debugElement.queryAll(By.css('.test-item')).map((element) => element.nativeElement);
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule, ScrollingModule],
imports: [ContentTestingModule, ScrollingModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { mockFile, mockNode } from '../mock';
import { ContentTestingModule } from '../testing/content.testing.module';
import { UploadVersionButtonComponent } from '../upload';
@@ -45,7 +44,7 @@ describe('NewVersionUploaderDialog', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
declarations: [
NewVersionUploaderDialogComponent,
VersionListComponent,
@@ -18,7 +18,6 @@
import { Component, EventEmitter, Output } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { BehaviorSubject, of, Subject } from 'rxjs';
import { mockFile, mockNewVersionUploaderData, mockNode } from '../mock';
import { ContentTestingModule } from '../testing/content.testing.module';
@@ -44,7 +43,6 @@ class TestDialogComponent {
uploadError = new EventEmitter<any>();
afterClosed = () => of({ action: 'refresh', node: mockNode });
}
describe('NewVersionUploaderService', () => {
@@ -56,10 +54,7 @@ describe('NewVersionUploaderService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
declarations: [TestDialogComponent]
});
});
@@ -83,9 +78,11 @@ describe('NewVersionUploaderService', () => {
describe('Mat Dialog configuration', () => {
let mockNewVersionUploaderDialogData: NewVersionUploaderDialogData;
beforeEach(() => {
spyOn(service.versionsApi, 'listVersionHistory').and.returnValue(Promise.resolve({
list: { entries: [{ entry: '2' }] }
} as any));
spyOn(service.versionsApi, 'listVersionHistory').and.returnValue(
Promise.resolve({
list: { entries: [{ entry: '2' }] }
} as any)
);
mockNewVersionUploaderDialogData = {
node: mockNode,
file: mockFile
@@ -190,16 +187,17 @@ describe('NewVersionUploaderService', () => {
width: '630px'
} as any);
}));
});
describe('Subscribe events from Dialog', () => {
let mockNewVersionUploaderDialogData: NewVersionUploaderDialogData;
beforeEach(() => {
spyOn(service.versionsApi, 'listVersionHistory').and.returnValue(Promise.resolve({
list: { entries: [{ entry: '2' }] }
}) as any);
spyOn(service.versionsApi, 'listVersionHistory').and.returnValue(
Promise.resolve({
list: { entries: [{ entry: '2' }] }
}) as any
);
mockNewVersionUploaderDialogData = {
node: mockNode,
file: mockFile
@@ -251,13 +249,15 @@ describe('NewVersionUploaderService', () => {
uploadError: new BehaviorSubject<any>({ value: 'Upload error' })
};
spyOnDialogOpen.and.returnValue(dialogRefSpyObj);
service.openUploadNewVersionDialog(mockNewVersionUploaderDialogData).subscribe(() => {
service.openUploadNewVersionDialog(mockNewVersionUploaderDialogData).subscribe(
() => {
fail('An error should have been thrown');
},
error => {
(error) => {
expect(error).toEqual({ value: 'Upload error' });
done();
});
}
);
});
it('should focus element indicated by passed selector after closing modal', (done) => {
@@ -271,11 +271,8 @@ describe('NewVersionUploaderService', () => {
done();
});
spyOn(document, 'querySelector').and.returnValue(elementToFocus);
service.openUploadNewVersionDialog(mockNewVersionUploaderDialogData, undefined, elementToFocusSelector)
.subscribe();
service.openUploadNewVersionDialog(mockNewVersionUploaderDialogData, undefined, elementToFocusSelector).subscribe();
});
});
});
});
@@ -18,21 +18,16 @@
import { TestBed } from '@angular/core/testing';
import { CommentModel, CoreTestingModule } from '@alfresco/adf-core';
import { fakeContentComment, fakeContentComments } from '../mocks/node-comments.mock';
import { TranslateModule } from '@ngx-translate/core';
import { NodeCommentsService } from './node-comments.service';
declare let jasmine: any;
describe('NodeCommentsService', () => {
let service: NodeCommentsService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreTestingModule
]
imports: [CoreTestingModule]
});
service = TestBed.inject(NodeCommentsService);
@@ -44,20 +39,17 @@ describe('NodeCommentsService', () => {
});
describe('Node comments', () => {
it('should add a comment node ', (done) => {
service.add('999', 'fake-comment-message').subscribe(
(res: CommentModel) => {
expect(res).toBeDefined();
expect(res.id).not.toEqual(null);
expect(res.message).toEqual('fake-comment-message');
expect(res.created).not.toEqual(null);
expect(res.createdBy.email).toEqual('fake-email@dom.com');
expect(res.createdBy.firstName).toEqual('firstName');
expect(res.createdBy.lastName).toEqual('lastName');
done();
}
);
service.add('999', 'fake-comment-message').subscribe((res: CommentModel) => {
expect(res).toBeDefined();
expect(res.id).not.toEqual(null);
expect(res.message).toEqual('fake-comment-message');
expect(res.created).not.toEqual(null);
expect(res.createdBy.email).toEqual('fake-email@dom.com');
expect(res.createdBy.firstName).toEqual('firstName');
expect(res.createdBy.lastName).toEqual('lastName');
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
@@ -67,15 +59,13 @@ describe('NodeCommentsService', () => {
});
it('should return the nodes comments ', (done) => {
service.get('999').subscribe(
(res: CommentModel[]) => {
expect(res).toBeDefined();
expect(res.length).toEqual(2);
expect(res[0].message).toEqual('fake-message-1');
expect(res[1].message).toEqual('fake-message-2');
done();
}
);
service.get('999').subscribe((res: CommentModel[]) => {
expect(res).toBeDefined();
expect(res.length).toEqual(2);
expect(res[0].message).toEqual('fake-message-1');
expect(res[1].message).toEqual('fake-message-2');
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
@@ -19,7 +19,6 @@ import { Node, PermissionElement } from '@alfresco/js-api';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { Subject } from 'rxjs';
import { AddPermissionPanelComponent } from './add-permission-panel.component';
import { ContentTestingModule } from '../../../testing/content.testing.module';
@@ -64,7 +63,7 @@ describe('AddPermissionDialog', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
providers: [
{ provide: MatDialogRef, useValue: dialogRef },
{ provide: MAT_DIALOG_DATA, useValue: data }
@@ -23,8 +23,6 @@ import { fakeAuthorityListResult, fakeNameListResult } from '../../../mock/add-p
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { SearchService } from '../../../search/services/search.service';
import { DebugElement } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { MatIconTestingModule } from '@angular/material/icon/testing';
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatSelectionListHarness } from '@angular/material/list/testing';
@@ -39,11 +37,7 @@ describe('AddPermissionPanelComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule,
MatIconTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(AddPermissionPanelComponent);
loader = TestbedHarnessEnvironment.loader(fixture);
@@ -20,27 +20,22 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AddPermissionComponent } from './add-permission.component';
import { AddPermissionPanelComponent } from './add-permission-panel.component';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { of, throwError } from 'rxjs';
import { fakeAuthorityResults } from '../../../mock/add-permission.component.mock';
import { NodePermissionService } from '../../services/node-permission.service';
import { ContentTestingModule } from '../../../testing/content.testing.module';
describe('AddPermissionComponent', () => {
let fixture: ComponentFixture<AddPermissionComponent>;
let element: HTMLElement;
let nodePermissionService: NodePermissionService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
nodePermissionService = TestBed.inject(NodePermissionService);
const response: any = { node: { id: 'fake-node', allowableOperations: ['updatePermissions']}, roles: [{ label: 'Test' , role: 'test'}] };
const response: any = { node: { id: 'fake-node', allowableOperations: ['updatePermissions'] }, roles: [{ label: 'Test', role: 'test' }] };
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of(response));
fixture = TestBed.createComponent(AddPermissionComponent);
element = fixture.nativeElement;
@@ -60,7 +55,9 @@ describe('AddPermissionComponent', () => {
});
it('should enable the ADD button when a selection is sent', async () => {
const addPermissionPanelComponent: AddPermissionPanelComponent = fixture.debugElement.query(By.directive(AddPermissionPanelComponent)).componentInstance;
const addPermissionPanelComponent: AddPermissionPanelComponent = fixture.debugElement.query(
By.directive(AddPermissionPanelComponent)
).componentInstance;
addPermissionPanelComponent.select.emit(fakeAuthorityResults);
fixture.detectChanges();
@@ -71,9 +68,11 @@ describe('AddPermissionComponent', () => {
});
it('should NOT enable the ADD button when a selection is sent but the user does not have the permissions', async () => {
const addPermissionPanelComponent: AddPermissionPanelComponent = fixture.debugElement.query(By.directive(AddPermissionPanelComponent)).componentInstance;
const addPermissionPanelComponent: AddPermissionPanelComponent = fixture.debugElement.query(
By.directive(AddPermissionPanelComponent)
).componentInstance;
addPermissionPanelComponent.select.emit(fakeAuthorityResults);
fixture.componentInstance.currentNode = new Node({id: 'fake-node-id'});
fixture.componentInstance.currentNode = new Node({ id: 'fake-node-id' });
fixture.detectChanges();
await fixture.whenStable();
@@ -84,10 +83,10 @@ describe('AddPermissionComponent', () => {
it('should emit a success event when the node is updated', async () => {
fixture.componentInstance.selectedItems = fakeAuthorityResults;
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of(new Node({ id: 'fake-node-id'})));
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of(new Node({ id: 'fake-node-id' })));
let lastValue: Node;
fixture.componentInstance.success.subscribe((node) => lastValue = node);
fixture.componentInstance.success.subscribe((node) => (lastValue = node));
fixture.detectChanges();
await fixture.whenStable();
@@ -109,10 +108,10 @@ describe('AddPermissionComponent', () => {
it('should emit an error event when the node update fail', async () => {
fixture.componentInstance.selectedItems = fakeAuthorityResults;
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(throwError({ error: 'err'}));
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(throwError({ error: 'err' }));
let lastValue: any;
fixture.componentInstance.error.subscribe((error) => lastValue = error);
fixture.componentInstance.error.subscribe((error) => (lastValue = error));
fixture.detectChanges();
await fixture.whenStable();
@@ -19,15 +19,13 @@ import { SimpleInheritedPermissionTestComponent } from '../../mock/inherited-per
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { NodesApiService } from '../../common/services/nodes-api.service';
const fakeNodeWithInherit: any = { id: 'fake-id', permissions : {isInheritanceEnabled : true}, allowableOperations: ['updatePermissions']};
const fakeNodeNoInherit: any = { id: 'fake-id', permissions : {isInheritanceEnabled : false}, allowableOperations: ['updatePermissions']};
const fakeNodeWithInheritNoPermission: any = { id: 'fake-id', permissions : {isInheritanceEnabled : true}};
const fakeNodeWithInherit: any = { id: 'fake-id', permissions: { isInheritanceEnabled: true }, allowableOperations: ['updatePermissions'] };
const fakeNodeNoInherit: any = { id: 'fake-id', permissions: { isInheritanceEnabled: false }, allowableOperations: ['updatePermissions'] };
const fakeNodeWithInheritNoPermission: any = { id: 'fake-id', permissions: { isInheritanceEnabled: true } };
describe('InheritPermissionDirective', () => {
let fixture: ComponentFixture<SimpleInheritedPermissionTestComponent>;
let element: HTMLElement;
let component: SimpleInheritedPermissionTestComponent;
@@ -35,13 +33,8 @@ describe('InheritPermissionDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
declarations: [
SimpleInheritedPermissionTestComponent
]
imports: [ContentTestingModule],
declarations: [SimpleInheritedPermissionTestComponent]
});
fixture = TestBed.createComponent(SimpleInheritedPermissionTestComponent);
component = fixture.componentInstance;
@@ -16,7 +16,6 @@
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { PermissionContainerComponent } from './permission-container.component';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { HarnessLoader } from '@angular/cdk/testing';
@@ -32,7 +31,7 @@ describe('PermissionContainerComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(PermissionContainerComponent);
component = fixture.componentInstance;
@@ -16,7 +16,6 @@
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { of, throwError } from 'rxjs';
import { SearchService } from '../../../search/services/search.service';
import { PermissionListComponent } from './permission-list.component';
@@ -54,7 +53,7 @@ describe('PermissionListComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(PermissionListComponent);
component = fixture.componentInstance;
@@ -18,7 +18,6 @@
import { NotificationService } from '@alfresco/adf-core';
import { NodesApiService } from '../../../common/services/nodes-api.service';
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { of, throwError } from 'rxjs';
import { PermissionListService } from './permission-list.service';
import { ContentTestingModule } from '../../../testing/content.testing.module';
@@ -31,19 +30,17 @@ describe('PermissionListService', () => {
let nodePermissionService: NodePermissionService;
let notificationService: NotificationService;
let nodesApiService: NodesApiService;
const localPermission = [new PermissionDisplayModel({
authorityId: 'GROUP_EVERYONE',
name: 'Contributor',
accessStatus: 'ALLOWED'
})
const localPermission = [
new PermissionDisplayModel({
authorityId: 'GROUP_EVERYONE',
name: 'Contributor',
accessStatus: 'ALLOWED'
})
];
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
service = TestBed.inject(PermissionListService);
nodePermissionService = TestBed.inject(NodePermissionService);
@@ -55,7 +52,7 @@ describe('PermissionListService', () => {
});
it('fetch Permission', (done) => {
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node: fakeNodeWithOnlyLocally , roles: []}));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakeNodeWithOnlyLocally, roles: [] }));
const subscription = service.data$.subscribe(({ node, inheritedPermissions, localPermissions, roles }) => {
expect(node).toBe(fakeNodeWithOnlyLocally);
@@ -70,12 +67,11 @@ describe('PermissionListService', () => {
});
describe('toggle permission', () => {
it('should show error if user does not have permission to update node', () => {
const node = JSON.parse(JSON.stringify(fakeNodeInheritedOnly));
const event = { source: { checked: false } };
node.allowableOperations = [];
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []}));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node, roles: [] }));
spyOn(nodesApiService, 'updateNode').and.stub();
service.fetchPermission('fetch node');
service.toggleInherited(event as any);
@@ -86,7 +82,7 @@ describe('PermissionListService', () => {
it('should include the local permission before toggle', (done) => {
const node = JSON.parse(JSON.stringify(fakeNodeInheritedOnly));
const event = { source: { checked: false } };
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []}));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node, roles: [] }));
spyOn(nodePermissionService, 'updatePermissions').and.returnValue(of(null));
spyOn(nodesApiService, 'updateNode').and.returnValue(of(JSON.parse(JSON.stringify(fakeNodeLocalSiteManager))));
service.fetchPermission('fetch node');
@@ -109,13 +105,15 @@ describe('PermissionListService', () => {
const node = JSON.parse(JSON.stringify(fakeNodeInheritedOnly));
const event = { source: { checked: false } };
const updateNode = JSON.parse(JSON.stringify(fakeNodeInheritedOnly));
node.permissions.locallySet = [{
authorityId: 'GROUP_site_testsite_SiteManager',
name: 'SiteManager',
accessStatus: 'ALLOWED'
}];
node.permissions.locallySet = [
{
authorityId: 'GROUP_site_testsite_SiteManager',
name: 'SiteManager',
accessStatus: 'ALLOWED'
}
];
updateNode.permissions.isInheritanceEnabled = false;
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []}));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node, roles: [] }));
spyOn(nodePermissionService, 'updatePermissions').and.returnValue(of(null));
spyOn(nodesApiService, 'updateNode').and.returnValue(of(updateNode));
service.fetchPermission('fetch node');
@@ -131,7 +129,7 @@ describe('PermissionListService', () => {
const event = { source: { checked: false } };
node.permissions.isInheritanceEnabled = true;
spyOn(nodesApiService, 'updateNode').and.returnValue(throwError('Failed to update'));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []}));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node, roles: [] }));
service.fetchPermission('fetch node');
service.toggleInherited(event as any);
@@ -144,14 +142,17 @@ describe('PermissionListService', () => {
describe('delete permission', () => {
const node = JSON.parse(JSON.stringify(fakeNodeWithOnlyLocally));
beforeEach(() => {
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []}));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node, roles: [] }));
service.fetchPermission('fetch node');
});
it('should be able to delete a permission', () => {
spyOn(nodePermissionService, 'removePermissions').and.returnValue(of(node));
service.deletePermissions(localPermission);
expect(notificationService.showInfo).toHaveBeenCalledWith('PERMISSION_MANAGER.MESSAGE.PERMISSION-BULK-DELETE-SUCCESS', null, { user: 0, group: 1 });
expect(notificationService.showInfo).toHaveBeenCalledWith('PERMISSION_MANAGER.MESSAGE.PERMISSION-BULK-DELETE-SUCCESS', null, {
user: 0,
group: 1
});
});
it('should show error message for errored delete operation', () => {
@@ -164,14 +165,17 @@ describe('PermissionListService', () => {
describe('Bulk Role', () => {
const node = JSON.parse(JSON.stringify(fakeNodeWithOnlyLocally));
beforeEach(() => {
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []}));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node, roles: [] }));
service.fetchPermission('fetch node');
});
it('should be able to update bulk permission', () => {
spyOn(nodePermissionService, 'updatePermissions').and.returnValue(of(node));
service.bulkRoleUpdate('fake-role');
expect(notificationService.showInfo).toHaveBeenCalledWith('PERMISSION_MANAGER.MESSAGE.PERMISSION-BULK-UPDATE-SUCCESS', null, { user: 0, group: 1 });
expect(notificationService.showInfo).toHaveBeenCalledWith('PERMISSION_MANAGER.MESSAGE.PERMISSION-BULK-UPDATE-SUCCESS', null, {
user: 0,
group: 1
});
});
it('should show error message for errored operation', () => {
@@ -16,7 +16,6 @@
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { UserIconColumnComponent } from './user-icon-column.component';
import { NodeEntry } from '@alfresco/js-api';
@@ -38,7 +37,7 @@ describe('UserIconColumnComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(UserIconColumnComponent);
component = fixture.componentInstance;
@@ -16,35 +16,30 @@
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { UserNameColumnComponent } from './user-name-column.component';
import { NodeEntry } from '@alfresco/js-api';
describe('UserNameColumnComponent', () => {
let fixture: ComponentFixture<UserNameColumnComponent>;
let component: UserNameColumnComponent;
let element: HTMLElement;
const person = {
const person = {
firstName: 'fake',
lastName: 'user',
email: 'fake@test.com'
};
const group = {
const group = {
id: 'fake-id',
displayName: 'fake authority'
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(UserNameColumnComponent);
fixture = TestBed.createComponent(UserNameColumnComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
fixture.detectChanges();
@@ -65,7 +60,7 @@ describe('UserNameColumnComponent', () => {
expect(element.querySelector('[title="fake@test.com"]').textContent).toContain('fake@test.com');
});
it('should render person value from node', (done) => {
it('should render person value from node', (done) => {
component.node = {
entry: {
nodeType: 'cm:person',
@@ -137,7 +132,7 @@ describe('UserNameColumnComponent', () => {
entry: {
nodeType: 'cm:authorityContainer',
properties: {
'cm:authorityName': 'Fake authority'
'cm:authorityName': 'Fake authority'
}
}
} as NodeEntry;
@@ -23,10 +23,8 @@ import { of, Subject, throwError } from 'rxjs';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { NodePermissionService } from './node-permission.service';
import { Node } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core';
describe('NodePermissionDialogService', () => {
let service: NodePermissionDialogService;
let materialDialog: MatDialog;
let spyOnDialogOpen: jasmine.Spy;
@@ -35,10 +33,7 @@ describe('NodePermissionDialogService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
const appConfig: AppConfigService = TestBed.inject(AppConfigService);
appConfig.config.ecmHost = 'http://localhost:9876/ecm';
@@ -56,11 +51,10 @@ describe('NodePermissionDialogService', () => {
});
describe('when node has permission to update permissions', () => {
let fakePermissionNode = new Node({});
beforeEach(() => {
fakePermissionNode = { id: 'fake-permission-node', allowableOperations: ['updatePermissions']} as Node;
fakePermissionNode = { id: 'fake-permission-node', allowableOperations: ['updatePermissions'] } as Node;
});
it('should be able to open the dialog showing node permissions', () => {
@@ -69,7 +63,7 @@ describe('NodePermissionDialogService', () => {
});
it('should return the updated node', (done) => {
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of(new Node({id : 'fake-node-updated'})));
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of(new Node({ id: 'fake-node-updated' })));
spyOn(service, 'openAddPermissionDialog').and.returnValue(of(null));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakePermissionNode, roles: [] }));
service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe((node) => {
@@ -79,24 +73,26 @@ describe('NodePermissionDialogService', () => {
});
it('should throw an error if the update of the node fails', (done) => {
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(throwError({error : 'error'}));
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(throwError({ error: 'error' }));
spyOn(service, 'openAddPermissionDialog').and.returnValue(of(null));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakePermissionNode, roles: [] }));
service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe(() => {
throwError('This call should fail');
}, (error) => {
expect(error.error).toBe('error');
done();
});
service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe(
() => {
throwError('This call should fail');
},
(error) => {
expect(error.error).toBe('error');
done();
}
);
});
});
describe('when node does not have permission to update permissions', () => {
let fakeForbiddenNode = new Node({});
beforeEach(() => {
fakeForbiddenNode = { id: 'fake-permission-node', allowableOperations: ['update']} as Node;
fakeForbiddenNode = { id: 'fake-permission-node', allowableOperations: ['update'] } as Node;
});
it('should not be able to open the dialog showing node permissions', () => {
@@ -106,13 +102,15 @@ describe('NodePermissionDialogService', () => {
it('should return the updated node', (done) => {
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakeForbiddenNode, roles: [] }));
service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe(() => {
throwError('This call should fail');
},
(error) => {
expect(error.message).toBe('PERMISSION_MANAGER.ERROR.NOT-ALLOWED');
done();
});
service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe(
() => {
throwError('This call should fail');
},
(error) => {
expect(error.message).toBe('PERMISSION_MANAGER.ERROR.NOT-ALLOWED');
done();
}
);
});
});
});
});
@@ -21,16 +21,18 @@ import { SearchService } from '../../search/services/search.service';
import { Node, PermissionElement } from '@alfresco/js-api';
import { of, throwError } from 'rxjs';
import {
fakeNodeWithOnlyLocally, fakeSiteRoles, fakeSiteNodeResponse,
fakeNodeToRemovePermission, fakeNodeWithoutPermissions, fakeNodeWithoutSite
fakeNodeWithOnlyLocally,
fakeSiteRoles,
fakeSiteNodeResponse,
fakeNodeToRemovePermission,
fakeNodeWithoutPermissions,
fakeNodeWithoutSite
} from '../../mock/permission-list.component.mock';
import { fakeAuthorityResults } from '../../mock/add-permission.component.mock';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { NodesApiService } from '../../common/services/nodes-api.service';
describe('NodePermissionService', () => {
let service: NodePermissionService;
let nodeService: NodesApiService;
let searchApiService: SearchService;
@@ -54,20 +56,20 @@ describe('NodePermissionService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
service = TestBed.inject(NodePermissionService);
searchApiService = TestBed.inject(SearchService);
nodeService = TestBed.inject(NodesApiService);
});
const returnUpdatedNode = (nodeBody: Node) => of(new Node({
id: 'fake-updated-node',
permissions: nodeBody.permissions
}));
const returnUpdatedNode = (nodeBody: Node) =>
of(
new Node({
id: 'fake-updated-node',
permissions: nodeBody.permissions
})
);
it('should return a list of roles taken from the site groups', (done) => {
spyOn(searchApiService, 'searchByQueryBody').and.returnValue(of(fakeSiteNodeResponse));
@@ -98,7 +100,7 @@ describe('NodePermissionService', () => {
const fakePermission: PermissionElement = {
authorityId: 'GROUP_EVERYONE',
name: 'Contributor',
accessStatus : fakeAccessStatus
accessStatus: fakeAccessStatus
};
spyOn(nodeService, 'updateNode').and.callFake((_, permissionBody) => returnUpdatedNode(permissionBody));
@@ -118,7 +120,7 @@ describe('NodePermissionService', () => {
const fakePermission = {
authorityId: 'FAKE_PERSON_1',
name: 'Contributor',
accessStatus : 'ALLOWED'
accessStatus: 'ALLOWED'
} as PermissionElement;
spyOn(nodeService, 'updateNode').and.callFake((_, permissionBody) => returnUpdatedNode(permissionBody));
const fakeNodeCopy = JSON.parse(JSON.stringify(fakeNodeToRemovePermission));
@@ -182,24 +184,25 @@ describe('NodePermissionService', () => {
it('should fail when user select the same authority and role to add', (done) => {
const fakeNodeCopy = JSON.parse(JSON.stringify(fakeNodeWithOnlyLocally));
const fakeDuplicateAuthority: PermissionElement [] = [{
authorityId: 'GROUP_EVERYONE',
accessStatus: 'ALLOWED',
name: 'Contributor'
}];
const fakeDuplicateAuthority: PermissionElement[] = [
{
authorityId: 'GROUP_EVERYONE',
accessStatus: 'ALLOWED',
name: 'Contributor'
}
];
service.updateLocallySetPermissions(fakeNodeCopy, fakeDuplicateAuthority)
.subscribe(
() => {
fail('should throw exception');
},
(errorMessage) => {
expect(errorMessage).not.toBeNull();
expect(errorMessage).toBeDefined();
expect(errorMessage).toBe('PERMISSION_MANAGER.ERROR.DUPLICATE-PERMISSION');
done();
}
);
service.updateLocallySetPermissions(fakeNodeCopy, fakeDuplicateAuthority).subscribe(
() => {
fail('should throw exception');
},
(errorMessage) => {
expect(errorMessage).not.toBeNull();
expect(errorMessage).toBeDefined();
expect(errorMessage).toBe('PERMISSION_MANAGER.ERROR.DUPLICATE-PERMISSION');
done();
}
);
});
it('should be able to remove the locallyset permission', (done) => {
@@ -17,7 +17,6 @@
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { SearchFacetFiltersService } from '../services/search-facet-filters.service';
import { SearchQueryBuilderService } from '../services/search-query-builder.service';
@@ -25,8 +24,7 @@ import { SearchQueryBuilderService } from '../services/search-query-builder.serv
@Component({
template: `<button adf-reset-search></button>`
})
class TestComponent {
}
class TestComponent {}
describe('Directive: ResetSearchDirective', () => {
let fixture: ComponentFixture<TestComponent>;
@@ -35,10 +33,7 @@ describe('Directive: ResetSearchDirective', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
@@ -48,7 +43,7 @@ describe('Directive: ResetSearchDirective', () => {
it('should reset the search on click', () => {
spyOn(queryBuilder, 'resetToDefaults');
searchFacetFiltersService.responseFacets = [ { type: 'field', label: 'f1' } ] as any;
searchFacetFiltersService.responseFacets = [{ type: 'field', label: 'f1' }] as any;
fixture.nativeElement.querySelector('button').click();
expect(searchFacetFiltersService.responseFacets).toEqual([]);
expect(queryBuilder.resetToDefaults).toHaveBeenCalled();
@@ -20,7 +20,6 @@ import { SearchFilterList } from '../../models/search-filter-list.model';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { sizeOptions, stepOne, stepThree } from '../../../mock';
import { TranslateModule } from '@ngx-translate/core';
import { HarnessLoader, TestKey } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatCheckboxHarness } from '@angular/material/checkbox/testing';
@@ -33,7 +32,7 @@ describe('SearchCheckListComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchCheckListComponent);
component = fixture.componentInstance;
@@ -18,7 +18,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatChipRemove } from '@angular/material/chips';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { Subject } from 'rxjs';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { SearchChipAutocompleteInputComponent } from './search-chip-autocomplete-input.component';
@@ -38,17 +37,14 @@ describe('SearchChipAutocompleteInputComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SearchChipAutocompleteInputComponent],
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchChipAutocompleteInputComponent);
loader = TestbedHarnessEnvironment.loader(fixture);
component = fixture.componentInstance;
component.onReset$ = onResetSubject.asObservable();
component.autocompleteOptions = [{value: 'option1'}, {value: 'option2'}];
component.autocompleteOptions = [{ value: 'option1' }, { value: 'option2' }];
fixture.detectChanges();
});
@@ -83,7 +79,7 @@ describe('SearchChipAutocompleteInputComponent', () => {
const inputElement = getInput();
inputElement.value = value;
fixture.detectChanges();
inputElement.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 13}));
inputElement.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 13 }));
fixture.detectChanges();
}
@@ -164,8 +160,8 @@ describe('SearchChipAutocompleteInputComponent', () => {
const optionToClick = matOptions[0];
await optionToClick.click();
expect(optionsChangedSpy).toHaveBeenCalledOnceWith([{value: 'option1'}]);
expect(component.selectedOptions).toEqual([{value: 'option1'}]);
expect(optionsChangedSpy).toHaveBeenCalledOnceWith([{ value: 'option1' }]);
expect(component.selectedOptions).toEqual([{ value: 'option1' }]);
expect((await getChipList()).length).toBe(1);
});
@@ -183,7 +179,7 @@ describe('SearchChipAutocompleteInputComponent', () => {
it('should apply class to already selected options based on custom compareOption function', async () => {
component.allowOnlyPredefinedValues = false;
component.autocompleteOptions = [{value: '.test1'}, {value: 'test3'}, {value: '.test2.'}, {value: 'test1'}];
component.autocompleteOptions = [{ value: '.test1' }, { value: 'test3' }, { value: '.test2.' }, { value: 'test1' }];
component.compareOption = (option1, option2) => option1.value.split('.')[1] === option2.value;
addNewOption('test1');
@@ -196,7 +192,7 @@ describe('SearchChipAutocompleteInputComponent', () => {
});
it('should limit autocomplete list to 15 values max', async () => {
component.autocompleteOptions = Array.from({length: 16}, (_, i) => ({value: `a${i}`}));
component.autocompleteOptions = Array.from({ length: 16 }, (_, i) => ({ value: `a${i}` }));
enterNewInputValue('a');
await fixture.whenStable();
@@ -219,7 +215,7 @@ describe('SearchChipAutocompleteInputComponent', () => {
});
it('should show autocomplete list based on custom filtering', async () => {
component.autocompleteOptions = [{value: '.test1'}, {value: 'test1'}, {value: 'test1.'}, {value: '.test2'}, {value: '.test12'}];
component.autocompleteOptions = [{ value: '.test1' }, { value: 'test1' }, { value: 'test1.' }, { value: '.test2' }, { value: '.test12' }];
component.filter = (options, value) => options.filter((option) => option.value.split('.')[1] === value);
enterNewInputValue('test1');
await fixture.whenStable();
@@ -238,7 +234,7 @@ describe('SearchChipAutocompleteInputComponent', () => {
it('should emit new value when selected options changed', async () => {
const optionsChangedSpy = spyOn(component.optionsChanged, 'emit');
addNewOption('option1');
expect(optionsChangedSpy).toHaveBeenCalledOnceWith([{value: 'option1'}]);
expect(optionsChangedSpy).toHaveBeenCalledOnceWith([{ value: 'option1' }]);
expect((await getChipList()).length).toBe(1);
expect(await getChipValue(0)).toBe('option1');
});
@@ -267,7 +263,7 @@ describe('SearchChipAutocompleteInputComponent', () => {
fixture.detectChanges();
expect(optionsChangedSpy).toHaveBeenCalledOnceWith([]);
expect((await getChipList())).toEqual([]);
expect(await getChipList()).toEqual([]);
expect(component.selectedOptions).toEqual([]);
});
@@ -279,12 +275,12 @@ describe('SearchChipAutocompleteInputComponent', () => {
fixture.debugElement.query(By.directive(MatChipRemove)).nativeElement.click();
fixture.detectChanges();
expect(optionsChangedSpy).toHaveBeenCalledOnceWith([{value: 'option2'}]);
expect(optionsChangedSpy).toHaveBeenCalledOnceWith([{ value: 'option2' }]);
expect((await getChipList()).length).toEqual(1);
});
it('should show full category path when fullPath provided', async () => {
component.filteredOptions = [{id: 'test-id', value: 'test-value', fullPath: 'test-full-path'}];
component.filteredOptions = [{ id: 'test-id', value: 'test-value', fullPath: 'test-full-path' }];
enterNewInputValue('test-value');
@@ -20,7 +20,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatChipHarness, MatChipRemoveHarness } from '@angular/material/chips/testing';
@@ -45,7 +44,7 @@ describe('SearchChipListComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
@@ -24,13 +24,12 @@ import { SearchControlComponent } from './search-control.component';
import { SearchService } from '../services/search.service';
import { of } from 'rxjs';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
@Component({
template: `
<adf-search-control [highlight]="true" #search>
<adf-empty-search-result>
<span id="custom-no-result">{{customMessage}}</span>
<span id="custom-no-result">{{ customMessage }}</span>
</adf-empty-search-result>
</adf-search-control>
`
@@ -46,7 +45,6 @@ export class SimpleSearchTestCustomEmptyComponent {
}
describe('SearchControlComponent', () => {
let fixture: ComponentFixture<SearchControlComponent>;
let component: SearchControlComponent;
let element: HTMLElement;
@@ -61,13 +59,8 @@ describe('SearchControlComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
declarations: [
SimpleSearchTestCustomEmptyComponent
]
imports: [ContentTestingModule],
declarations: [SimpleSearchTestCustomEmptyComponent]
});
fixture = TestBed.createComponent(SearchControlComponent);
debugElement = fixture.debugElement;
@@ -94,15 +87,12 @@ describe('SearchControlComponent', () => {
};
describe('when input values are inserted', () => {
beforeEach(() => {
fixture.detectChanges();
});
it('should emit searchChange when search term input changed', (done) => {
searchServiceSpy.and.returnValue(
of({ entry: { list: [] } })
);
searchServiceSpy.and.returnValue(of({ entry: { list: [] } }));
const searchDisposable = component.searchChange.subscribe((value) => {
expect(value).toBe('customSearchTerm');
@@ -141,7 +131,6 @@ describe('SearchControlComponent', () => {
});
describe('component rendering', () => {
it('should display a text input field by default', async () => {
fixture.detectChanges();
await fixture.whenStable();
@@ -158,10 +147,9 @@ describe('SearchControlComponent', () => {
const attr = element.querySelector('#adf-control-input').getAttribute('autocomplete');
expect(attr).toBe('off');
});
});
});
describe('autocomplete list', () => {
it('should make autocomplete list control hidden initially', (done) => {
fixture.detectChanges();
fixture.whenStable().then(() => {
@@ -325,10 +313,9 @@ describe('SearchControlComponent', () => {
expect(element.querySelector('#autocomplete-search-result-list')).toBeNull();
});
});
});
describe('option click', () => {
it('should emit a option clicked event when item is clicked', (done) => {
spyOn(component.searchTextInput, 'isSearchBarActive').and.returnValue(true);
searchServiceSpy.and.returnValue(of(JSON.parse(JSON.stringify(results))));
@@ -389,7 +376,6 @@ describe('SearchControlComponent', () => {
});
describe('SearchControlComponent - No result custom', () => {
beforeEach(() => {
fixtureCustom = TestBed.createComponent(SimpleSearchTestCustomEmptyComponent);
componentCustom = fixtureCustom.componentInstance;
@@ -16,7 +16,6 @@
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { SearchDateRange } from './search-date-range/search-date-range';
@@ -25,17 +24,7 @@ import { SearchDateRangeComponent } from './search-date-range/search-date-range.
import { SearchDateRangeTabbedComponent } from './search-date-range-tabbed.component';
import { DateRangeType } from './search-date-range/date-range-type';
import { InLastDateType } from './search-date-range/in-last-date-type';
import {
endOfDay,
endOfToday,
formatISO,
parse,
startOfDay, startOfMonth,
startOfWeek,
subDays,
subMonths,
subWeeks
} from 'date-fns';
import { endOfDay, endOfToday, formatISO, parse, startOfDay, startOfMonth, startOfWeek, subDays, subMonths, subWeeks } from 'date-fns';
@Component({
selector: 'adf-search-filter-tabbed',
@@ -72,10 +61,7 @@ describe('SearchDateRangeTabbedComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SearchDateRangeTabbedComponent, SearchFilterTabbedComponent, SearchDateRangeComponent],
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
imports: [ContentTestingModule],
providers: [
{ provide: SearchFilterTabbedComponent, useClass: MockSearchFilterTabbedComponent },
{ provide: SearchDateRangeComponent, useClass: MockSearchDateRangeComponent }
@@ -157,7 +143,9 @@ describe('SearchDateRangeTabbedComponent', () => {
component.onDateRangedValueChanged(inLastMockData, 'modifiedDate');
fixture.detectChanges();
component.submitValues();
expect(component.displayValue$.next).toHaveBeenCalledWith('CREATED DATE: 05-Jun-23 - 07-Jun-23 MODIFIED DATE: SEARCH.DATE_RANGE_ADVANCED.IN_LAST_DISPLAY_LABELS.WEEKS');
expect(component.displayValue$.next).toHaveBeenCalledWith(
'CREATED DATE: 05-Jun-23 - 07-Jun-23 MODIFIED DATE: SEARCH.DATE_RANGE_ADVANCED.IN_LAST_DISPLAY_LABELS.WEEKS'
);
component.onDateRangedValueChanged(anyMockDate, 'createdDate');
component.onDateRangedValueChanged(anyMockDate, 'modifiedDate');
@@ -171,8 +159,9 @@ describe('SearchDateRangeTabbedComponent', () => {
component.onDateRangedValueChanged(inLastMockData, 'modifiedDate');
fixture.detectChanges();
let inLastStartDate = startOfWeek(subWeeks(new Date(), 5));
let query = `createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
let query =
`createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
expect(component.combinedQuery).toEqual(query);
inLastMockData = {
@@ -185,8 +174,9 @@ describe('SearchDateRangeTabbedComponent', () => {
component.onDateRangedValueChanged(inLastMockData, 'modifiedDate');
fixture.detectChanges();
inLastStartDate = startOfDay(subDays(new Date(), 9));
query = `createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
query =
`createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
expect(component.combinedQuery).toEqual(query);
inLastMockData = {
@@ -199,8 +189,9 @@ describe('SearchDateRangeTabbedComponent', () => {
component.onDateRangedValueChanged(inLastMockData, 'modifiedDate');
fixture.detectChanges();
inLastStartDate = startOfMonth(subMonths(new Date(), 7));
query = `createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
query =
`createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
expect(component.combinedQuery).toEqual(query);
expect(component.combinedQuery).toEqual(query);
@@ -217,8 +208,9 @@ describe('SearchDateRangeTabbedComponent', () => {
component.submitValues();
fixture.detectChanges();
const inLastStartDate = startOfWeek(subWeeks(new Date(), 5));
const query = `createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
const query =
`createdDate:['${formatISO(startOfDay(betweenMockData.betweenStartDate))}' TO '${formatISO(endOfDay(betweenMockData.betweenEndDate))}']` +
` AND modifiedDate:['${formatISO(startOfDay(inLastStartDate))}' TO '${formatISO(endOfToday())}']`;
expect(component.context.queryFragments['dateRange']).toEqual(query);
expect(component.context.update).toHaveBeenCalled();
});
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../../testing/content.testing.module';
import { SearchDateRangeComponent } from './search-date-range.component';
import { addDays, endOfToday, format, parse, startOfYesterday, subDays } from 'date-fns';
@@ -38,10 +37,7 @@ describe('SearchDateRangeComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SearchDateRangeComponent],
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchDateRangeComponent);
@@ -234,7 +230,7 @@ describe('SearchDateRangeComponent', () => {
betweenStartDate: undefined,
betweenEndDate: undefined
};
let dateRangeTypeRadioButton = await loader.getHarness(MatRadioButtonHarness.with({ selector: '[data-automation-id="date-range-in-last"]' }));
let dateRangeTypeRadioButton = await loader.getHarness(MatRadioButtonHarness.with({ selector: '[data-automation-id="date-range-in-last"]' }));
await dateRangeTypeRadioButton.check();
selectDropdownOption('date-range-in-last-option-weeks');
enterValueInInputFieldAndTriggerEvent('date-range-in-last-input', '');
@@ -18,12 +18,10 @@
import { DEFAULT_DATETIME_FORMAT, SearchDatetimeRangeComponent } from './search-datetime-range.component';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { MatDatetimepickerInputEvent } from '@mat-datetimepicker/core';
import { DateFnsUtils } from '@alfresco/adf-core';
import { isValid } from 'date-fns';
describe('SearchDatetimeRangeComponent', () => {
let fixture: ComponentFixture<SearchDatetimeRangeComponent>;
let component: SearchDatetimeRangeComponent;
@@ -34,10 +32,7 @@ describe('SearchDatetimeRangeComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchDatetimeRangeComponent);
component = fixture.componentInstance;
@@ -147,10 +142,13 @@ describe('SearchDatetimeRangeComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
component.apply({
from: fromDatetime,
to: toDatetime
}, true);
component.apply(
{
from: fromDatetime,
to: toDatetime
},
true
);
const expectedQuery = `cm:created:['2016-10-16T12:30:00.000Z' TO '2017-10-16T20:00:59.000Z']`;
@@ -175,10 +173,13 @@ describe('SearchDatetimeRangeComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
component.apply({
from: fromInGmt,
to: toInGmt
}, true);
component.apply(
{
from: fromInGmt,
to: toInGmt
},
true
);
const expectedQuery = `cm:created:['2021-02-24T15:00:00.000Z' TO '2021-02-28T13:00:59.000Z']`;
@@ -16,7 +16,6 @@
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchFacetFieldComponent } from './search-facet-field.component';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
@@ -24,50 +23,46 @@ import { ContentTestingModule } from '../../../testing/content.testing.module';
import { FacetField } from '../../models/facet-field.interface';
import { FacetFieldBucket } from '../../models/facet-field-bucket.interface';
import { SearchFilterList } from '../../models/search-filter-list.model';
import { TranslateModule } from '@ngx-translate/core';
describe('SearchFacetFieldComponent', () => {
let component: SearchFacetFieldComponent;
let fixture: ComponentFixture<SearchFacetFieldComponent>;
let searchFacetFiltersService: SearchFacetFiltersService;
let queryBuilder: SearchQueryBuilderService;
let component: SearchFacetFieldComponent;
let fixture: ComponentFixture<SearchFacetFieldComponent>;
let searchFacetFiltersService: SearchFacetFiltersService;
let queryBuilder: SearchQueryBuilderService;
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
});
searchFacetFiltersService = TestBed.inject(SearchFacetFiltersService);
queryBuilder = TestBed.inject(SearchQueryBuilderService);
});
beforeEach(() => {
fixture = TestBed.createComponent(SearchFacetFieldComponent);
component = fixture.componentInstance;
spyOn(searchFacetFiltersService, 'updateSelectedBuckets').and.stub();
});
it('should update bucket model and query builder on facet toggle', () => {
spyOn(queryBuilder, 'update').and.stub();
spyOn(queryBuilder, 'addUserFacetBucket').and.callThrough();
const event: any = { checked: true };
const facetField: FacetField = { field: 'f1', label: 'f1', buckets: new SearchFilterList() };
const bucket: FacetFieldBucket = { checked: false, filterQuery: 'q1', label: 'q1', count: 1 };
component.field = facetField;
fixture.detectChanges();
component.onToggleBucket(event, facetField, bucket);
expect(bucket.checked).toBeTruthy();
expect(queryBuilder.addUserFacetBucket).toHaveBeenCalledWith(facetField.field, bucket);
expect(queryBuilder.update).toHaveBeenCalled();
expect(searchFacetFiltersService.updateSelectedBuckets).toHaveBeenCalled();
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [ContentTestingModule]
});
searchFacetFiltersService = TestBed.inject(SearchFacetFiltersService);
queryBuilder = TestBed.inject(SearchQueryBuilderService);
});
it('should update bucket model and query builder on facet un-toggle', () => {
beforeEach(() => {
fixture = TestBed.createComponent(SearchFacetFieldComponent);
component = fixture.componentInstance;
spyOn(searchFacetFiltersService, 'updateSelectedBuckets').and.stub();
});
it('should update bucket model and query builder on facet toggle', () => {
spyOn(queryBuilder, 'update').and.stub();
spyOn(queryBuilder, 'addUserFacetBucket').and.callThrough();
const event: any = { checked: true };
const facetField: FacetField = { field: 'f1', label: 'f1', buckets: new SearchFilterList() };
const bucket: FacetFieldBucket = { checked: false, filterQuery: 'q1', label: 'q1', count: 1 };
component.field = facetField;
fixture.detectChanges();
component.onToggleBucket(event, facetField, bucket);
expect(bucket.checked).toBeTruthy();
expect(queryBuilder.addUserFacetBucket).toHaveBeenCalledWith(facetField.field, bucket);
expect(queryBuilder.update).toHaveBeenCalled();
expect(searchFacetFiltersService.updateSelectedBuckets).toHaveBeenCalled();
});
it('should update bucket model and query builder on facet un-toggle', () => {
spyOn(queryBuilder, 'update').and.stub();
spyOn(queryBuilder, 'removeUserFacetBucket').and.callThrough();
@@ -85,13 +80,13 @@ describe('SearchFacetFieldComponent', () => {
expect(searchFacetFiltersService.updateSelectedBuckets).toHaveBeenCalled();
});
it('should unselect facet query and update builder', () => {
it('should unselect facet query and update builder', () => {
spyOn(queryBuilder, 'update').and.stub();
spyOn(queryBuilder, 'removeUserFacetBucket').and.callThrough();
const event: any = { checked: false };
const query = { checked: true, label: 'q1', filterQuery: 'query1' };
const facetField = { field: 'q1', type: 'query', label: 'label1', buckets: new SearchFilterList([ query ] ) } as FacetField;
const facetField = { field: 'q1', type: 'query', label: 'label1', buckets: new SearchFilterList([query]) } as FacetField;
component.field = facetField;
fixture.detectChanges();
@@ -104,7 +99,7 @@ describe('SearchFacetFieldComponent', () => {
expect(searchFacetFiltersService.updateSelectedBuckets).toHaveBeenCalled();
});
it('should update query builder only when has bucket to unselect', () => {
it('should update query builder only when has bucket to unselect', () => {
spyOn(queryBuilder, 'update').and.stub();
const field: FacetField = { field: 'f1', label: 'f1' };
@@ -113,7 +108,7 @@ describe('SearchFacetFieldComponent', () => {
expect(queryBuilder.update).not.toHaveBeenCalled();
});
it('should allow to to reset selected buckets', () => {
it('should allow to to reset selected buckets', () => {
const buckets: FacetFieldBucket[] = [
{ label: 'bucket1', checked: true, count: 1, filterQuery: 'q1' },
{ label: 'bucket2', checked: false, count: 1, filterQuery: 'q2' }
@@ -131,7 +126,7 @@ describe('SearchFacetFieldComponent', () => {
expect(component.canResetSelectedBuckets(field)).toBeTruthy();
});
it('should not allow to reset selected buckets', () => {
it('should not allow to reset selected buckets', () => {
const buckets: FacetFieldBucket[] = [
{ label: 'bucket1', checked: false, count: 1, filterQuery: 'q1' },
{ label: 'bucket2', checked: false, count: 1, filterQuery: 'q2' }
@@ -149,7 +144,7 @@ describe('SearchFacetFieldComponent', () => {
expect(component.canResetSelectedBuckets(field)).toEqual(false);
});
it('should reset selected buckets', () => {
it('should reset selected buckets', () => {
spyOn(queryBuilder, 'execute').and.stub();
const buckets: FacetFieldBucket[] = [
{ label: 'bucket1', checked: false, count: 1, filterQuery: 'q1' },
@@ -171,7 +166,7 @@ describe('SearchFacetFieldComponent', () => {
expect(buckets[1].checked).toEqual(false);
});
it('should update query builder upon resetting buckets', () => {
it('should update query builder upon resetting buckets', () => {
spyOn(queryBuilder, 'update').and.stub();
const buckets: FacetFieldBucket[] = [
@@ -191,5 +186,4 @@ describe('SearchFacetFieldComponent', () => {
component.resetSelectedBuckets(field);
expect(queryBuilder.update).toHaveBeenCalled();
});
});
@@ -15,11 +15,10 @@
* limitations under the License.
*/
import { Component, Inject, Input, ViewEncapsulation } from '@angular/core';
import { Component, inject, Input, ViewEncapsulation } from '@angular/core';
import { FacetField } from '../../models/facet-field.interface';
import { MatCheckboxChange } from '@angular/material/checkbox';
import { FacetFieldBucket } from '../../models/facet-field-bucket.interface';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../search-query-service.token';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { FacetWidget } from '../../models/facet-widget.interface';
@@ -33,17 +32,15 @@ import { Subject } from 'rxjs';
encapsulation: ViewEncapsulation.None
})
export class SearchFacetFieldComponent implements FacetWidget {
private queryBuilder = inject(SearchQueryBuilderService);
private searchFacetFiltersService = inject(SearchFacetFiltersService);
private translationService = inject(TranslationService);
@Input()
field!: FacetField;
displayValue$: Subject<string> = new Subject<string>();
constructor(
@Inject(SEARCH_QUERY_SERVICE_TOKEN) public queryBuilder: SearchQueryBuilderService,
private searchFacetFiltersService: SearchFacetFiltersService,
private translationService: TranslationService
) {}
get canUpdateOnChange() {
return this.field.settings?.allowUpdateOnChange ?? true;
}
@@ -18,7 +18,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { SearchFilterAutocompleteChipsComponent } from './search-filter-autocomplete-chips.component';
import { TagService } from '@alfresco/adf-content-services';
import { EMPTY, of } from 'rxjs';
@@ -32,14 +31,13 @@ describe('SearchFilterAutocompleteChipsComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SearchFilterAutocompleteChipsComponent],
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
providers: [{
provide: TagService,
useValue: { getAllTheTags: () => EMPTY }
}]
imports: [ContentTestingModule],
providers: [
{
provide: TagService,
useValue: { getAllTheTags: () => EMPTY }
}
]
});
fixture = TestBed.createComponent(SearchFilterAutocompleteChipsComponent);
@@ -51,8 +49,11 @@ describe('SearchFilterAutocompleteChipsComponent', () => {
update: () => EMPTY
} as any;
component.settings = {
field: 'test', allowUpdateOnChange: true, hideDefaultAction: false, allowOnlyPredefinedValues: false,
autocompleteOptions: [{value: 'option1'}, {value: 'option2'}]
field: 'test',
allowUpdateOnChange: true,
hideDefaultAction: false,
allowOnlyPredefinedValues: false,
autocompleteOptions: [{ value: 'option1' }, { value: 'option2' }]
};
fixture.detectChanges();
});
@@ -65,15 +66,15 @@ describe('SearchFilterAutocompleteChipsComponent', () => {
function addNewOption(value: string) {
const inputElement = fixture.debugElement.query(By.css('adf-search-chip-autocomplete-input input')).nativeElement;
inputElement.value = value;
inputElement.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 13}));
inputElement.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 13 }));
fixture.detectChanges();
}
it('should set autocomplete options on init', (done) => {
component.settings.autocompleteOptions = [{value: 'test 1'}, {value: 'test 2'}];
component.settings.autocompleteOptions = [{ value: 'test 1' }, { value: 'test 2' }];
component.ngOnInit();
component.autocompleteOptions$.subscribe(result => {
expect(result).toEqual([{value: 'test 1'}, {value: 'test 2'}]);
component.autocompleteOptions$.subscribe((result) => {
expect(result).toEqual([{ value: 'test 1' }, { value: 'test 2' }]);
done();
});
});
@@ -82,15 +83,15 @@ describe('SearchFilterAutocompleteChipsComponent', () => {
const tagPagingMock = {
list: {
pagination: {},
entries: [{entry: {tag: 'tag1', id: 'id1'}}, {entry: {tag: 'tag2', id: 'id2'}}]
entries: [{ entry: { tag: 'tag1', id: 'id1' } }, { entry: { tag: 'tag2', id: 'id2' } }]
}
};
component.settings.field = AutocompleteField.TAG;
spyOn(tagService, 'getAllTheTags').and.returnValue(of(tagPagingMock));
component.ngOnInit();
component.autocompleteOptions$.subscribe(result => {
expect(result).toEqual([{value: 'tag1'},{value: 'tag2'}]);
component.autocompleteOptions$.subscribe((result) => {
expect(result).toEqual([{ value: 'tag1' }, { value: 'tag2' }]);
done();
});
});
@@ -106,24 +107,28 @@ describe('SearchFilterAutocompleteChipsComponent', () => {
});
it('should reset value and display value when reset button is clicked', () => {
component.setValue([{value: 'option1'}, {value: 'option2'}]);
component.setValue([{ value: 'option1' }, { value: 'option2' }]);
fixture.detectChanges();
expect(component.selectedOptions).toEqual([{value: 'option1'}, {value: 'option2'}]);
expect(component.selectedOptions).toEqual([{ value: 'option1' }, { value: 'option2' }]);
spyOn(component.context, 'update');
spyOn(component.displayValue$, 'next');
const clearBtn: HTMLButtonElement = fixture.debugElement.query(By.css('[data-automation-id="adf-search-chip-autocomplete-btn-clear"]')).nativeElement;
const clearBtn: HTMLButtonElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-search-chip-autocomplete-btn-clear"]')
).nativeElement;
clearBtn.click();
expect(component.context.queryFragments[component.id]).toBe('');
expect(component.context.update).toHaveBeenCalled();
expect(component.selectedOptions).toEqual( [] );
expect(component.selectedOptions).toEqual([]);
expect(component.displayValue$.next).toHaveBeenCalledWith('');
});
it('should correctly compose the search query', () => {
spyOn(component.context, 'update');
component.selectedOptions = [{value: 'option2'}, {value: 'option1'}];
const applyBtn: HTMLButtonElement = fixture.debugElement.query(By.css('[data-automation-id="adf-search-chip-autocomplete-btn-apply"]')).nativeElement;
component.selectedOptions = [{ value: 'option2' }, { value: 'option1' }];
const applyBtn: HTMLButtonElement = fixture.debugElement.query(
By.css('[data-automation-id="adf-search-chip-autocomplete-btn-apply"]')
).nativeElement;
applyBtn.click();
fixture.detectChanges();
@@ -131,7 +136,7 @@ describe('SearchFilterAutocompleteChipsComponent', () => {
expect(component.context.queryFragments[component.id]).toBe('test:"option2" OR test:"option1"');
component.settings.field = AutocompleteField.CATEGORIES;
component.selectedOptions = [{id: 'test-id', value: 'test'}];
component.selectedOptions = [{ id: 'test-id', value: 'test' }];
applyBtn.click();
fixture.detectChanges();
expect(component.context.queryFragments[component.id]).toBe('cm:categories:"workspace://SpacesStore/test-id"');
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ContentTestingModule } from '../../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { By } from '@angular/platform-browser';
import { SearchFilterList } from '../../../models/search-filter-list.model';
import { SearchFacetChipTabbedComponent } from './search-facet-chip-tabbed.component';
@@ -35,7 +34,7 @@ describe('SearchFacetChipTabbedComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
schemas: [NO_ERRORS_SCHEMA]
});
fixture = TestBed.createComponent(SearchFacetChipTabbedComponent);
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ContentTestingModule } from '../../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { SearchQueryBuilderService } from '../../../services/search-query-builder.service';
import { SearchFilterList } from '../../../models/search-filter-list.model';
import { FacetField } from '../../../models/facet-field.interface';
@@ -38,7 +37,7 @@ describe('SearchFacetTabbedContentComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
schemas: [NO_ERRORS_SCHEMA]
});
fixture = TestBed.createComponent(SearchFacetTabbedContentComponent);
@@ -111,7 +110,7 @@ describe('SearchFacetTabbedContentComponent', () => {
});
it('should display creator tab as active initially and allow navigation', async () => {
let tabs = await getTabs();
const tabs = await getTabs();
expect(await tabs[0].isSelected()).toBeTrue();
expect(await tabs[1].isSelected()).toBeFalse();
@@ -130,9 +129,9 @@ describe('SearchFacetTabbedContentComponent', () => {
addBucketItem('field', 'test');
addBucketItem('field2', 'test2');
expect(component.autocompleteOptions['field'].length).toBe(1);
expect(component.autocompleteOptions['field'][0]).toEqual({value: 'test'});
expect(component.autocompleteOptions['field'][0]).toEqual({ value: 'test' });
expect(component.autocompleteOptions['field2'].length).toBe(1);
expect(component.autocompleteOptions['field2'][0]).toEqual({value: 'test2'});
expect(component.autocompleteOptions['field2'][0]).toEqual({ value: 'test2' });
});
it('should add buckets when items are selected', () => {
@@ -140,7 +139,7 @@ describe('SearchFacetTabbedContentComponent', () => {
addBucketItem('field', 'test');
addBucketItem('field2', 'test2');
component.onOptionsChange([{ value: 'test' }], 'field');
expect(queryBuilder.addUserFacetBucket).toHaveBeenCalledWith('field',component.tabbedFacet.facets['field'].buckets.items[0]);
expect(queryBuilder.addUserFacetBucket).toHaveBeenCalledWith('field', component.tabbedFacet.facets['field'].buckets.items[0]);
});
it('should remove buckets when items are unselected', () => {
@@ -148,7 +147,7 @@ describe('SearchFacetTabbedContentComponent', () => {
addBucketItem('field', 'test');
addBucketItem('field2', 'test2');
component.onOptionsChange([], 'field');
expect(queryBuilder.removeUserFacetBucket).toHaveBeenCalledWith('field',component.tabbedFacet.facets['field'].buckets.items[0]);
expect(queryBuilder.removeUserFacetBucket).toHaveBeenCalledWith('field', component.tabbedFacet.facets['field'].buckets.items[0]);
});
it('should update emit new display value when next elements are selected', () => {
@@ -157,10 +156,12 @@ describe('SearchFacetTabbedContentComponent', () => {
spyOn(component.displayValue$, 'emit');
addBucketItem('field', selectedOption1);
addBucketItem('field', selectedOption2);
component.onOptionsChange([{ value: selectedOption1 }, { value: selectedOption2 }],'field');
component.onOptionsChange([{ value: selectedOption1 }, { value: selectedOption2 }], 'field');
fixture.detectChanges();
expect(component.displayValue$.emit).toHaveBeenCalledWith(`${component.tabbedFacet.facets['field'].label}_LABEL: ${selectedOption1}, ${selectedOption2} `);
expect(component.displayValue$.emit).toHaveBeenCalledWith(
`${component.tabbedFacet.facets['field'].label}_LABEL: ${selectedOption1}, ${selectedOption2} `
);
});
it('should update display value when elements from both tabs are selected', () => {
@@ -169,18 +170,20 @@ describe('SearchFacetTabbedContentComponent', () => {
const displayValueEmitterSpy = spyOn(component.displayValue$, 'emit');
addBucketItem('field', selectedOption1);
addBucketItem('field2', selectedOption2);
component.onOptionsChange([{value: selectedOption1}], 'field');
component.onOptionsChange([{value: selectedOption2}], 'field2');
component.onOptionsChange([{ value: selectedOption1 }], 'field');
component.onOptionsChange([{ value: selectedOption2 }], 'field2');
fixture.detectChanges();
expect(displayValueEmitterSpy).toHaveBeenCalledTimes(2);
expect(displayValueEmitterSpy.calls.allArgs()).toEqual([
[`${component.tabbedFacet.facets['field'].label}_LABEL: ${selectedOption1} `],
[`${component.tabbedFacet.facets['field'].label}_LABEL: ${selectedOption1} ${component.tabbedFacet.facets['field2'].label}_LABEL: ${selectedOption2} `]
[
`${component.tabbedFacet.facets['field'].label}_LABEL: ${selectedOption1} ${component.tabbedFacet.facets['field2'].label}_LABEL: ${selectedOption2} `
]
]);
});
it('should update search query and display value on submit',() => {
it('should update search query and display value on submit', () => {
spyOn(component, 'updateDisplayValue').and.callThrough();
spyOn(component, 'submitValues').and.callThrough();
spyOn(searchFacetService, 'updateSelectedBuckets').and.callThrough();
@@ -15,10 +15,9 @@
* limitations under the License.
*/
import { Component, EventEmitter, Inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewEncapsulation } from '@angular/core';
import { Component, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewEncapsulation } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { SearchQueryBuilderService } from '../../../services/search-query-builder.service';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../../search-query-service.token';
import { FacetWidget } from '../../../models/facet-widget.interface';
import { TranslationService } from '@alfresco/adf-core';
import { AutocompleteOption } from '../../../models/autocomplete-option.interface';
@@ -32,6 +31,10 @@ import { SearchFacetFiltersService } from '../../../services/search-facet-filter
encapsulation: ViewEncapsulation.None
})
export class SearchFacetTabbedContentComponent implements OnInit, OnDestroy, OnChanges, FacetWidget {
private queryBuilder = inject(SearchQueryBuilderService);
private translationService = inject(TranslationService);
private searchFacetFiltersService = inject(SearchFacetFiltersService);
@Input()
tabbedFacet: TabbedFacetField;
@@ -55,11 +58,6 @@ export class SearchFacetTabbedContentComponent implements OnInit, OnDestroy, OnC
autocompleteOptions = {};
selectedOptions = {};
constructor(@Inject(SEARCH_QUERY_SERVICE_TOKEN) private queryBuilder: SearchQueryBuilderService,
private translationService: TranslationService,
private searchFacetFiltersService: SearchFacetFiltersService) {
}
ngOnInit() {
this.tabbedFacet.fields.forEach((field) => {
Object.defineProperty(this.selectedOptions, field, {
@@ -18,7 +18,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchFacetChipComponent } from './search-facet-chip.component';
import { ContentTestingModule } from '../../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { SearchQueryBuilderService } from '../../../services/search-query-builder.service';
import { SearchFilterList } from '../../../models/search-filter-list.model';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@@ -35,7 +34,7 @@ describe('SearchFacetChipComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchFacetChipComponent);
component = fixture.componentInstance;
@@ -1,17 +1,17 @@
<mat-chip-list role="listbox" [attr.aria-label]="'SEARCH.FILTER.ARIA-LABEL.SEARCH_FILTER' | translate">
<ng-container *ngFor="let category of queryBuilder.categories">
<ng-container *ngFor="let category of categories">
<adf-search-widget-chip [category]="category"></adf-search-widget-chip>
</ng-container>
<ng-container *ngIf="facetFiltersService.tabbedFacet && showContextFacets">
<ng-container *ngIf="showContextFacets && tabbedFacet">
<adf-search-facet-chip-tabbed
[tabbedFacet]="facetFiltersService.tabbedFacet"
[tabbedFacet]="tabbedFacet"
[attr.data-automation-id]="facetChipTabbedId" >
</adf-search-facet-chip-tabbed>
</ng-container>
<ng-container *ngIf="facetFiltersService.responseFacets && showContextFacets">
<ng-container *ngFor="let field of facetFiltersService.responseFacets">
<ng-container *ngIf="showContextFacets && responseFacets">
<ng-container *ngFor="let field of responseFacets">
<adf-search-facet-chip [field]="field" [attr.data-automation-id]="'search-fact-chip-' + field.field" ></adf-search-facet-chip>
</ng-container>
</ng-container>
@@ -22,18 +22,8 @@ import { SearchQueryBuilderService } from '../../services/search-query-builder.s
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { By } from '@angular/platform-browser';
import { SearchFacetFieldComponent } from '../search-facet-field/search-facet-field.component';
import { TranslateModule } from '@ngx-translate/core';
import { SearchFilterList } from '../../models/search-filter-list.model';
import {
disabledCategories,
filteredResult,
mockSearchResult,
searchFilter,
simpleCategories,
stepOne,
stepThree,
stepTwo
} from '../../../mock';
import { disabledCategories, filteredResult, mockSearchResult, searchFilter, simpleCategories, stepOne, stepThree, stepTwo } from '../../../mock';
import { AppConfigService } from '@alfresco/adf-core';
import { MatButtonHarness } from '@angular/material/button/testing';
import { HarnessLoader } from '@angular/cdk/testing';
@@ -50,10 +40,7 @@ describe('SearchFilterChipsComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
queryBuilder = TestBed.inject(SearchQueryBuilderService);
appConfigService = TestBed.inject(AppConfigService);
@@ -66,27 +53,41 @@ describe('SearchFilterChipsComponent', () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
facetFields: {
fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
]
},
facetQueries: {
queries: []
}
};
searchFacetFiltersService.responseFacets = [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList()}
searchFacetFiltersService.responseFacets = [
{
type: 'field',
label: 'f1',
field: 'f1',
buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() }
];
searchFacetFiltersService.queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [
{ label: 'b1', metrics: [{value: {count: 6}}], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] },
{
type: 'field',
label: 'f1',
field: 'f1',
buckets: [
{ label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' },
{ label: 'b2', metrics: [{ value: { count: 1 } }], filterQuery: 'filter2' }
]
},
{ type: 'field', label: 'f2', field: 'f2', buckets: [] }
];
const data = {
@@ -107,34 +108,48 @@ describe('SearchFilterChipsComponent', () => {
searchFacetFiltersService.onDataLoaded(data);
expect(searchFacetFiltersService.responseFacets.length).toEqual(2);
expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].checked).toEqual(true, 'should show the already checked item');
expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].checked).toEqual(true);
});
it('should fetch facet fields from response payload and show the newly checked items', async () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
facetFields: {
fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
]
},
facetQueries: {
queries: []
}
};
searchFacetFiltersService.responseFacets = [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList()}
{
type: 'field',
label: 'f1',
field: 'f1',
buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() }
];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [
{ label: 'b1', metrics: [{value: {count: 6}}], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] },
{
type: 'field',
label: 'f1',
field: 'f1',
buckets: [
{ label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' },
{ label: 'b2', metrics: [{ value: { count: 1 } }], filterQuery: 'filter2' }
]
},
{ type: 'field', label: 'f2', field: 'f2', buckets: [] }
];
const data = {
@@ -154,26 +169,34 @@ describe('SearchFilterChipsComponent', () => {
searchFacetFiltersService.onDataLoaded(data);
expect(searchFacetFiltersService.responseFacets.length).toEqual(2);
expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].checked).toEqual(true, 'should show the newly checked item');
expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].checked).toEqual(true);
});
it('should show buckets with 0 values when there are no facet fields on the response payload', async () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
facetFields: {
fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
]
},
facetQueries: {
queries: []
}
};
searchFacetFiltersService.responseFacets = [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList( [
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) },
{
type: 'field',
label: 'f1',
field: 'f1',
buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() }
];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
@@ -203,10 +226,11 @@ describe('SearchFilterChipsComponent', () => {
field: 'query-response',
label: 'query response',
buckets: new SearchFilterList([
{ label: 'q1', query: 'q1', checked: true, metrics: [{value: {count: 1}}] },
{ label: 'q2', query: 'q2', checked: false, metrics: [{value: {count: 1}}] },
{ label: 'q3', query: 'q3', checked: true, metrics: [{value: {count: 1}}] }])
} as any;
{ label: 'q1', query: 'q1', checked: true, metrics: [{ value: { count: 1 } }] },
{ label: 'q2', query: 'q2', checked: false, metrics: [{ value: { count: 1 } }] },
{ label: 'q3', query: 'q3', checked: true, metrics: [{ value: { count: 1 } }] }
])
} as any;
searchFacetFiltersService.responseFacets = [queryResponse];
fixture.detectChanges();
@@ -227,8 +251,7 @@ describe('SearchFilterChipsComponent', () => {
});
describe('widgets', () => {
it('should not show the disabled widget', async () => {
it('should not show the disabled widget', async () => {
appConfigService.config.search = { categories: disabledCategories };
queryBuilder.resetToDefaults();
@@ -237,7 +260,7 @@ describe('SearchFilterChipsComponent', () => {
expect(chips.length).toBe(0);
});
it('should show the widgets only if configured', async () => {
it('should show the widgets only if configured', async () => {
appConfigService.config.search = { categories: simpleCategories };
queryBuilder.resetToDefaults();
@@ -245,7 +268,7 @@ describe('SearchFilterChipsComponent', () => {
expect(chips.length).toBe(2);
const titleElements = fixture.debugElement.queryAll(By.css('.adf-search-filter-placeholder'));
expect(titleElements.map(title => title.nativeElement.innerText.trim())).toEqual(['Name:', 'Type:']);
expect(titleElements.map((title) => title.nativeElement.innerText.trim())).toEqual(['Name:', 'Type:']);
});
it('should be update the search query when name changed', async () => {
@@ -286,9 +309,10 @@ describe('SearchFilterChipsComponent', () => {
fixture.detectChanges();
let sizes = await loader.getAllHarnesses(MatCheckboxHarness.with({ selector: '.adf-search-filter-facet-checkbox' }));
stepOne.forEach(async (item, index) => {
for (const item of stepOne) {
const index = stepOne.indexOf(item);
expect(await sizes[index].getLabelText()).toEqual(item);
});
}
let moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
let lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
@@ -300,9 +324,10 @@ describe('SearchFilterChipsComponent', () => {
fixture.detectChanges();
sizes = await loader.getAllHarnesses(MatCheckboxHarness.with({ selector: '.adf-search-filter-facet-checkbox' }));
stepTwo.forEach(async (item, index) => {
for (const item of stepTwo) {
const index = stepTwo.indexOf(item);
expect(await sizes[index].getLabelText()).toEqual(item);
});
}
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
@@ -312,9 +337,10 @@ describe('SearchFilterChipsComponent', () => {
moreButton.triggerEventHandler('click', {});
fixture.detectChanges();
sizes = await loader.getAllHarnesses(MatCheckboxHarness.with({ selector: '.adf-search-filter-facet-checkbox' }));
stepThree.forEach(async (item, index) => {
for (const item of stepThree) {
const index = stepThree.indexOf(item);
expect(await sizes[index].getLabelText()).toEqual(item);
});
}
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
@@ -325,9 +351,10 @@ describe('SearchFilterChipsComponent', () => {
fixture.detectChanges();
sizes = await loader.getAllHarnesses(MatCheckboxHarness.with({ selector: '.adf-search-filter-facet-checkbox' }));
stepTwo.forEach(async (item, index) => {
for (const item of stepTwo) {
const index = stepTwo.indexOf(item);
expect(await sizes[index].getLabelText()).toEqual(item);
});
}
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
@@ -338,9 +365,10 @@ describe('SearchFilterChipsComponent', () => {
fixture.detectChanges();
sizes = await loader.getAllHarnesses(MatCheckboxHarness.with({ selector: '.adf-search-filter-facet-checkbox' }));
stepOne.forEach(async (item, index) => {
for (const item of stepOne) {
const index = stepOne.indexOf(item);
expect(await sizes[index].getLabelText()).toEqual(item);
});
}
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
@@ -392,23 +420,24 @@ describe('SearchFilterChipsComponent', () => {
fixture.detectChanges();
filteredMenu = await loader.getAllHarnesses(MatCheckboxHarness.with({ selector: '.adf-search-filter-facet-checkbox' }));
filteredResult.forEach(async (item, index) => {
for (const item of filteredResult) {
const index = filteredResult.indexOf(item);
expect(await filteredMenu[index].getLabelText()).toEqual(item);
});
}
const clearButton = await loader.getHarness(MatButtonHarness.with({selector: '[title="SEARCH.FILTER.BUTTONS.CLEAR"]' }));
const clearButton = await loader.getHarness(MatButtonHarness.with({ selector: '[title="SEARCH.FILTER.BUTTONS.CLEAR"]' }));
await clearButton.click();
filteredMenu = await loader.getAllHarnesses(MatCheckboxHarness.with({ selector: '.adf-search-filter-facet-checkbox' }));
stepOne.forEach(async (item, index) => {
for (const item of stepOne) {
const index = stepOne.indexOf(item);
expect(await filteredMenu[index].getLabelText()).toEqual(item);
});
}
await filteredMenu[0].check();
expect(await filteredMenu[0].getLabelText()).toEqual('Extra Small (10239)');
expect(queryBuilder.update).toHaveBeenCalledTimes(1);
});
});
});
@@ -15,12 +15,12 @@
* limitations under the License.
*/
import { Component, Inject, Input, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { Component, inject, Input, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../search-query-service.token';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { FacetField, SearchCategory, TabbedFacetField } from '../../models';
@Component({
selector: 'adf-search-filter-chips',
@@ -29,6 +29,9 @@ import { takeUntil } from 'rxjs/operators';
encapsulation: ViewEncapsulation.None
})
export class SearchFilterChipsComponent implements OnInit, OnDestroy {
private queryBuilder = inject(SearchQueryBuilderService);
private facetFiltersService = inject(SearchFacetFiltersService);
private onDestroy$ = new Subject<void>();
/** Toggles whether to show or not the context facet filters. */
@@ -37,11 +40,17 @@ export class SearchFilterChipsComponent implements OnInit, OnDestroy {
facetChipTabbedId = '';
constructor(
@Inject(SEARCH_QUERY_SERVICE_TOKEN)
public queryBuilder: SearchQueryBuilderService,
public facetFiltersService: SearchFacetFiltersService
) {}
get categories(): SearchCategory[] {
return this.queryBuilder.categories || [];
}
get tabbedFacet(): TabbedFacetField | null {
return this.facetFiltersService.tabbedFacet;
}
get responseFacets(): FacetField[] {
return this.facetFiltersService.responseFacets || [];
}
ngOnInit() {
this.queryBuilder.executed
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchFilterMenuCardComponent } from './search-filter-menu-card.component';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../../testing/content.testing.module';
describe('SearchFilterMenuComponent', () => {
@@ -26,10 +25,7 @@ describe('SearchFilterMenuComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchFilterMenuCardComponent);
component = fixture.componentInstance;
@@ -18,7 +18,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchWidgetChipComponent } from './search-widget-chip.component';
import { simpleCategories } from '../../../../mock';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../../testing/content.testing.module';
import { MatMenuModule } from '@angular/material/menu';
import { By } from '@angular/platform-browser';
@@ -36,7 +35,7 @@ describe('SearchWidgetChipComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatMenuModule, TranslateModule.forRoot(), ContentTestingModule]
imports: [MatMenuModule, ContentTestingModule]
});
queryBuilder = TestBed.inject(SearchQueryBuilderService);
fixture = TestBed.createComponent(SearchWidgetChipComponent);
@@ -17,11 +17,9 @@
import { Subject } from 'rxjs';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { SearchService } from '../../services/search.service';
import { SearchHeaderQueryBuilderService } from '../../services/search-header-query-builder.service';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../search-query-service.token';
import { By } from '@angular/platform-browser';
import { SearchFilterContainerComponent } from './search-filter-container.component';
import { SearchCategory } from '../../models/search-category.interface';
@@ -60,11 +58,8 @@ describe('SearchFilterContainerComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
providers: [
{ provide: SearchService, useValue: searchMock },
{ provide: SEARCH_QUERY_SERVICE_TOKEN, useClass: SearchHeaderQueryBuilderService }
]
imports: [ContentTestingModule],
providers: [{ provide: SearchService, useValue: searchMock }]
});
fixture = TestBed.createComponent(SearchFilterContainerComponent);
component = fixture.componentInstance;
@@ -15,24 +15,12 @@
* limitations under the License.
*/
import {
Component,
Input,
Output,
OnInit,
EventEmitter,
ViewEncapsulation,
ViewChild,
Inject,
OnDestroy,
ElementRef
} from '@angular/core';
import { Component, Input, Output, OnInit, EventEmitter, ViewEncapsulation, ViewChild, OnDestroy, ElementRef } from '@angular/core';
import { ConfigurableFocusTrapFactory, ConfigurableFocusTrap } from '@angular/cdk/a11y';
import { DataColumn, TranslationService } from '@alfresco/adf-core';
import { SearchWidgetContainerComponent } from '../search-widget-container/search-widget-container.component';
import { SearchHeaderQueryBuilderService } from '../../services/search-header-query-builder.service';
import { SearchCategory } from '../../models/search-category.interface';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../search-query-service.token';
import { Subject } from 'rxjs';
import { MatMenuTrigger } from '@angular/material/menu';
import { FilterSearch } from '../../models/filter-search.interface';
@@ -69,7 +57,7 @@ export class SearchFilterContainerComponent implements OnInit, OnDestroy {
private onDestroy$ = new Subject<boolean>();
constructor(
@Inject(SEARCH_QUERY_SERVICE_TOKEN) private searchFilterQueryBuilder: SearchHeaderQueryBuilderService,
private searchFilterQueryBuilder: SearchHeaderQueryBuilderService,
private translationService: TranslationService,
private focusTrapFactory: ConfigurableFocusTrapFactory
) {}
@@ -16,7 +16,6 @@
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../../testing/content.testing.module';
import { SearchFilterCardComponent } from './search-filter-card.component';
@@ -41,10 +40,7 @@ describe('SearchFilterCardComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchFilterCardComponent);
component = fixture.componentInstance;
@@ -37,7 +37,6 @@ import {
stepThree,
stepTwo
} from '../../../mock';
import { TranslateModule } from '@ngx-translate/core';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { SearchFacetFieldComponent } from '../search-facet-field/search-facet-field.component';
import { HarnessLoader } from '@angular/cdk/testing';
@@ -60,7 +59,7 @@ describe('SearchFilterComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
imports: [ContentTestingModule],
providers: [{ provide: SearchService, useValue: searchMock }]
});
searchFacetFiltersService = TestBed.inject(SearchFacetFiltersService);
@@ -163,7 +162,7 @@ describe('SearchFilterComponent', () => {
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList([]) }
];
searchFacetFiltersService.queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [
{
@@ -221,7 +220,7 @@ describe('SearchFilterComponent', () => {
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() }
];
searchFacetFiltersService.queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const data = {
list: {
context: {}
@@ -15,11 +15,10 @@
* limitations under the License.
*/
import { Component, Inject, Input, ViewEncapsulation } from '@angular/core';
import { Component, Input, ViewEncapsulation } from '@angular/core';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
import { FacetFieldBucket } from '../../models/facet-field-bucket.interface';
import { FacetField } from '../../models/facet-field.interface';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../search-query-service.token';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
@Component({
@@ -40,10 +39,7 @@ export class SearchFilterComponent {
};
displayResetButton: boolean;
constructor(
@Inject(SEARCH_QUERY_SERVICE_TOKEN) public queryBuilder: SearchQueryBuilderService,
public facetFiltersService: SearchFacetFiltersService
) {
constructor(public queryBuilder: SearchQueryBuilderService, public facetFiltersService: SearchFacetFiltersService) {
if (queryBuilder.config?.facetQueries) {
this.facetQueriesLabel = queryBuilder.config.facetQueries.label || 'Facet Queries';
this.facetExpanded['query'] = queryBuilder.config.facetQueries.expanded;
@@ -1,8 +1,8 @@
<ng-container *ngIf="queryBuilder.searchForms | async as forms">
<ng-container *ngIf="searchForms$ | async as forms">
<ng-container *ngIf="forms.length === 1">
<button class="adf-search-form adf-search-form-button"
disableRipple mat-button
[disableRipple] mat-button
[title]="getSelected(forms) | translate"
[attr.aria-label]="getSelected(forms) | translate">
<span class="adf-search-form-title">
@@ -15,7 +15,7 @@
<button class="adf-search-form adf-search-form-button"
[matMenuTriggerFor]="menu"
#menuTrigger="matMenuTrigger"
disableRipple
[disableRipple]
mat-button
[title]="getSelected(forms) | translate"
[attr.aria-label]="getSelected(forms) | translate"
@@ -17,9 +17,7 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchFormComponent } from './search-form.component';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../search-query-service.token';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
import { SearchForm } from '../../models/search-form.interface';
import { By } from '@angular/platform-browser';
@@ -41,12 +39,11 @@ describe('SearchFormComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule],
providers: [{ provide: SEARCH_QUERY_SERVICE_TOKEN, useClass: SearchQueryBuilderService }]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchFormComponent);
component = fixture.componentInstance;
queryBuilder = TestBed.inject<SearchQueryBuilderService>(SEARCH_QUERY_SERVICE_TOKEN);
queryBuilder = TestBed.inject(SearchQueryBuilderService);
queryBuilder.searchForms.next(mockSearchForms);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
@@ -15,26 +15,25 @@
* limitations under the License.
*/
import { Component, EventEmitter, Inject, Output, ViewEncapsulation } from '@angular/core';
import { Component, EventEmitter, inject, Output, ViewEncapsulation } from '@angular/core';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
import { SearchForm } from '../../models/search-form.interface';
import { SEARCH_QUERY_SERVICE_TOKEN } from '../../search-query-service.token';
@Component({
selector: 'adf-search-form',
templateUrl: './search-form.component.html',
styleUrls: ['./search-form.component.scss'],
encapsulation: ViewEncapsulation.None
selector: 'adf-search-form',
templateUrl: './search-form.component.html',
styleUrls: ['./search-form.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class SearchFormComponent {
private queryBuilder = inject(SearchQueryBuilderService);
searchForms$ = this.queryBuilder.searchForms;
/** Emitted when the form change */
@Output()
formChange: EventEmitter<SearchForm> = new EventEmitter<SearchForm>();
constructor(@Inject(SEARCH_QUERY_SERVICE_TOKEN) public queryBuilder: SearchQueryBuilderService) {
}
onSelectionChange(form: SearchForm) {
this.queryBuilder.updateSelectedConfiguration(form.index);
this.formChange.emit(form);
@@ -20,7 +20,6 @@ import { MatInputHarness } from '@angular/material/input/testing';
import { SearchInputComponent } from '@alfresco/adf-content-services';
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
describe('SearchInputComponent', () => {
@@ -44,7 +43,7 @@ describe('SearchInputComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule, SearchInputComponent]
imports: [ContentTestingModule, SearchInputComponent]
});
fixture = TestBed.createComponent(SearchInputComponent);
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { LogicalSearchCondition, LogicalSearchFields, SearchLogicalFilterComponent } from './search-logical-filter.component';
@@ -28,7 +27,7 @@ describe('SearchLogicalFilterComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SearchLogicalFilterComponent],
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchLogicalFilterComponent);
@@ -20,7 +20,6 @@ import { SearchFilterList } from '../../models/search-filter-list.model';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { sizeOptions, stepOne, stepThree } from '../../../mock';
import { TranslateModule } from '@ngx-translate/core';
import { HarnessLoader, TestKey } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatCheckboxHarness } from '@angular/material/checkbox/testing';
@@ -33,7 +32,7 @@ describe('SearchCheckListComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ContentTestingModule]
imports: [ContentTestingModule]
});
fixture = TestBed.createComponent(SearchCheckListComponent);
component = fixture.componentInstance;

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