prepare tests for ng-12 upgrade (#7099)

* prepare tests for ng12 upgrade

* fix lint

* fix tests

* test fixes

* fix code and tests

* fix code and tests

* test fixes

* test fixes
This commit is contained in:
Denys Vuika
2021-06-11 07:36:32 +01:00
committed by GitHub
parent 558056b05c
commit eb71a79d1e
112 changed files with 982 additions and 1057 deletions
@@ -25,7 +25,7 @@ import { AspectListDialogComponentData } from './aspect-list-dialog-data.interfa
import { NodesApiService } from 'core'; import { NodesApiService } from 'core';
import { AspectListService } from './aspect-list.service'; import { AspectListService } from './aspect-list.service';
import { delay } from 'rxjs/operators'; import { delay } from 'rxjs/operators';
import { AspectEntry } from '@alfresco/js-api'; import { AspectEntry, MinimalNode } from '@alfresco/js-api';
const aspectListMock: AspectEntry[] = [{ const aspectListMock: AspectEntry[] = [{
entry: { entry: {
@@ -274,7 +274,7 @@ describe('AspectListDialogComponent', () => {
spyOn(aspectListService, 'getAspects').and.returnValue(of([...aspectListMock, ...customAspectListMock])); spyOn(aspectListService, 'getAspects').and.returnValue(of([...aspectListMock, ...customAspectListMock]));
spyOn(aspectListService, 'getVisibleAspects').and.returnValue(['frs:AspectOne']); spyOn(aspectListService, 'getVisibleAspects').and.returnValue(['frs:AspectOne']);
spyOn(aspectListService, 'getCustomAspects').and.returnValue(of(customAspectListMock)); spyOn(aspectListService, 'getCustomAspects').and.returnValue(of(customAspectListMock));
spyOn(nodeService, 'getNode').and.returnValue(of({ id: 'fake-node-id', aspectNames: ['frs:AspectOne', 'cst:customAspect'] }).pipe(delay(0))); spyOn(nodeService, 'getNode').and.returnValue(of(new MinimalNode({ id: 'fake-node-id', aspectNames: ['frs:AspectOne', 'cst:customAspect'] })).pipe(delay(0)));
fixture = TestBed.createComponent(AspectListDialogComponent); fixture = TestBed.createComponent(AspectListDialogComponent);
fixture.componentInstance.data.select = new Subject<string[]>(); fixture.componentInstance.data.select = new Subject<string[]>();
fixture.detectChanges(); fixture.detectChanges();
@@ -127,7 +127,7 @@ describe('AspectListComponent', () => {
}); });
it('should show the loading spinner when result is loading', () => { it('should show the loading spinner when result is loading', () => {
const delayReusult = of([]).pipe(delay(0)); const delayReusult = of(null).pipe(delay(0));
spyOn(nodeService, 'getNode').and.returnValue(delayReusult); spyOn(nodeService, 'getNode').and.returnValue(delayReusult);
spyOn(aspectListService, 'getAspects').and.returnValue(delayReusult); spyOn(aspectListService, 'getAspects').and.returnValue(delayReusult);
fixture.detectChanges(); fixture.detectChanges();
@@ -147,7 +147,7 @@ describe('AspectListComponent', () => {
spyOn(aspectListService, 'getCustomAspects').and.returnValue(of(customAspectListMock)); spyOn(aspectListService, 'getCustomAspects').and.returnValue(of(customAspectListMock));
spyOn(aspectListService, 'getVisibleAspects').and.returnValue(['frs:AspectOne']); spyOn(aspectListService, 'getVisibleAspects').and.returnValue(['frs:AspectOne']);
nodeService = TestBed.inject(NodesApiService); nodeService = TestBed.inject(NodesApiService);
spyOn(nodeService, 'getNode').and.returnValue(of({ id: 'fake-node-id', aspectNames: ['frs:AspectOne'] })); spyOn(nodeService, 'getNode').and.returnValue(of({ id: 'fake-node-id', aspectNames: ['frs:AspectOne'] } as any));
component.nodeId = 'fake-node-id'; component.nodeId = 'fake-node-id';
fixture.detectChanges(); fixture.detectChanges();
}); });
@@ -124,7 +124,7 @@ describe('AspectListService', () => {
componentInstance: { componentInstance: {
error: new Subject<any>() error: new Subject<any>()
} }
}); } as any);
spyOnDialogClose = spyOn(materialDialog, 'closeAll'); spyOnDialogClose = spyOn(materialDialog, 'closeAll');
}); });
@@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { MinimalNode } from '@alfresco/js-api';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, CardViewUpdateService, NodesApiService, setupTestBed } from 'core'; import { AlfrescoApiService, CardViewUpdateService, NodesApiService, setupTestBed } from 'core';
@@ -48,7 +49,7 @@ describe('NodeAspectService', () => {
it('should open the aspect list dialog', () => { it('should open the aspect list dialog', () => {
spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of([])); spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of([]));
spyOn(nodeApiService, 'updateNode').and.returnValue(of({})); spyOn(nodeApiService, 'updateNode').and.returnValue(of(null));
nodeAspectService.updateNodeAspects('fake-node-id'); nodeAspectService.updateNodeAspects('fake-node-id');
expect(aspectListService.openAspectListDialog).toHaveBeenCalledWith('fake-node-id'); expect(aspectListService.openAspectListDialog).toHaveBeenCalledWith('fake-node-id');
}); });
@@ -56,7 +57,7 @@ describe('NodeAspectService', () => {
it('should update the node when the aspect dialog apply the changes', () => { it('should update the node when the aspect dialog apply the changes', () => {
const expectedParameters = { aspectNames: ['a', 'b', 'c'] }; const expectedParameters = { aspectNames: ['a', 'b', 'c'] };
spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c'])); spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c']));
spyOn(nodeApiService, 'updateNode').and.returnValue(of({})); spyOn(nodeApiService, 'updateNode').and.returnValue(of(null));
nodeAspectService.updateNodeAspects('fake-node-id'); nodeAspectService.updateNodeAspects('fake-node-id');
expect(nodeApiService.updateNode).toHaveBeenCalledWith('fake-node-id', expectedParameters); expect(nodeApiService.updateNode).toHaveBeenCalledWith('fake-node-id', expectedParameters);
}); });
@@ -67,7 +68,7 @@ describe('NodeAspectService', () => {
expect(nodeUpdated.aspectNames).toEqual(['a', 'b', 'c']); expect(nodeUpdated.aspectNames).toEqual(['a', 'b', 'c']);
done(); done();
}); });
const fakeNode = { id: 'fake-node-id', aspectNames: ['a', 'b', 'c'] }; const fakeNode = new MinimalNode({ id: 'fake-node-id', aspectNames: ['a', 'b', 'c'] });
spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c'])); spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c']));
spyOn(nodeApiService, 'updateNode').and.returnValue(of(fakeNode)); spyOn(nodeApiService, 'updateNode').and.returnValue(of(fakeNode));
nodeAspectService.updateNodeAspects('fake-node-id'); nodeAspectService.updateNodeAspects('fake-node-id');
@@ -79,7 +80,7 @@ describe('NodeAspectService', () => {
expect(nodeUpdated.aspectNames).toEqual(['a', 'b', 'c']); expect(nodeUpdated.aspectNames).toEqual(['a', 'b', 'c']);
done(); done();
}); });
const fakeNode = { id: 'fake-node-id', aspectNames: ['a', 'b', 'c'] }; const fakeNode = new MinimalNode({ id: 'fake-node-id', aspectNames: ['a', 'b', 'c'] });
spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c'])); spyOn(aspectListService, 'openAspectListDialog').and.returnValue(of(['a', 'b', 'c']));
spyOn(nodeApiService, 'updateNode').and.returnValue(of(fakeNode)); spyOn(nodeApiService, 'updateNode').and.returnValue(of(fakeNode));
nodeAspectService.updateNodeAspects('fake-node-id'); nodeAspectService.updateNodeAspects('fake-node-id');
@@ -310,9 +310,7 @@ describe('ContentMetadataComponent', () => {
const expectedProperties = []; const expectedProperties = [];
component.expanded = true; component.expanded = true;
fixture.detectChanges(); fixture.detectChanges();
spyOn(contentMetadataService, 'getGroupedProperties').and.callFake(() => { spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{ properties: expectedProperties } as any]));
return of([{ properties: expectedProperties }]);
});
spyOn(component, 'showGroup').and.returnValue(true); spyOn(component, 'showGroup').and.returnValue(true);
component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) }); component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) });
@@ -328,7 +326,7 @@ describe('ContentMetadataComponent', () => {
component.expanded = true; component.expanded = true;
component.displayEmpty = false; component.displayEmpty = false;
fixture.detectChanges(); fixture.detectChanges();
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{ properties: [] }])); spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{ properties: [] } as any]));
spyOn(component, 'showGroup').and.returnValue(true); spyOn(component, 'showGroup').and.returnValue(true);
component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) }); component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) });
@@ -343,7 +341,7 @@ describe('ContentMetadataComponent', () => {
it('should hide card views group when the grouped properties are empty', async(() => { it('should hide card views group when the grouped properties are empty', async(() => {
component.expanded = true; component.expanded = true;
fixture.detectChanges(); fixture.detectChanges();
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{ properties: [] }])); spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{ properties: [] } as any]));
component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) }); component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) });
@@ -367,7 +365,7 @@ describe('ContentMetadataComponent', () => {
label: 'To' label: 'To'
}] }]
}; };
spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{ properties: [cardViewGroup] }])); spyOn(contentMetadataService, 'getGroupedProperties').and.returnValue(of([{ properties: [cardViewGroup] } as any]));
component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) }); component.ngOnChanges({ node: new SimpleChange(node, expectedNode, false) });
@@ -103,7 +103,7 @@ describe('ContentMetaDataService', () => {
modifiedByUser: {displayName: 'test-user-modified'}, modifiedByUser: {displayName: 'test-user-modified'},
properties: [] properties: []
}; };
spyOn(contentPropertyService, 'getContentTypeCardItem').and.returnValue(of({ label: 'hello i am a weird content type'})); spyOn(contentPropertyService, 'getContentTypeCardItem').and.returnValue(of({ label: 'hello i am a weird content type'} as any));
service.getContentTypeProperty(fakeNode).subscribe( service.getContentTypeProperty(fakeNode).subscribe(
(res: any) => { (res: any) => {
@@ -130,9 +130,7 @@ describe('ContentMetaDataService', () => {
const fakeNode: Node = <Node> { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } ; const fakeNode: Node = <Node> { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } ;
setConfig('default', { 'exif:exif': '*' }); setConfig('default', { 'exif:exif': '*' });
spyOn(classesApi, 'getClass').and.callFake(() => { spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
return of(exifResponse);
});
service.getGroupedProperties(fakeNode).subscribe( service.getGroupedProperties(fakeNode).subscribe(
(res) => { (res) => {
@@ -150,9 +148,7 @@ describe('ContentMetaDataService', () => {
const fakeNode: Node = <Node> { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } ; const fakeNode: Node = <Node> { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } ;
setConfig('default', { 'exif:exif': '*', 'rma:record': '*' }); setConfig('default', { 'exif:exif': '*', 'rma:record': '*' });
spyOn(classesApi, 'getClass').and.callFake(() => { spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
return of(exifResponse);
});
service.getGroupedProperties(fakeNode).subscribe( service.getGroupedProperties(fakeNode).subscribe(
(res) => { (res) => {
@@ -187,9 +183,7 @@ describe('ContentMetaDataService', () => {
]; ];
setConfig('custom', customLayoutOrientedScheme); setConfig('custom', customLayoutOrientedScheme);
spyOn(classesApi, 'getClass').and.callFake(() => { spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(contentResponse));
return of(contentResponse);
});
service.getGroupedProperties(fakeNode, 'custom').subscribe( service.getGroupedProperties(fakeNode, 'custom').subscribe(
(res) => { (res) => {
@@ -232,9 +226,7 @@ describe('ContentMetaDataService', () => {
]; ];
setConfig('custom', customLayoutOrientedScheme); setConfig('custom', customLayoutOrientedScheme);
spyOn(classesApi, 'getClass').and.callFake(() => { spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(contentResponse));
return of(contentResponse);
});
service.getGroupedProperties(fakeNode, 'custom').subscribe( service.getGroupedProperties(fakeNode, 'custom').subscribe(
(res) => { (res) => {
@@ -268,9 +260,7 @@ describe('ContentMetaDataService', () => {
]; ];
setConfig('custom', customLayoutOrientedScheme); setConfig('custom', customLayoutOrientedScheme);
spyOn(classesApi, 'getClass').and.callFake(() => { spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(contentResponse));
return of(contentResponse);
});
service.getGroupedProperties(fakeNode, 'custom').subscribe( service.getGroupedProperties(fakeNode, 'custom').subscribe(
(res) => { (res) => {
@@ -22,7 +22,7 @@ import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { ContentTypeService } from '../../content-type'; import { ContentTypeService } from '../../content-type';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { Node } from '@alfresco/js-api'; import { Node, TypeEntry } from '@alfresco/js-api';
describe('ContentTypePropertyService', () => { describe('ContentTypePropertyService', () => {
@@ -83,11 +83,7 @@ describe('ContentTypePropertyService', () => {
} }
}; };
const mockSelectOptions = { const mockSelectOptions: TypeEntry[] = [
'list':
{
'pagination': { 'count': 1, 'hasMoreItems': false, 'totalItems': 1, 'skipCount': 0, 'maxItems': 100 },
'entries': [
{ {
'entry': { 'entry': {
'isArchive': true, 'isArchive': true,
@@ -114,9 +110,8 @@ describe('ContentTypePropertyService', () => {
}], }],
'parentId': 'cm:content' 'parentId': 'cm:content'
} }
}]
} }
}; ];
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -18,7 +18,6 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { PropertyDescriptorsService } from './property-descriptors.service'; import { PropertyDescriptorsService } from './property-descriptors.service';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core'; import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { of } from 'rxjs';
import { ClassesApi } from '@alfresco/js-api'; import { ClassesApi } from '@alfresco/js-api';
import { PropertyGroup } from '../interfaces/content-metadata.interfaces'; import { PropertyGroup } from '../interfaces/content-metadata.interfaces';
import { ContentTestingModule } from '../../testing/content.testing.module'; import { ContentTestingModule } from '../../testing/content.testing.module';
@@ -77,7 +76,7 @@ describe('PropertyDescriptorLoaderService', () => {
let counter = 0; let counter = 0;
spyOn(classesApi, 'getClass').and.callFake(() => { spyOn(classesApi, 'getClass').and.callFake(() => {
return of(apiResponses[counter++]); return Promise.resolve(apiResponses[counter++]);
}); });
service.load(['exif:exif', 'cm:content']) service.load(['exif:exif', 'cm:content'])
@@ -90,7 +90,7 @@ describe('ContentNodeDialogService', () => {
componentInstance: { componentInstance: {
error: new Subject<any>() error: new Subject<any>()
} }
}); } as any);
}); });
it('should not open the lock node dialog if have no permission', () => { it('should not open the lock node dialog if have no permission', () => {
@@ -18,7 +18,7 @@
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { Node, NodeEntry, NodePaging, RequestScope, ResultSetPaging, SiteEntry, SitePaging, UserInfo } from '@alfresco/js-api'; import { MinimalNode, Node, NodeEntry, NodePaging, RequestScope, ResultSetPaging, SiteEntry, SitePaging, UserInfo } from '@alfresco/js-api';
import { AppConfigService, FileModel, FileUploadStatus, NodesApiService, setupTestBed, SitesService, UploadService, FileUploadCompleteEvent, DataRow, ThumbnailService, ContentService, DataColumn } from '@alfresco/adf-core'; import { AppConfigService, FileModel, FileUploadStatus, NodesApiService, setupTestBed, SitesService, UploadService, FileUploadCompleteEvent, DataRow, ThumbnailService, ContentService, DataColumn } from '@alfresco/adf-core';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { DropdownBreadcrumbComponent } from '../breadcrumb'; import { DropdownBreadcrumbComponent } from '../breadcrumb';
@@ -105,7 +105,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
searchQueryBuilderService = component.queryBuilderService; searchQueryBuilderService = component.queryBuilderService;
component.queryBuilderService.resetToDefaults(); component.queryBuilderService.resetToDefaults();
spyOn(nodeService, 'getNode').and.returnValue(of({ id: 'fake-node', path: { elements: [{ nodeType: 'st:site', name: 'fake-site'}] } })); spyOn(nodeService, 'getNode').and.returnValue(of(new MinimalNode({ id: 'fake-node', path: { elements: [{ nodeType: 'st:site', name: 'fake-site'}] } })));
searchSpy = spyOn(searchQueryBuilderService, 'execute'); searchSpy = spyOn(searchQueryBuilderService, 'execute');
const fakeSite = new SiteEntry({ entry: { id: 'fake-site', guid: 'fake-site', title: 'fake-site', visibility: 'visible' } }); const fakeSite = new SiteEntry({ entry: { id: 'fake-site', guid: 'fake-site', title: 'fake-site', visibility: 'visible' } });
spyOn(sitesService, 'getSite').and.returnValue(of(fakeSite)); spyOn(sitesService, 'getSite').and.returnValue(of(fakeSite));
@@ -124,12 +124,12 @@ describe('ContentNodeSelectorPanelComponent', () => {
spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } })); spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } }));
spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test')); spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test'));
spyOn(sitesService, 'getSites').and.returnValue(of({ spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({
list: { list: {
entries: [<SiteEntry> { entry: { guid: 'namek', id: 'namek' } }, entries: [<SiteEntry> { entry: { guid: 'namek', id: 'namek' } },
<SiteEntry> { entry: { guid: 'blog', id: 'blog' } }] <SiteEntry> { entry: { guid: 'blog', id: 'blog' } }]
} }
})); })));
component.currentFolderId = 'cat-girl-nuku-nuku'; component.currentFolderId = 'cat-girl-nuku-nuku';
fixture.detectChanges(); fixture.detectChanges();
@@ -229,7 +229,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } })); spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } }));
spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test')); spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test'));
spyOn(sitesService, 'getSites').and.returnValue(of({ list: { entries: [] } })); spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
component.currentFolderId = 'cat-girl-nuku-nuku'; component.currentFolderId = 'cat-girl-nuku-nuku';
fixture.detectChanges(); fixture.detectChanges();
@@ -338,7 +338,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
describe('Site selection', () => { describe('Site selection', () => {
beforeEach(() => { beforeEach(() => {
spyOn(sitesService, 'getSites').and.returnValue(of({ list: { entries: [] } })); spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
component.currentFolderId = 'fake-starting-folder'; component.currentFolderId = 'fake-starting-folder';
}); });
@@ -380,15 +380,15 @@ describe('ContentNodeSelectorPanelComponent', () => {
component.isSelectionValid = (node: Node) => node.isFile; component.isSelectionValid = (node: Node) => node.isFile;
spyOn(documentListService, 'getFolderNode').and.returnValue(of(expectedDefaultFolderNode)); spyOn(documentListService, 'getFolderNode').and.returnValue(of(expectedDefaultFolderNode));
spyOn(documentListService, 'getFolder').and.returnValue(of({ spyOn(documentListService, 'getFolder').and.returnValue(of(new NodePaging({
list: { list: {
pagination: {}, pagination: {},
entries: [], entries: [],
source: {} source: {}
} }
})); })));
spyOn(sitesService, 'getSites').and.returnValue(of({ list: { entries: [] } })); spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
customResourcesService = TestBed.inject(CustomResourcesService); customResourcesService = TestBed.inject(CustomResourcesService);
getCorrespondingNodeIdsSpy = spyOn(customResourcesService, 'getCorrespondingNodeIds').and getCorrespondingNodeIdsSpy = spyOn(customResourcesService, 'getCorrespondingNodeIds').and
@@ -1034,7 +1034,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
const rows = [<DataRow> {}, <DataRow> {}]; const rows = [<DataRow> {}, <DataRow> {}];
component.documentList.data = new ShareDataTableAdapter(thumbnailService, contentService, schema); component.documentList.data = new ShareDataTableAdapter(thumbnailService, contentService, schema);
spyOn(component.documentList.data, 'getRows').and.returnValue(rows); spyOn(component.documentList.data, 'getRows').and.returnValue(rows);
spyOn(sitesService, 'getSites').and.returnValue(of({ list: { entries: [] } })); spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
}); });
it('should the selection become the currently navigated folder when the folder loads (Acts as destination for cases like copy action)', () => { it('should the selection become the currently navigated folder when the folder loads (Acts as destination for cases like copy action)', () => {
@@ -19,7 +19,7 @@ import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/materia
import { CUSTOM_ELEMENTS_SCHEMA, EventEmitter } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA, EventEmitter } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ContentNodeSelectorComponent } from './content-node-selector.component'; import { ContentNodeSelectorComponent } from './content-node-selector.component';
import { Node, NodeEntry } from '@alfresco/js-api'; import { Node, NodeEntry, SitePaging } from '@alfresco/js-api';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { SitesService, ContentService, UploadService, FileModel, FileUploadEvent } from '@alfresco/adf-core'; import { SitesService, ContentService, UploadService, FileModel, FileUploadEvent } from '@alfresco/adf-core';
import { of } from 'rxjs'; import { of } from 'rxjs';
@@ -77,7 +77,7 @@ describe('ContentNodeSelectorComponent', () => {
spyOn(documentListService, 'getFolder').and.callThrough(); spyOn(documentListService, 'getFolder').and.callThrough();
spyOn(documentListService, 'getFolderNode').and.callThrough(); spyOn(documentListService, 'getFolderNode').and.callThrough();
spyOn(sitesService, 'getSites').and.returnValue(of({ list: { entries: [] } })); spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
fixture = TestBed.createComponent(ContentNodeSelectorComponent); fixture = TestBed.createComponent(ContentNodeSelectorComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -76,7 +76,7 @@ describe('ShareDialogComponent', () => {
} }
}; };
spyOn(nodesApiService, 'updateNode').and.returnValue(of({})); spyOn(nodesApiService, 'updateNode').and.returnValue(of(null));
}); });
afterEach(() => { afterEach(() => {
@@ -158,7 +158,7 @@ describe('ShareDialogComponent', () => {
}); });
it('should open a confirmation dialog when unshare button is triggered', () => { it('should open a confirmation dialog when unshare button is triggered', () => {
spyOn(matDialog, 'open').and.returnValue({ beforeClosed: () => of(false) }); spyOn(matDialog, 'open').and.returnValue({ beforeClosed: () => of(false) } as any);
spyOn(sharedLinksApiService, 'deleteSharedLink').and.callThrough(); spyOn(sharedLinksApiService, 'deleteSharedLink').and.callThrough();
node.entry.properties['qshare:sharedId'] = 'sharedId'; node.entry.properties['qshare:sharedId'] = 'sharedId';
@@ -179,7 +179,7 @@ describe('ShareDialogComponent', () => {
}); });
it('should unshare file when confirmation dialog returns true', fakeAsync(() => { it('should unshare file when confirmation dialog returns true', fakeAsync(() => {
spyOn(matDialog, 'open').and.returnValue({ beforeClosed: () => of(true) }); spyOn(matDialog, 'open').and.returnValue({ beforeClosed: () => of(true) } as any);
spyOn(sharedLinksApiService, 'deleteSharedLink').and.returnValue(of({})); spyOn(sharedLinksApiService, 'deleteSharedLink').and.returnValue(of({}));
node.entry.properties['qshare:sharedId'] = 'sharedId'; node.entry.properties['qshare:sharedId'] = 'sharedId';
@@ -199,7 +199,7 @@ describe('ShareDialogComponent', () => {
})); }));
it('should not unshare file when confirmation dialog returns false', fakeAsync(() => { it('should not unshare file when confirmation dialog returns false', fakeAsync(() => {
spyOn(matDialog, 'open').and.returnValue({ beforeClosed: () => of(false) }); spyOn(matDialog, 'open').and.returnValue({ beforeClosed: () => of(false) } as any);
spyOn(sharedLinksApiService, 'deleteSharedLink').and.callThrough(); spyOn(sharedLinksApiService, 'deleteSharedLink').and.callThrough();
node.entry.properties['qshare:sharedId'] = 'sharedId'; node.entry.properties['qshare:sharedId'] = 'sharedId';
@@ -313,7 +313,7 @@ describe('ShareDialogComponent', () => {
describe('datetimepicker type', () => { describe('datetimepicker type', () => {
beforeEach(() => { beforeEach(() => {
spyOn(sharedLinksApiService, 'createSharedLinks').and.returnValue(of({})); spyOn(sharedLinksApiService, 'createSharedLinks').and.returnValue(of(null));
node.entry.allowableOperations = ['update']; node.entry.allowableOperations = ['update'];
component.data = { component.data = {
node, node,
@@ -324,7 +324,7 @@ describe('ShareDialogComponent', () => {
it('it should update node with input date and end of day time when type is `date`', fakeAsync(() => { it('it should update node with input date and end of day time when type is `date`', fakeAsync(() => {
const dateTimePickerType = 'date'; const dateTimePickerType = 'date';
const date = moment('2525-01-01 13:00:00'); const date = moment('2525-01-01 13:00:00');
spyOn(appConfigService, 'get').and.callFake(() => dateTimePickerType); spyOn(appConfigService, 'get').and.callFake(() => dateTimePickerType as any);
fixture.detectChanges(); fixture.detectChanges();
fixture.nativeElement.querySelector('mat-slide-toggle[data-automation-id="adf-expire-toggle"] label') fixture.nativeElement.querySelector('mat-slide-toggle[data-automation-id="adf-expire-toggle"] label')
@@ -93,7 +93,7 @@ describe('FolderDialogComponent', () => {
}); });
it('should submit updated values if form is valid', () => { it('should submit updated values if form is valid', () => {
spyOn(nodesApi, 'updateNode').and.returnValue(of({})); spyOn(nodesApi, 'updateNode').and.returnValue(of(null));
component.form.controls['name'].setValue('folder-name-update'); component.form.controls['name'].setValue('folder-name-update');
component.form.controls['title'].setValue('folder-title-update'); component.form.controls['title'].setValue('folder-title-update');
@@ -114,7 +114,7 @@ describe('FolderDialogComponent', () => {
}); });
it('should call dialog to close with form data when submit is successfully', () => { it('should call dialog to close with form data when submit is successfully', () => {
const folder = { const folder: any = {
data: 'folder-data' data: 'folder-data'
}; };
@@ -126,7 +126,7 @@ describe('FolderDialogComponent', () => {
}); });
it('should emit success output event with folder when submit is successful', async(() => { it('should emit success output event with folder when submit is successful', async(() => {
const folder = { data: 'folder-data' }; const folder: any = { data: 'folder-data' };
let expectedNode = null; let expectedNode = null;
spyOn(nodesApi, 'updateNode').and.returnValue(of(folder)); spyOn(nodesApi, 'updateNode').and.returnValue(of(folder));
@@ -191,7 +191,7 @@ describe('FolderDialogComponent', () => {
}); });
it('should submit updated values if form is valid', () => { it('should submit updated values if form is valid', () => {
spyOn(nodesApi, 'createFolder').and.returnValue(of({})); spyOn(nodesApi, 'createFolder').and.returnValue(of(null));
component.form.controls['name'].setValue('folder-name-update'); component.form.controls['name'].setValue('folder-name-update');
component.form.controls['title'].setValue('folder-title-update'); component.form.controls['title'].setValue('folder-title-update');
@@ -213,7 +213,7 @@ describe('FolderDialogComponent', () => {
}); });
it('should submit updated values if form is valid (with custom nodeType)', () => { it('should submit updated values if form is valid (with custom nodeType)', () => {
spyOn(nodesApi, 'createFolder').and.returnValue(of({})); spyOn(nodesApi, 'createFolder').and.returnValue(of(null));
component.form.controls['name'].setValue('folder-name-update'); component.form.controls['name'].setValue('folder-name-update');
component.form.controls['title'].setValue('folder-title-update'); component.form.controls['title'].setValue('folder-title-update');
@@ -236,7 +236,7 @@ describe('FolderDialogComponent', () => {
}); });
it('should call dialog to close with form data when submit is successfully', () => { it('should call dialog to close with form data when submit is successfully', () => {
const folder = { const folder: any = {
data: 'folder-data' data: 'folder-data'
}; };
@@ -24,6 +24,7 @@ import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { delay } from 'rxjs/operators'; import { delay } from 'rxjs/operators';
import { SiteEntry } from '@alfresco/js-api';
describe('LibraryDialogComponent', () => { describe('LibraryDialogComponent', () => {
let fixture: ComponentFixture<LibraryDialogComponent>; let fixture: ComponentFixture<LibraryDialogComponent>;
@@ -128,7 +129,7 @@ describe('LibraryDialogComponent', () => {
it('should create site when form is valid', fakeAsync(() => { it('should create site when form is valid', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'createSite').and.returnValue( spyOn(sitesService, 'createSite').and.returnValue(
of({entry: {id: 'fake-id'}}).pipe(delay(100)) of({entry: {id: 'fake-id'}} as SiteEntry).pipe(delay(100))
); );
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => {
return throwError('error'); return throwError('error');
@@ -163,9 +164,7 @@ describe('LibraryDialogComponent', () => {
it('should not create site when form is invalid', fakeAsync(() => { it('should not create site when form is invalid', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'createSite').and.returnValue( spyOn(sitesService, 'createSite').and.returnValue(of(null));
Promise.resolve({})
);
spyOn(sitesService, 'getSite').and.returnValue(of(null)); spyOn(sitesService, 'getSite').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
@@ -99,7 +99,7 @@ describe('NodeLockDialogComponent', () => {
}); });
it('should submit the form and lock the node', () => { it('should submit the form and lock the node', () => {
spyOn(alfrescoApi.nodesApi, 'lockNode').and.returnValue(Promise.resolve({})); spyOn(alfrescoApi.nodesApi, 'lockNode').and.returnValue(Promise.resolve(null));
component.submit(); component.submit();
@@ -114,7 +114,7 @@ describe('NodeLockDialogComponent', () => {
}); });
it('should submit the form and unlock the node', () => { it('should submit the form and unlock the node', () => {
spyOn(alfrescoApi.nodesApi, 'unlockNode').and.returnValue(Promise.resolve({})); spyOn(alfrescoApi.nodesApi, 'unlockNode').and.returnValue(Promise.resolve(null));
component.form.controls['isLocked'].setValue(false); component.form.controls['isLocked'].setValue(false);
component.submit(); component.submit();
@@ -123,7 +123,7 @@ describe('NodeLockDialogComponent', () => {
}); });
it('should call dialog to close with form data when submit is successfully', fakeAsync(() => { it('should call dialog to close with form data when submit is successfully', fakeAsync(() => {
const node = { entry: {} }; const node: any = { entry: {} };
spyOn(alfrescoApi.nodesApi, 'lockNode').and.returnValue(Promise.resolve(node)); spyOn(alfrescoApi.nodesApi, 'lockNode').and.returnValue(Promise.resolve(node));
component.submit(); component.submit();
@@ -53,11 +53,12 @@ import { DocumentListService } from './../services/document-list.service';
import { CustomResourcesService } from './../services/custom-resources.service'; import { CustomResourcesService } from './../services/custom-resources.service';
import { DocumentListComponent } from './document-list.component'; import { DocumentListComponent } from './document-list.component';
import { ContentTestingModule } from '../../testing/content.testing.module'; import { ContentTestingModule } from '../../testing/content.testing.module';
import { NodeEntry } from '@alfresco/js-api'; import { FavoritePaging, NodeEntry } from '@alfresco/js-api';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { DocumentListModule } from '../document-list.module'; import { DocumentListModule } from '../document-list.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { ShareDataRow } from '../data/share-data-row.model'; import { ShareDataRow } from '../data/share-data-row.model';
import { DocumentLoaderNode } from '../models/document-folder.model';
describe('DocumentList', () => { describe('DocumentList', () => {
@@ -100,23 +101,15 @@ describe('DocumentList', () => {
thumbnailService = TestBed.inject(ThumbnailService); thumbnailService = TestBed.inject(ThumbnailService);
contentService = TestBed.inject(ContentService); contentService = TestBed.inject(ContentService);
spyFolder = spyOn(documentListService, 'getFolder').and.callFake(() => { spyFolder = spyOn(documentListService, 'getFolder').and.returnValue(of({ list: {} }));
return Promise.resolve({ list: {} }); spyFolderNode = spyOn(documentListService, 'getFolderNode').and.returnValue(of(new NodeEntry({ entry: {} })));
}); spyOn(apiService.nodesApi, 'getNode').and.returnValue(Promise.resolve(new NodeEntry({ entry: {} })));
spyFolderNode = spyOn(documentListService, 'getFolderNode').and.callFake(() => {
return Promise.resolve({ entry: {} });
});
spyOn(apiService.nodesApi, 'getNode').and.callFake(() => {
return Promise.resolve({ entry: {} });
});
documentList.ngOnInit(); documentList.ngOnInit();
documentList.currentFolderId = 'no-node'; documentList.currentFolderId = 'no-node';
spyGetSites = spyOn(customResourcesService.sitesApi, 'listSites').and.returnValue(Promise.resolve(fakeGetSitesAnswer)); spyGetSites = spyOn(customResourcesService.sitesApi, 'listSites').and.returnValue(Promise.resolve(fakeGetSitesAnswer));
spyFavorite = spyOn(customResourcesService.favoritesApi, 'listFavorites').and.returnValue(Promise.resolve({ list: { entries: [] } })); spyFavorite = spyOn(customResourcesService.favoritesApi, 'listFavorites').and.returnValue(Promise.resolve(new FavoritePaging({ list: { entries: [] } })));
}); });
afterEach(() => { afterEach(() => {
@@ -871,7 +864,7 @@ describe('DocumentList', () => {
it('should display folder content on click', () => { it('should display folder content on click', () => {
const node = new FolderNode('<display name>'); const node = new FolderNode('<display name>');
spyOn(documentList, 'loadFolder').and.returnValue(Promise.resolve(true)); spyOn(documentList, 'loadFolder').and.stub();
documentList.navigationMode = DocumentListComponent.SINGLE_CLICK_NAVIGATION; documentList.navigationMode = DocumentListComponent.SINGLE_CLICK_NAVIGATION;
documentList.onNodeClick(node); documentList.onNodeClick(node);
@@ -1236,7 +1229,7 @@ describe('DocumentList', () => {
}); });
it('should load folder by ID on init', async () => { it('should load folder by ID on init', async () => {
spyOn(documentList, 'loadFolder').and.returnValue(Promise.resolve()); spyOn(documentList, 'loadFolder').and.stub();
fixture.detectChanges(); fixture.detectChanges();
@@ -1328,7 +1321,7 @@ describe('DocumentList', () => {
it('should allow to perform navigation for virtual sources', () => { it('should allow to perform navigation for virtual sources', () => {
spyFolderNode = spyOn(documentListService, 'loadFolderByNodeId').and.callFake(() => { spyFolderNode = spyOn(documentListService, 'loadFolderByNodeId').and.callFake(() => {
return of({ currentNode: {}, children: { list: { pagination: {} } } }); return of(new DocumentLoaderNode(null, { list: { pagination: {} } }));
}); });
const sources = ['-trashcan-', '-sharedlinks-', '-sites-', '-mysites-', '-favorites-', '-recent-']; const sources = ['-trashcan-', '-sharedlinks-', '-sites-', '-mysites-', '-favorites-', '-recent-'];
@@ -19,6 +19,7 @@ import { CustomResourcesService } from './custom-resources.service';
import { PaginationModel } from '@alfresco/adf-core'; import { PaginationModel } from '@alfresco/adf-core';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { ContentTestingModule } from '../../testing/content.testing.module'; import { ContentTestingModule } from '../../testing/content.testing.module';
import { FavoritePaging } from '@alfresco/js-api';
describe('CustomResourcesService', () => { describe('CustomResourcesService', () => {
let customResourcesService: CustomResourcesService; let customResourcesService: CustomResourcesService;
@@ -33,7 +34,7 @@ describe('CustomResourcesService', () => {
describe('loadFavorites', () => { describe('loadFavorites', () => {
it('should return a list of items with default properties when target properties does not exist', (done) => { it('should return a list of items with default properties when target properties does not exist', (done) => {
spyOn(customResourcesService.favoritesApi, 'listFavorites').and.returnValue(Promise.resolve({ spyOn(customResourcesService.favoritesApi, 'listFavorites').and.returnValue(Promise.resolve(new FavoritePaging({
list: { list: {
entries: [ entries: [
{ {
@@ -48,7 +49,7 @@ describe('CustomResourcesService', () => {
} }
] ]
} }
})); })));
const pagination: PaginationModel = { const pagination: PaginationModel = {
maxItems: 100, maxItems: 100,
skipCount: 0 skipCount: 0
@@ -72,7 +73,7 @@ describe('CustomResourcesService', () => {
}); });
it('should return a list of items with merged properties when target properties exist', (done) => { it('should return a list of items with merged properties when target properties exist', (done) => {
spyOn(customResourcesService.favoritesApi, 'listFavorites').and.returnValue(Promise.resolve({ spyOn(customResourcesService.favoritesApi, 'listFavorites').and.returnValue(Promise.resolve(new FavoritePaging({
list: { list: {
entries: [ entries: [
{ {
@@ -90,7 +91,7 @@ describe('CustomResourcesService', () => {
} }
] ]
} }
})); })));
const pagination: PaginationModel = { const pagination: PaginationModel = {
maxItems: 100, maxItems: 100,
skipCount: 0 skipCount: 0
@@ -69,7 +69,7 @@ export class DocumentListService implements DocumentListLoader {
* @param targetParentId The id of the folder where the node will be moved * @param targetParentId The id of the folder where the node will be moved
* @returns NodeEntry for the moved node * @returns NodeEntry for the moved node
*/ */
moveNode(nodeId: string, targetParentId: string) { moveNode(nodeId: string, targetParentId: string): Observable<NodeEntry> {
return from(this.apiService.getInstance().nodes.moveNode(nodeId, { targetParentId })).pipe( return from(this.apiService.getInstance().nodes.moveNode(nodeId, { targetParentId })).pipe(
catchError((err) => this.handleError(err)) catchError((err) => this.handleError(err))
); );
@@ -16,7 +16,7 @@
*/ */
import { async, TestBed } from '@angular/core/testing'; import { async, TestBed } from '@angular/core/testing';
import { Node } from '@alfresco/js-api'; import { Node, NodeEntry } from '@alfresco/js-api';
import { AppConfigService, setupTestBed } from '@alfresco/adf-core'; import { AppConfigService, setupTestBed } from '@alfresco/adf-core';
import { DocumentListService } from './document-list.service'; import { DocumentListService } from './document-list.service';
import { NodeActionsService } from './node-actions.service'; import { NodeActionsService } from './node-actions.service';
@@ -59,7 +59,7 @@ describe('NodeActionsService', () => {
}); });
it('should be able to copy content', async(() => { it('should be able to copy content', async(() => {
spyOn(documentListService, 'copyNode').and.returnValue(of('FAKE-OK')); spyOn(documentListService, 'copyNode').and.returnValue(of(new NodeEntry()));
spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode])); spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode]));
service.copyContent(fakeNode, 'allowed').subscribe((value) => { service.copyContent(fakeNode, 'allowed').subscribe((value) => {
@@ -68,7 +68,7 @@ describe('NodeActionsService', () => {
})); }));
it('should be able to move content', async(() => { it('should be able to move content', async(() => {
spyOn(documentListService, 'moveNode').and.returnValue(of('FAKE-OK')); spyOn(documentListService, 'moveNode').and.returnValue(of(new NodeEntry()));
spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode])); spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode]));
service.moveContent(fakeNode, 'allowed').subscribe((value) => { service.moveContent(fakeNode, 'allowed').subscribe((value) => {
@@ -77,7 +77,7 @@ describe('NodeActionsService', () => {
})); }));
it('should be able to move folder', async(() => { it('should be able to move folder', async(() => {
spyOn(documentListService, 'moveNode').and.returnValue(of('FAKE-OK')); spyOn(documentListService, 'moveNode').and.returnValue(of(new NodeEntry()));
spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode])); spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode]));
service.moveFolder(fakeNode, 'allowed').subscribe((value) => { service.moveFolder(fakeNode, 'allowed').subscribe((value) => {
@@ -86,7 +86,7 @@ describe('NodeActionsService', () => {
})); }));
it('should be able to copy folder', async(() => { it('should be able to copy folder', async(() => {
spyOn(documentListService, 'copyNode').and.returnValue(of('FAKE-OK')); spyOn(documentListService, 'copyNode').and.returnValue(of(new NodeEntry()));
spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode])); spyOn(contentDialogService, 'openCopyMoveDialog').and.returnValue(of([fakeNode]));
service.copyFolder(fakeNode, 'allowed').subscribe((value) => { service.copyFolder(fakeNode, 'allowed').subscribe((value) => {
@@ -17,7 +17,7 @@
import { Component, ViewChild } from '@angular/core'; import { Component, ViewChild } from '@angular/core';
import { SearchComponent } from '../search/components/search.component'; import { SearchComponent } from '../search/components/search.component';
import { QueryBody } from '@alfresco/js-api'; import { QueryBody, ResultSetPaging } from '@alfresco/js-api';
const entryItem = { const entryItem = {
entry: { entry: {
@@ -53,21 +53,21 @@ const entryDifferentItem = {
} }
}; };
export let result = { export let result = new ResultSetPaging({
list: { list: {
entries: [ entries: [
entryItem entryItem
] ]
} }
}; });
export let differentResult = { export let differentResult = new ResultSetPaging({
list: { list: {
entries: [ entries: [
entryDifferentItem entryDifferentItem
] ]
} }
}; });
export let results = { export let results = {
list: { list: {
@@ -171,7 +171,7 @@ export function getFakeSitePagingLastPage(): SitePaging {
} }
export function getFakeSitePagingWithMembers() { export function getFakeSitePagingWithMembers() {
return { return new SitePaging({
'list': { 'list': {
'entries': [{ 'entries': [{
'entry': { 'entry': {
@@ -289,5 +289,5 @@ export function getFakeSitePagingWithMembers() {
} }
] ]
} }
}; });
} }
@@ -42,9 +42,8 @@ describe('AddPermissionComponent', () => {
beforeEach(() => { beforeEach(() => {
nodePermissionService = TestBed.inject(NodePermissionService); nodePermissionService = TestBed.inject(NodePermissionService);
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue( const response: any = { node: { id: 'fake-node', allowableOperations: ['updatePermissions']}, roles: [{ label: 'Test' , role: 'test'}] };
of({ node: { id: 'fake-node', allowableOperations: ['updatePermissions']}, roles: [{ label: 'Test' , role: 'test'}] }) spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of(response));
);
fixture = TestBed.createComponent(AddPermissionComponent); fixture = TestBed.createComponent(AddPermissionComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
fixture.detectChanges(); fixture.detectChanges();
@@ -86,7 +85,7 @@ describe('AddPermissionComponent', () => {
it('should emit a success event when the node is updated', async (done) => { it('should emit a success event when the node is updated', async (done) => {
fixture.componentInstance.selectedItems = fakeAuthorityResults; fixture.componentInstance.selectedItems = fakeAuthorityResults;
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of({ id: 'fake-node-id'})); spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of(new Node({ id: 'fake-node-id'})));
fixture.componentInstance.success.subscribe((node) => { fixture.componentInstance.success.subscribe((node) => {
expect(node.id).toBe('fake-node-id'); expect(node.id).toBe('fake-node-id');
@@ -101,7 +100,7 @@ describe('AddPermissionComponent', () => {
it('should NOT emit a success event when the user does not have permission to update the node', () => { it('should NOT emit a success event when the user does not have permission to update the node', () => {
fixture.componentInstance.selectedItems = fakeAuthorityResults; fixture.componentInstance.selectedItems = fakeAuthorityResults;
fixture.componentInstance.currentNode = new Node({ id: 'fake-node-id' }); fixture.componentInstance.currentNode = new Node({ id: 'fake-node-id' });
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of({ id: 'fake-node-id' })); spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of(new Node({ id: 'fake-node-id' })));
const spySuccess = spyOn(fixture.componentInstance, 'success'); const spySuccess = spyOn(fixture.componentInstance, 'success');
fixture.componentInstance.applySelection(); fixture.componentInstance.applySelection();
@@ -34,6 +34,7 @@ import {
fakeSiteRoles fakeSiteRoles
} from '../../../mock/permission-list.component.mock'; } from '../../../mock/permission-list.component.mock';
import { ContentTestingModule } from '../../../testing/content.testing.module'; import { ContentTestingModule } from '../../../testing/content.testing.module';
import { MinimalNode } from '@alfresco/js-api';
describe('PermissionListComponent', () => { describe('PermissionListComponent', () => {
@@ -221,7 +222,7 @@ describe('PermissionListComponent', () => {
}); });
it('should update the role when another value is chosen', async () => { it('should update the role when another value is chosen', async () => {
spyOn(nodeService, 'updateNode').and.returnValue(of({id: 'fake-uwpdated-node'})); spyOn(nodeService, 'updateNode').and.returnValue(of(new MinimalNode({id: 'fake-uwpdated-node'})));
searchQuerySpy.and.returnValue(of(fakeEmptyResponse)); searchQuerySpy.and.returnValue(of(fakeEmptyResponse));
component.ngOnInit(); component.ngOnInit();
@@ -242,7 +243,7 @@ describe('PermissionListComponent', () => {
}); });
it('should delete the person', async () => { it('should delete the person', async () => {
spyOn(nodeService, 'updateNode').and.returnValue(of({id: 'fake-uwpdated-node'})); spyOn(nodeService, 'updateNode').and.returnValue(of(new MinimalNode({id: 'fake-uwpdated-node'})));
searchQuerySpy.and.returnValue(of(fakeEmptyResponse)); searchQuerySpy.and.returnValue(of(fakeEmptyResponse));
component.ngOnInit(); component.ngOnInit();
await fixture.detectChanges(); await fixture.detectChanges();
@@ -53,7 +53,7 @@ describe('NodePermissionDialogService', () => {
componentInstance: { componentInstance: {
error: new Subject<any>() error: new Subject<any>()
} }
}); } as any);
}); });
describe('when node has permission to update permissions', () => { describe('when node has permission to update permissions', () => {
@@ -70,8 +70,8 @@ describe('NodePermissionDialogService', () => {
}); });
it('should return the updated node', (done) => { it('should return the updated node', (done) => {
spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of({id : 'fake-node-updated'})); spyOn(nodePermissionService, 'updateNodePermissions').and.returnValue(of(new Node({id : 'fake-node-updated'})));
spyOn(service, 'openAddPermissionDialog').and.returnValue(of({})); spyOn(service, 'openAddPermissionDialog').and.returnValue(of(null));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakePermissionNode, roles: [] })); spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakePermissionNode, roles: [] }));
service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe((node) => { service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe((node) => {
expect(node.id).toBe('fake-node-updated'); expect(node.id).toBe('fake-node-updated');
@@ -81,7 +81,7 @@ describe('NodePermissionDialogService', () => {
it('should throw an error if the update of the node fails', (done) => { 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({})); spyOn(service, 'openAddPermissionDialog').and.returnValue(of(null));
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakePermissionNode, roles: [] })); spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({ node: fakePermissionNode, roles: [] }));
service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe(() => { service.updateNodePermissionByDialog('fake-node-id', 'fake-title').subscribe(() => {
throwError('This call should fail'); throwError('This call should fail');
@@ -84,7 +84,7 @@ describe('SearchControlComponent', () => {
component = fixture.componentInstance; component = fixture.componentInstance;
element = fixture.nativeElement; element = fixture.nativeElement;
searchServiceSpy = spyOn(searchService, 'search').and.returnValue(of('')); searchServiceSpy = spyOn(searchService, 'search').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
}); });
@@ -115,7 +115,7 @@ describe('SearchFilterContainerComponent', () => {
it('should emit filterChange after the Apply button is clicked', async (done) => { it('should emit filterChange after the Apply button is clicked', async (done) => {
spyOn(alfrescoApiService.searchApi, 'search').and.returnValue(Promise.resolve(fakeNodePaging)); spyOn(alfrescoApiService.searchApi, 'search').and.returnValue(Promise.resolve(fakeNodePaging));
spyOn(queryBuilder, 'buildQuery').and.returnValue({}); spyOn(queryBuilder, 'buildQuery').and.returnValue(null);
component.filterChange.subscribe(() => { component.filterChange.subscribe(() => {
done(); done();
}); });
@@ -147,7 +147,7 @@ describe('SearchFilterContainerComponent', () => {
it('should emit filterChange after the Clear button is clicked', async (done) => { it('should emit filterChange after the Clear button is clicked', async (done) => {
spyOn(alfrescoApiService.searchApi, 'search').and.returnValue(Promise.resolve(fakeNodePaging)); spyOn(alfrescoApiService.searchApi, 'search').and.returnValue(Promise.resolve(fakeNodePaging));
spyOn(queryBuilder, 'buildQuery').and.returnValue({}); spyOn(queryBuilder, 'buildQuery').and.returnValue(null);
component.filterChange.subscribe(() => { component.filterChange.subscribe(() => {
done(); done();
}); });
@@ -164,7 +164,7 @@ describe('SearchFilterContainerComponent', () => {
}); });
it('should emit filterChange after the Enter key is pressed', async (done) => { it('should emit filterChange after the Enter key is pressed', async (done) => {
spyOn(queryBuilder, 'buildQuery').and.returnValue({}); spyOn(queryBuilder, 'buildQuery').and.returnValue(null);
component.filterChange.subscribe(() => { component.filterChange.subscribe(() => {
done(); done();
}); });
@@ -22,20 +22,21 @@ import { ContentTestingModule } from '../../testing/content.testing.module';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { TreeBaseNode } from '../models/tree-view.model'; import { TreeBaseNode } from '../models/tree-view.model';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { NodePaging } from '@alfresco/js-api';
describe('TreeViewService', () => { describe('TreeViewService', () => {
let service: TreeViewService; let service: TreeViewService;
let nodeService: NodesApiService; let nodeService: NodesApiService;
const fakeNodeList = { list: { entries: [ const fakeNodeList = new NodePaging({ list: { entries: [
{ entry: { id: 'fake-node-id', name: 'fake-node-name', isFolder: true } } { entry: { id: 'fake-node-id', name: 'fake-node-name', isFolder: true } }
] } }; ] } });
const fakeMixedNodeList = { list: { entries: [ const fakeMixedNodeList = new NodePaging({ list: { entries: [
{ entry: { id: 'fake-node-id', name: 'fake-node-name', isFolder: true } }, { entry: { id: 'fake-node-id', name: 'fake-node-name', isFolder: true } },
{ entry: { id: 'fake-file-id', name: 'fake-file-name', isFolder: false } } { entry: { id: 'fake-file-id', name: 'fake-file-name', isFolder: false } }
] } }; ] } });
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -77,7 +77,7 @@ describe('VersionListComponent', () => {
afterClosed() { afterClosed() {
return of(false); return of(false);
} }
}); } as any);
component.deleteVersion('1'); component.deleteVersion('1');
@@ -91,7 +91,7 @@ describe('VersionListComponent', () => {
afterClosed() { afterClosed() {
return of(true); return of(true);
} }
}); } as any);
spyOn(alfrescoApiService.versionsApi, 'deleteVersion').and.returnValue(Promise.resolve(true)); spyOn(alfrescoApiService.versionsApi, 'deleteVersion').and.returnValue(Promise.resolve(true));
@@ -108,7 +108,7 @@ describe('VersionListComponent', () => {
afterClosed() { afterClosed() {
return of(false); return of(false);
} }
}); } as any);
spyOn(alfrescoApiService.versionsApi, 'deleteVersion').and.returnValue(Promise.resolve(true)); spyOn(alfrescoApiService.versionsApi, 'deleteVersion').and.returnValue(Promise.resolve(true));
@@ -157,7 +157,7 @@ describe('VersionListComponent', () => {
it('should show the versions after loading', (done) => { it('should show the versions after loading', (done) => {
fixture.detectChanges(); fixture.detectChanges();
spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and.callFake(() => { spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and.callFake(() => {
return Promise.resolve({ return Promise.resolve(new VersionPaging({
list: { list: {
entries: [ entries: [
{ {
@@ -165,7 +165,7 @@ describe('VersionListComponent', () => {
} }
] ]
} }
}); }));
}); });
component.ngOnChanges(); component.ngOnChanges();
@@ -186,7 +186,7 @@ describe('VersionListComponent', () => {
it('should NOT show the versions comments if input property is set not to show them', (done) => { it('should NOT show the versions comments if input property is set not to show them', (done) => {
spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and
.callFake(() => Promise.resolve( .callFake(() => Promise.resolve(
{ new VersionPaging({
list: { list: {
entries: [ entries: [
{ {
@@ -194,7 +194,7 @@ describe('VersionListComponent', () => {
} }
] ]
} }
} })
)); ));
component.showComments = false; component.showComments = false;
@@ -219,7 +219,7 @@ describe('VersionListComponent', () => {
versionComment: 'test-version-comment' versionComment: 'test-version-comment'
} }
}; };
spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and.returnValue(Promise.resolve({ list: { entries: [versionEntry] } })); spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and.returnValue(Promise.resolve(new VersionPaging({ list: { entries: [versionEntry] } })));
spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValue('the/download/url'); spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValue('the/download/url');
fixture.detectChanges(); fixture.detectChanges();
@@ -329,7 +329,7 @@ describe('VersionListComponent', () => {
const spyOnListVersionHistory = spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and const spyOnListVersionHistory = spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and
.callFake(() => Promise.resolve({ list: { entries: versionTest } })); .callFake(() => Promise.resolve({ list: { entries: versionTest } }));
spyOn(alfrescoApiService.versionsApi, 'revertVersion').and.callFake(() => Promise.resolve()); spyOn(alfrescoApiService.versionsApi, 'revertVersion').and.callFake(() => Promise.resolve(null));
component.restore(versionId); component.restore(versionId);
fixture.detectChanges(); fixture.detectChanges();
@@ -19,7 +19,7 @@ import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core'; import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { Node } from '@alfresco/js-api'; import { Node, VersionPaging } from '@alfresco/js-api';
import { VersionManagerComponent } from './version-manager.component'; import { VersionManagerComponent } from './version-manager.component';
import { ContentTestingModule } from '../testing/content.testing.module'; import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
@@ -59,7 +59,7 @@ describe('VersionManagerComponent', () => {
alfrescoApiService = TestBed.inject(AlfrescoApiService); alfrescoApiService = TestBed.inject(AlfrescoApiService);
spyOnListVersionHistory = spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and spyOnListVersionHistory = spyOn(alfrescoApiService.versionsApi, 'listVersionHistory').and
.callFake(() => Promise.resolve({ list: { entries: [ versionEntry ] }})); .callFake(() => Promise.resolve(new VersionPaging({ list: { entries: [ versionEntry ] }})));
}); });
it('should load the versions for a given node', () => { it('should load the versions for a given node', () => {
+1 -1
View File
@@ -58,7 +58,7 @@ export const aboutAPSMockDetails = {
minorVersion: '10' minorVersion: '10'
}; };
export const mockModules = { export const mockModules: any = {
edition: 'Enterprise', edition: 'Enterprise',
version: { version: {
major: '6', major: '6',
@@ -62,6 +62,7 @@ describe('CardViewTextItemComponent', () => {
editable: false editable: false
}); });
component.ngOnChanges({ property: new SimpleChange(null, null, true) }); component.ngOnChanges({ property: new SimpleChange(null, null, true) });
fixture.detectChanges();
}); });
it('should render the label and value', async () => { it('should render the label and value', async () => {
@@ -256,6 +257,7 @@ describe('CardViewTextItemComponent', () => {
editable: false editable: false
}); });
component.ngOnChanges({ property: new SimpleChange(null, null, true) }); component.ngOnChanges({ property: new SimpleChange(null, null, true) });
fixture.detectChanges();
}); });
it('should render the default as value if the value is empty, clickable is false and displayEmpty is true', (done) => { it('should render the default as value if the value is empty, clickable is false and displayEmpty is true', (done) => {
@@ -468,6 +470,7 @@ describe('CardViewTextItemComponent', () => {
editable: true editable: true
}); });
component.ngOnChanges({ property: new SimpleChange(null, null, true) }); component.ngOnChanges({ property: new SimpleChange(null, null, true) });
fixture.detectChanges();
}); });
it('should call the isValid method with the edited value', fakeAsync((done) => { it('should call the isValid method with the edited value', fakeAsync((done) => {
@@ -563,7 +566,7 @@ describe('CardViewTextItemComponent', () => {
}); });
})); }));
it('should reset erros when exiting editable mode', fakeAsync((done) => { it('should reset erros when exiting editable mode', fakeAsync(() => {
let errorMessage: string; let errorMessage: string;
const expectedErrorMessages = [{ message: 'Something went wrong' } as CardViewItemValidator]; const expectedErrorMessages = [{ message: 'Something went wrong' } as CardViewItemValidator];
component.property.isValid = () => false; component.property.isValid = () => false;
@@ -584,7 +587,6 @@ describe('CardViewTextItemComponent', () => {
errorMessage = fixture.debugElement.nativeElement.querySelector('.adf-textitem-editable-error'); errorMessage = fixture.debugElement.nativeElement.querySelector('.adf-textitem-editable-error');
expect(errorMessage).toBe(null); expect(errorMessage).toBe(null);
expect(component.errors).toEqual([]); expect(component.errors).toEqual([]);
done();
}); });
}); });
})); }));
@@ -620,7 +622,7 @@ describe('CardViewTextItemComponent', () => {
inputField.nativeElement.click(); inputField.nativeElement.click();
})); }));
it('should trigger an update event on the CardViewUpdateService [integration]', fakeAsync((done) => { it('should trigger an update event on the CardViewUpdateService [integration]', (done) => {
component.property.isValid = () => true; component.property.isValid = () => true;
const cardViewUpdateService = TestBed.inject(CardViewUpdateService); const cardViewUpdateService = TestBed.inject(CardViewUpdateService);
const expectedText = 'changed text'; const expectedText = 'changed text';
@@ -639,7 +641,7 @@ describe('CardViewTextItemComponent', () => {
updateTextField(component.property.key, expectedText); updateTextField(component.property.key, expectedText);
}); });
})); });
it('should update the value using the updateItem$ subject', (async () => { it('should update the value using the updateItem$ subject', (async () => {
component.property.isValid = () => true; component.property.isValid = () => true;
@@ -664,7 +666,7 @@ describe('CardViewTextItemComponent', () => {
})); }));
it('should update multiline input the value on input updated', fakeAsync((done) => { it('should update multiline input the value on input updated', (done) => {
component.property.isValid = () => true; component.property.isValid = () => true;
component.property.multiline = true; component.property.multiline = true;
const expectedText = 'changed text'; const expectedText = 'changed text';
@@ -693,7 +695,7 @@ describe('CardViewTextItemComponent', () => {
expect(component.property.value).toBe(expectedText); expect(component.property.value).toBe(expectedText);
}); });
}); });
})); });
}); });
describe('number', () => { describe('number', () => {
@@ -711,6 +713,7 @@ describe('CardViewTextItemComponent', () => {
component.editable = true; component.editable = true;
component.property.validators.push(new CardViewItemIntValidator()); component.property.validators.push(new CardViewItemIntValidator());
component.ngOnChanges({ property: new SimpleChange(null, null, true) }); component.ngOnChanges({ property: new SimpleChange(null, null, true) });
fixture.detectChanges();
}); });
it('should show validation error when string passed', fakeAsync((done) => { it('should show validation error when string passed', fakeAsync((done) => {
@@ -793,7 +796,7 @@ describe('CardViewTextItemComponent', () => {
}); });
})); }));
it('should update input the value on input updated', fakeAsync((done) => { it('should update input the value on input updated', (done) => {
const expectedNumber = 2020; const expectedNumber = 2020;
spyOn(component, 'update').and.callThrough(); spyOn(component, 'update').and.callThrough();
fixture.detectChanges(); fixture.detectChanges();
@@ -817,7 +820,7 @@ describe('CardViewTextItemComponent', () => {
expect(component.property.value).toBe(expectedNumber.toString()); expect(component.property.value).toBe(expectedNumber.toString());
}); });
}); });
})); });
}); });
describe('float', () => { describe('float', () => {
@@ -830,12 +833,13 @@ describe('CardViewTextItemComponent', () => {
label: 'Text label', label: 'Text label',
value: floatValue, value: floatValue,
key: 'textkey', key: 'textkey',
default: 'FAKE-DEFAULT-KEY', default: 1,
editable: true editable: true
}); });
component.editable = true; component.editable = true;
component.property.validators.push(new CardViewItemFloatValidator()); component.property.validators.push(new CardViewItemFloatValidator());
component.ngOnChanges({ property: new SimpleChange(null, null, true) }); component.ngOnChanges({ property: new SimpleChange(null, null, true) });
fixture.detectChanges();
}); });
it('should show validation error when string passed', fakeAsync((done) => { it('should show validation error when string passed', fakeAsync((done) => {
@@ -854,7 +858,7 @@ describe('CardViewTextItemComponent', () => {
}); });
})); }));
it('should show validation error for empty string', fakeAsync((done) => { it('should show validation error for empty string (float)', fakeAsync((done) => {
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
@@ -870,7 +874,7 @@ describe('CardViewTextItemComponent', () => {
}); });
})); }));
it('should update input the value on input updated', fakeAsync((done) => { it('should update input the value on input updated', (done) => {
const expectedNumber = 88.44; const expectedNumber = 88.44;
spyOn(component, 'update').and.callThrough(); spyOn(component, 'update').and.callThrough();
fixture.detectChanges(); fixture.detectChanges();
@@ -894,7 +898,7 @@ describe('CardViewTextItemComponent', () => {
expect(component.property.value).toBe(expectedNumber.toString()); expect(component.property.value).toBe(expectedNumber.toString());
}); });
}); });
})); });
}); });
function updateTextField(key, value) { function updateTextField(key, value) {
+11 -10
View File
@@ -24,6 +24,7 @@ import { CommentContentService } from '../services/comment-content.service';
import { setupTestBed } from '../testing/setup-test-bed'; import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { CommentModel } from '../models/comment.model';
describe('CommentsComponent', () => { describe('CommentsComponent', () => {
@@ -51,28 +52,28 @@ describe('CommentsComponent', () => {
commentProcessService = fixture.debugElement.injector.get(CommentProcessService); commentProcessService = fixture.debugElement.injector.get(CommentProcessService);
commentContentService = fixture.debugElement.injector.get(CommentContentService); commentContentService = fixture.debugElement.injector.get(CommentContentService);
addContentCommentSpy = spyOn(commentContentService, 'addNodeComment').and.returnValue(of({ addContentCommentSpy = spyOn(commentContentService, 'addNodeComment').and.returnValue(of(new CommentModel({
id: 123, id: 123,
message: 'Test Comment', message: 'Test Comment',
createdBy: {id: '999'} createdBy: {id: '999'}
})); })));
getContentCommentsSpy = spyOn(commentContentService, 'getNodeComments').and.returnValue(of([ getContentCommentsSpy = spyOn(commentContentService, 'getNodeComments').and.returnValue(of([
{message: 'Test1', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}, new CommentModel({message: 'Test1', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}),
{message: 'Test2', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}, new CommentModel({message: 'Test2', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}),
{message: 'Test3', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}} new CommentModel({message: 'Test3', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}})
])); ]));
getProcessCommentsSpy = spyOn(commentProcessService, 'getTaskComments').and.returnValue(of([ getProcessCommentsSpy = spyOn(commentProcessService, 'getTaskComments').and.returnValue(of([
{message: 'Test1', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}, new CommentModel({message: 'Test1', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}),
{message: 'Test2', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}, new CommentModel({message: 'Test2', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}}),
{message: 'Test3', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}} new CommentModel({message: 'Test3', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'}})
])); ]));
addProcessCommentSpy = spyOn(commentProcessService, 'addTaskComment').and.returnValue(of({ addProcessCommentSpy = spyOn(commentProcessService, 'addTaskComment').and.returnValue(of(new CommentModel({
id: 123, id: 123,
message: 'Test Comment', message: 'Test Comment',
createdBy: {id: '999'} createdBy: {id: '999'}
})); })));
}); });
afterEach(() => { afterEach(() => {
@@ -41,7 +41,7 @@ describe('NodeDownloadDirective', () => {
let apiService: AlfrescoApiService; let apiService: AlfrescoApiService;
let contentService; let contentService;
let dialogSpy; let dialogSpy;
const mockOauth2Auth = { const mockOauth2Auth: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve() callCustomApi: () => Promise.resolve()
}, },
@@ -159,7 +159,7 @@ describe('NodeDownloadDirective', () => {
}); });
it('should create link element to download file node', () => { it('should create link element to download file node', () => {
const dummyLinkElement = { const dummyLinkElement: any = {
download: null, download: null,
href: null, href: null,
click: () => null, click: () => null,
@@ -72,7 +72,7 @@ describe('NodeFavoriteDirective', () => {
}); });
it('should reset favorites if selection is empty', fakeAsync(() => { it('should reset favorites if selection is empty', fakeAsync(() => {
spyOn(alfrescoApiService.getInstance().core.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve()); spyOn(alfrescoApiService.getInstance().core.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve(null));
const selection = [ const selection = [
{ entry: { id: '1', name: 'name1' } } { entry: { id: '1', name: 'name1' } }
@@ -97,7 +97,7 @@ describe('NodeFavoriteDirective', () => {
beforeEach(() => { beforeEach(() => {
favoritesApiSpy = spyOn(alfrescoApiService.getInstance().core.favoritesApi, 'getFavorite') favoritesApiSpy = spyOn(alfrescoApiService.getInstance().core.favoritesApi, 'getFavorite')
.and.returnValue(Promise.resolve()); .and.returnValue(Promise.resolve(null));
}); });
it('should check each selected node if it is a favorite', fakeAsync(() => { it('should check each selected node if it is a favorite', fakeAsync(() => {
@@ -341,7 +341,7 @@ describe('NodeFavoriteDirective', () => {
})); }));
it('should process node as favorite', fakeAsync(() => { it('should process node as favorite', fakeAsync(() => {
spyOn(alfrescoApiService.getInstance().core.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve()); spyOn(alfrescoApiService.getInstance().core.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve(null));
const selection = [ const selection = [
{ entry: { id: '1', name: 'name1' } } { entry: { id: '1', name: 'name1' } }
+2 -2
View File
@@ -110,7 +110,7 @@ describe('UploadDirective', () => {
it('should raise upload-files event on files drop', (done) => { it('should raise upload-files event on files drop', (done) => {
directive.enabled = true; directive.enabled = true;
const event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']); const event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']);
spyOn(directive, 'getDataTransfer').and.returnValue({}); spyOn(directive, 'getDataTransfer').and.returnValue({} as any);
spyOn(directive, 'getFilesDropped').and.returnValue(Promise.resolve([ spyOn(directive, 'getFilesDropped').and.returnValue(Promise.resolve([
<FileInfo> {}, <FileInfo> {},
<FileInfo> {} <FileInfo> {}
@@ -127,7 +127,7 @@ describe('UploadDirective', () => {
<FileInfo> {} <FileInfo> {}
]; ];
const event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']); const event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']);
spyOn(directive, 'getDataTransfer').and.returnValue({}); spyOn(directive, 'getDataTransfer').and.returnValue({} as any);
spyOn(directive, 'getFilesDropped').and.returnValue(Promise.resolve(files)); spyOn(directive, 'getFilesDropped').and.returnValue(Promise.resolve(files));
spyOn(nativeElement, 'dispatchEvent').and.callFake((e) => { spyOn(nativeElement, 'dispatchEvent').and.callFake((e) => {
@@ -22,6 +22,7 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { setupTestBed } from '../testing/setup-test-bed'; import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { VersionCompatibilityService } from '../services/version-compatibility.service'; import { VersionCompatibilityService } from '../services/version-compatibility.service';
import { VersionModel } from '../models/product-version.model';
@Component({ @Component({
template: ` template: `
@@ -51,12 +52,12 @@ describe('VersionCompatibilityDirective', () => {
let fixture: ComponentFixture<TestComponent>; let fixture: ComponentFixture<TestComponent>;
let versionCompatibilityService: VersionCompatibilityService; let versionCompatibilityService: VersionCompatibilityService;
const acsResponceMock = { const acsResponceMock = new VersionModel({
display: '7.0.1', display: '7.0.1',
major: '7', major: '7',
minor: '0', minor: '0',
patch: '1' patch: '1'
}; });
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -129,7 +129,7 @@ describe('RadioButtonsWidgetComponent', () => {
}); });
it('should update the field value when an option is selected', () => { it('should update the field value when an option is selected', () => {
spyOn(widget, 'onFieldChanged').and.returnValue(of({})); spyOn(widget, 'onFieldChanged').and.stub();
widget.onOptionClick('fake-opt'); widget.onOptionClick('fake-opt');
expect(widget.field.value).toEqual('fake-opt'); expect(widget.field.value).toEqual('fake-opt');
@@ -28,8 +28,9 @@ import { UploadWidgetComponent } from './upload.widget';
import { setupTestBed } from '../../../../testing/setup-test-bed'; import { setupTestBed } from '../../../../testing/setup-test-bed';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { RelatedContentRepresentation } from '@alfresco/js-api';
const fakePngAnswer = { const fakePngAnswer = new RelatedContentRepresentation({
'id': 1155, 'id': 1155,
'name': 'a_png_file.png', 'name': 'a_png_file.png',
'created': '2017-07-25T17:17:37.099Z', 'created': '2017-07-25T17:17:37.099Z',
@@ -41,7 +42,7 @@ const fakePngAnswer = {
'simpleType': 'image', 'simpleType': 'image',
'previewStatus': 'queued', 'previewStatus': 'queued',
'thumbnailStatus': 'queued' 'thumbnailStatus': 'queued'
}; });
const fakeJpgAnswer = { const fakeJpgAnswer = {
'id': 1156, 'id': 1156,
@@ -211,7 +212,7 @@ describe('UploadWidgetComponent', () => {
return of(fakeJpgAnswer); return of(fakeJpgAnswer);
} }
return of(); return of(null);
}); });
uploadWidgetComponent.field.params.multiple = true; uploadWidgetComponent.field.params.multiple = true;
@@ -241,7 +242,7 @@ describe('UploadWidgetComponent', () => {
return of(fakeJpgAnswer); return of(fakeJpgAnswer);
} }
return of(); return of(null);
}); });
uploadWidgetComponent.field.params.multiple = true; uploadWidgetComponent.field.params.multiple = true;
+1 -1
View File
@@ -233,7 +233,7 @@ describe('Form service', () => {
activiti: { activiti: {
processApi: processApiSpy processApi: processApiSpy
} }
}); } as any);
processApiSpy.getProcessDefinitionStartForm.and.returnValue(Promise.resolve({ id: '1' })); processApiSpy.getProcessDefinitionStartForm.and.returnValue(Promise.resolve({ id: '1' }));
service.getStartFormDefinition('myprocess:1').subscribe(() => { service.getStartFormDefinition('myprocess:1').subscribe(() => {
@@ -228,9 +228,9 @@ describe('SidenavLayoutComponent', () => {
describe('Template transclusion', () => { describe('Template transclusion', () => {
let fixture: ComponentFixture<any>, let fixture: ComponentFixture<any>;
mediaMatcher: MediaMatcher; let mediaMatcher: MediaMatcher;
const mediaQueryList = { const mediaQueryList: any = {
matches: false, matches: false,
addListener: () => {}, addListener: () => {},
removeListener: () => {} removeListener: () => {}
@@ -25,7 +25,7 @@ import { AuthenticationService } from '../../services/authentication.service';
import { LoginErrorEvent } from '../models/login-error.event'; import { LoginErrorEvent } from '../models/login-error.event';
import { LoginSuccessEvent } from '../models/login-success.event'; import { LoginSuccessEvent } from '../models/login-success.event';
import { LoginComponent } from './login.component'; import { LoginComponent } from './login.component';
import { of, throwError, Observable } from 'rxjs'; import { of, throwError } from 'rxjs';
import { OauthConfigModel } from '../../models/oauth-config.model'; import { OauthConfigModel } from '../../models/oauth-config.model';
import { AlfrescoApiService } from '../../services/alfresco-api.service'; import { AlfrescoApiService } from '../../services/alfresco-api.service';
@@ -177,12 +177,7 @@ describe('LoginComponent', () => {
it('should update user preferences upon login', async(() => { it('should update user preferences upon login', async(() => {
spyOn(userPreferences, 'setStoragePrefix').and.callThrough(); spyOn(userPreferences, 'setStoragePrefix').and.callThrough();
spyOn(alfrescoApiService.getInstance(), 'login').and.callFake(() => { spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.resolve());
return new Observable((observer) => {
observer.next();
observer.complete();
});
});
component.success.subscribe(() => { component.success.subscribe(() => {
expect(userPreferences.setStoragePrefix).toHaveBeenCalledWith('fake-username'); expect(userPreferences.setStoragePrefix).toHaveBeenCalledWith('fake-username');
@@ -202,10 +197,7 @@ describe('LoginComponent', () => {
}); });
it('should be changed to the "checking key" after a login attempt', () => { it('should be changed to the "checking key" after a login attempt', () => {
spyOn(authService, 'login').and.returnValue({ spyOn(authService, 'login').and.stub();
subscribe: () => {
}
});
loginWithCredentials('fake-username', 'fake-password'); loginWithCredentials('fake-username', 'fake-password');
@@ -247,10 +239,7 @@ describe('LoginComponent', () => {
}); });
it('should be taken into consideration during login attempt', () => { it('should be taken into consideration during login attempt', () => {
spyOn(authService, 'login').and.returnValue({ spyOn(authService, 'login').and.stub();
subscribe: () => {
}
});
component.rememberMe = false; component.rememberMe = false;
loginWithCredentials('fake-username', 'fake-password'); loginWithCredentials('fake-username', 'fake-password');
@@ -409,12 +398,7 @@ describe('LoginComponent', () => {
}); });
it('should return error with a wrong username', (done) => { it('should return error with a wrong username', (done) => {
spyOn(alfrescoApiService.getInstance(), 'login').and.callFake(() => { spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject());
return new Observable((observer) => {
observer.next();
observer.error();
});
});
component.error.subscribe(() => { component.error.subscribe(() => {
fixture.detectChanges(); fixture.detectChanges();
@@ -429,12 +413,7 @@ describe('LoginComponent', () => {
}); });
it('should return error with a wrong password', (done) => { it('should return error with a wrong password', (done) => {
spyOn(alfrescoApiService.getInstance(), 'login').and.callFake(() => { spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject());
return new Observable((observer) => {
observer.next();
observer.error();
});
});
component.error.subscribe(() => { component.error.subscribe(() => {
fixture.detectChanges(); fixture.detectChanges();
@@ -450,12 +429,7 @@ describe('LoginComponent', () => {
}); });
it('should return error with a wrong username and password', (done) => { it('should return error with a wrong username and password', (done) => {
spyOn(alfrescoApiService.getInstance(), 'login').and.callFake(() => { spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject());
return new Observable((observer) => {
observer.next();
observer.error();
});
});
component.error.subscribe(() => { component.error.subscribe(() => {
fixture.detectChanges(); fixture.detectChanges();
@@ -623,12 +597,7 @@ describe('LoginComponent', () => {
}); });
it('should emit only the username and not the password as part of the executeSubmit', async(() => { it('should emit only the username and not the password as part of the executeSubmit', async(() => {
spyOn(alfrescoApiService.getInstance(), 'login').and.callFake(() => { spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.resolve());
return new Observable((observer) => {
observer.next();
observer.complete();
});
});
component.executeSubmit.subscribe((res) => { component.executeSubmit.subscribe((res) => {
fixture.detectChanges(); fixture.detectChanges();
@@ -668,7 +637,7 @@ describe('LoginComponent', () => {
spyOn(authService, 'isOauth').and.returnValue(true); spyOn(authService, 'isOauth').and.returnValue(true);
appConfigService.config.oauth2 = <OauthConfigModel> { implicitFlow: true, silentLogin: true }; appConfigService.config.oauth2 = <OauthConfigModel> { implicitFlow: true, silentLogin: true };
spyOn(component, 'redirectToImplicitLogin').and.returnValue(Promise.resolve({})); spyOn(component, 'redirectToImplicitLogin').and.stub();
component.ngOnInit(); component.ngOnInit();
fixture.detectChanges(); fixture.detectChanges();
+4 -2
View File
@@ -15,6 +15,8 @@
* limitations under the License. * limitations under the License.
*/ */
import { BpmUserModel } from '../models';
export let fakeBpmUserNoImage = { export let fakeBpmUserNoImage = {
apps: [], apps: [],
capabilities: 'fake-capability', capabilities: 'fake-capability',
@@ -37,7 +39,7 @@ export let fakeBpmUserNoImage = {
type: 'fake-type' type: 'fake-type'
}; };
export let fakeBpmUser = { export let fakeBpmUser = new BpmUserModel({
apps: [], apps: [],
capabilities: null, capabilities: null,
company: 'fake-company', company: 'fake-company',
@@ -57,7 +59,7 @@ export let fakeBpmUser = {
tenantName: 'fake-tenant-name', tenantName: 'fake-tenant-name',
tenantPictureId: 'fake-tenant-picture-id', tenantPictureId: 'fake-tenant-picture-id',
type: 'fake-type' type: 'fake-type'
}; });
export let fakeBpmEditedUser = { export let fakeBpmEditedUser = {
apps: [], apps: [],
+6 -5
View File
@@ -16,7 +16,8 @@
*/ */
import { EcmCompanyModel } from '../models/ecm-company.model'; import { EcmCompanyModel } from '../models/ecm-company.model';
import { PersonEntry, Person } from '@alfresco/js-api'; import { PersonEntry, Person, PersonPaging } from '@alfresco/js-api';
import { EcmUserModel } from '../models';
export const fakeEcmCompany: EcmCompanyModel = { export const fakeEcmCompany: EcmCompanyModel = {
organization: 'company-fake-name', organization: 'company-fake-name',
@@ -29,7 +30,7 @@ export const fakeEcmCompany: EcmCompanyModel = {
email: 'fakeCompany@fake.com' email: 'fakeCompany@fake.com'
}; };
export const fakeEcmUser = { export const fakeEcmUser = new EcmUserModel({
id: 'fake-id', id: 'fake-id',
firstName: 'fake-ecm-first-name', firstName: 'fake-ecm-first-name',
lastName: 'fake-ecm-last-name', lastName: 'fake-ecm-last-name',
@@ -48,7 +49,7 @@ export const fakeEcmUser = {
userStatus: 'active', userStatus: 'active',
enabled: true, enabled: true,
emailNotificationsEnabled: true emailNotificationsEnabled: true
}; });
export const fakeEcmUser2 = { export const fakeEcmUser2 = {
id: 'another-fake-id', id: 'another-fake-id',
@@ -103,7 +104,7 @@ export const fakeEcmEditedUser = {
emailNotificationsEnabled: true emailNotificationsEnabled: true
}; };
export const fakeEcmUserList = { export const fakeEcmUserList = new PersonPaging({
list: { list: {
pagination: { pagination: {
count: 2, count: 2,
@@ -121,7 +122,7 @@ export const fakeEcmUserList = {
} }
] ]
} }
}; });
export const createNewPersonMock = { export const createNewPersonMock = {
id: 'fake-id', id: 'fake-id',
+11 -8
View File
@@ -50,7 +50,7 @@ export const roleMappingMock = [
{ id: 'role-id-1', name: 'role-name-1' }, { id: 'role-id-2', name: 'role-name-2' } { id: 'role-id-1', name: 'role-name-1' }, { id: 'role-id-2', name: 'role-name-2' }
]; ];
export const roleMappingApi = { export const roleMappingApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(roleMappingMock); return Promise.resolve(roleMappingMock);
@@ -58,7 +58,7 @@ export const roleMappingApi = {
} }
}; };
export const noRoleMappingApi = { export const noRoleMappingApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve([]); return Promise.resolve([]);
@@ -66,7 +66,7 @@ export const noRoleMappingApi = {
} }
}; };
export const groupsMockApi = { export const groupsMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(mockIdentityGroups); return Promise.resolve(mockIdentityGroups);
@@ -74,7 +74,7 @@ export const groupsMockApi = {
} }
}; };
export const createGroupMappingApi = { export const createGroupMappingApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -82,7 +82,7 @@ export const createGroupMappingApi = {
} }
}; };
export const updateGroupMappingApi = { export const updateGroupMappingApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -90,7 +90,7 @@ export const updateGroupMappingApi = {
} }
}; };
export const deleteGroupMappingApi = { export const deleteGroupMappingApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -98,7 +98,7 @@ export const deleteGroupMappingApi = {
} }
}; };
export const applicationDetailsMockApi = { export const applicationDetailsMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve([mockApplicationDetails]); return Promise.resolve([mockApplicationDetails]);
@@ -112,4 +112,7 @@ export const mockIdentityRoles = [
new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-ROLE-1'}) new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-ROLE-1'})
]; ];
export const clientRoles = [ 'MOCK-ADMIN-ROLE', 'MOCK-USER-ROLE']; export const clientRoles: IdentityRoleModel[] = [
new IdentityRoleModel({ name: 'MOCK-ADMIN-ROLE' }),
new IdentityRoleModel({ name: 'MOCK-USER-ROLE' })
];
+12 -12
View File
@@ -70,7 +70,7 @@ export const mockGroups = [
<IdentityGroupModel> { id: 'mock-group-id-2', name: 'Mock Group 2', path: '', subGroups: [] } <IdentityGroupModel> { id: 'mock-group-id-2', name: 'Mock Group 2', path: '', subGroups: [] }
]; ];
export const queryUsersMockApi = { export const queryUsersMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(mockIdentityUsers); return Promise.resolve(mockIdentityUsers);
@@ -78,7 +78,7 @@ export const queryUsersMockApi = {
} }
}; };
export const createUserMockApi = { export const createUserMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -86,7 +86,7 @@ export const createUserMockApi = {
} }
}; };
export const updateUserMockApi = { export const updateUserMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -94,7 +94,7 @@ export const updateUserMockApi = {
} }
}; };
export const deleteUserMockApi = { export const deleteUserMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -102,7 +102,7 @@ export const deleteUserMockApi = {
} }
}; };
export const getInvolvedGroupsMockApi = { export const getInvolvedGroupsMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(mockGroups); return Promise.resolve(mockGroups);
@@ -110,7 +110,7 @@ export const getInvolvedGroupsMockApi = {
} }
}; };
export const joinGroupMockApi = { export const joinGroupMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -118,7 +118,7 @@ export const joinGroupMockApi = {
} }
}; };
export const leaveGroupMockApi = { export const leaveGroupMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -126,7 +126,7 @@ export const leaveGroupMockApi = {
} }
}; };
export const getAvailableRolesMockApi = { export const getAvailableRolesMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(mockAvailableRoles); return Promise.resolve(mockAvailableRoles);
@@ -134,7 +134,7 @@ export const getAvailableRolesMockApi = {
} }
}; };
export const getAssignedRolesMockApi = { export const getAssignedRolesMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(mockAssignedRoles); return Promise.resolve(mockAssignedRoles);
@@ -142,7 +142,7 @@ export const getAssignedRolesMockApi = {
} }
}; };
export const getEffectiveRolesMockApi = { export const getEffectiveRolesMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(mockEffectiveRoles); return Promise.resolve(mockEffectiveRoles);
@@ -150,7 +150,7 @@ export const getEffectiveRolesMockApi = {
} }
}; };
export const assignRolesMockApi = { export const assignRolesMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -158,7 +158,7 @@ export const assignRolesMockApi = {
} }
}; };
export const removeRolesMockApi = { export const removeRolesMockApi: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
+1 -1
View File
@@ -54,7 +54,7 @@ export let mockError = {
} }
}; };
export let searchMockApi = { export let searchMockApi: any = {
core: { core: {
queriesApi: { queriesApi: {
findNodes: () => Promise.resolve(fakeSearch) findNodes: () => Promise.resolve(fakeSearch)
+12 -12
View File
@@ -22,11 +22,11 @@ import { AlfrescoApiService } from './alfresco-api.service';
import { AuthenticationService } from './authentication.service'; import { AuthenticationService } from './authentication.service';
import { setupTestBed } from '../testing/setup-test-bed'; import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { SystemPropertiesRepresentation } from '@alfresco/js-api'; import { DiscoveryEntry, SystemPropertiesRepresentation } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { of, throwError } from 'rxjs'; import { of } from 'rxjs';
const fakeEcmDiscoveryResponse: any = { const fakeEcmDiscoveryResponse = new DiscoveryEntry({
entry: { entry: {
repository: { repository: {
edition: 'FAKE', edition: 'FAKE',
@@ -79,7 +79,7 @@ const fakeEcmDiscoveryResponse: any = {
] ]
} }
} }
}; });
const fakeBPMDiscoveryResponse: any = { const fakeBPMDiscoveryResponse: any = {
revisionVersion: '2', revisionVersion: '2',
@@ -89,7 +89,7 @@ const fakeBPMDiscoveryResponse: any = {
minorVersion: '6' minorVersion: '6'
}; };
const fakeBPMDiscoverySystemPropertyResponse: any = { const fakeBPMDiscoverySystemPropertyResponse = new SystemPropertiesRepresentation({
allowInvolveByEmail: true, allowInvolveByEmail: true,
disableJavaScriptEventsInFormEditor: false, disableJavaScriptEventsInFormEditor: false,
logoutDisabled: false, logoutDisabled: false,
@@ -99,7 +99,7 @@ const fakeBPMDiscoverySystemPropertyResponse: any = {
clientId: 'fakeClient', clientId: 'fakeClient',
useBrowserLogout: true useBrowserLogout: true
} }
}; });
describe('Discovery Api Service', () => { describe('Discovery Api Service', () => {
let service: DiscoveryApiService; let service: DiscoveryApiService;
@@ -119,7 +119,7 @@ describe('Discovery Api Service', () => {
describe('For ECM', () => { describe('For ECM', () => {
it('Should retrieve the info about the product for ECM', done => { it('Should retrieve the info about the product for ECM', done => {
spyOn(apiService.getInstance().discovery.discoveryApi, 'getRepositoryInformation') spyOn(apiService.getInstance().discovery.discoveryApi, 'getRepositoryInformation')
.and.returnValue(of(fakeEcmDiscoveryResponse)); .and.returnValue(Promise.resolve(fakeEcmDiscoveryResponse));
service.getEcmProductInfo() service.getEcmProductInfo()
.subscribe((data: EcmProductVersionModel) => { .subscribe((data: EcmProductVersionModel) => {
@@ -137,7 +137,7 @@ describe('Discovery Api Service', () => {
it('getEcmProductInfo catch errors call', done => { it('getEcmProductInfo catch errors call', done => {
spyOn(apiService.getInstance().discovery.discoveryApi, 'getRepositoryInformation') spyOn(apiService.getInstance().discovery.discoveryApi, 'getRepositoryInformation')
.and.returnValue(throwError({ status: 403 })); .and.returnValue(Promise.reject({ status: 403 }));
service.getEcmProductInfo().subscribe( service.getEcmProductInfo().subscribe(
() => {}, () => {},
@@ -151,7 +151,7 @@ describe('Discovery Api Service', () => {
describe('For BPM', () => { describe('For BPM', () => {
it('Should retrieve the info about the product for BPM', done => { it('Should retrieve the info about the product for BPM', done => {
spyOn(apiService.getInstance().activiti.aboutApi, 'getAppVersion') spyOn(apiService.getInstance().activiti.aboutApi, 'getAppVersion')
.and.returnValue(of(fakeBPMDiscoveryResponse)); .and.returnValue(Promise.resolve(fakeBPMDiscoveryResponse));
service.getBpmProductInfo().subscribe((data: BpmProductVersionModel) => { service.getBpmProductInfo().subscribe((data: BpmProductVersionModel) => {
expect(data).not.toBeNull(); expect(data).not.toBeNull();
@@ -164,7 +164,7 @@ describe('Discovery Api Service', () => {
it('getBpmProductInfo catch errors call', done => { it('getBpmProductInfo catch errors call', done => {
spyOn(apiService.getInstance().activiti.aboutApi, 'getAppVersion') spyOn(apiService.getInstance().activiti.aboutApi, 'getAppVersion')
.and.returnValue(throwError({ status: 403 })); .and.returnValue(Promise.reject({ status: 403 }));
service.getBpmProductInfo().subscribe( service.getBpmProductInfo().subscribe(
() => {}, () => {},
@@ -176,7 +176,7 @@ describe('Discovery Api Service', () => {
it('Should retrieve the system properties for BPM', done => { it('Should retrieve the system properties for BPM', done => {
spyOn(apiService.getInstance().activiti.systemPropertiesApi, 'getProperties') spyOn(apiService.getInstance().activiti.systemPropertiesApi, 'getProperties')
.and.returnValue(of(fakeBPMDiscoverySystemPropertyResponse)); .and.returnValue(Promise.resolve(fakeBPMDiscoverySystemPropertyResponse));
service.getBPMSystemProperties().subscribe((data: SystemPropertiesRepresentation) => { service.getBPMSystemProperties().subscribe((data: SystemPropertiesRepresentation) => {
expect(data).not.toBeNull(); expect(data).not.toBeNull();
@@ -196,7 +196,7 @@ describe('Discovery Api Service', () => {
apiService.getInstance().activiti.systemPropertiesApi, apiService.getInstance().activiti.systemPropertiesApi,
'getProperties' 'getProperties'
).and.returnValue( ).and.returnValue(
throwError({ Promise.reject({
error: { error: {
response: { response: {
statusCode: 404, statusCode: 404,
@@ -45,7 +45,7 @@ describe('LoginDialogService', () => {
componentInstance: { componentInstance: {
error: new Subject<any>() error: new Subject<any>()
} }
}); } as any);
}); });
it('should be able to open the dialog when node has permission', () => { it('should be able to open the dialog when node has permission', () => {
+1 -1
View File
@@ -38,7 +38,7 @@ describe('NodesApiService', () => {
} }
} }
}; };
const mockSpy = { const mockSpy: any = {
core: { core: {
nodesApi: { nodesApi: {
getNode: jasmine.createSpy('getNode'), getNode: jasmine.createSpy('getNode'),
@@ -24,7 +24,7 @@ import { setupTestBed } from '../testing/setup-test-bed';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { LogService } from './log.service'; import { LogService } from './log.service';
import { of } from 'rxjs'; import { PersonEntry } from '@alfresco/js-api';
describe('PeopleContentService', () => { describe('PeopleContentService', () => {
@@ -47,7 +47,7 @@ describe('PeopleContentService', () => {
}); });
it('should be able to fetch person details based on id', (done) => { it('should be able to fetch person details based on id', (done) => {
spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve({ entry: fakeEcmUser })); spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
service.getPerson('fake-id').subscribe((person) => { service.getPerson('fake-id').subscribe((person) => {
expect(person.entry.id).toEqual('fake-id'); expect(person.entry.id).toEqual('fake-id');
expect(person.entry.email).toEqual('fakeEcm@ecmUser.com'); expect(person.entry.email).toEqual('fakeEcm@ecmUser.com');
@@ -56,7 +56,7 @@ describe('PeopleContentService', () => {
}); });
it('calls getPerson api method by an id', (done) => { it('calls getPerson api method by an id', (done) => {
const getPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve({})); const getPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(null));
service.getPerson('fake-id').subscribe(() => { service.getPerson('fake-id').subscribe(() => {
expect(getPersonSpy).toHaveBeenCalledWith('fake-id'); expect(getPersonSpy).toHaveBeenCalledWith('fake-id');
done(); done();
@@ -64,7 +64,7 @@ describe('PeopleContentService', () => {
}); });
it('calls getPerson api method with "-me-"', (done) => { it('calls getPerson api method with "-me-"', (done) => {
const getPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve({})); const getPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(null));
service.getPerson('-me-').subscribe(() => { service.getPerson('-me-').subscribe(() => {
expect(getPersonSpy).toHaveBeenCalledWith('-me-'); expect(getPersonSpy).toHaveBeenCalledWith('-me-');
done(); done();
@@ -95,7 +95,7 @@ describe('PeopleContentService', () => {
}); });
it('should be able to create new person', (done) => { it('should be able to create new person', (done) => {
spyOn(service.peopleApi, 'createPerson').and.returnValue(Promise.resolve({ entry: fakeEcmUser })); spyOn(service.peopleApi, 'createPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
service.createPerson(createNewPersonMock).subscribe((person) => { service.createPerson(createNewPersonMock).subscribe((person) => {
expect(person.id).toEqual('fake-id'); expect(person.id).toEqual('fake-id');
expect(person.email).toEqual('fakeEcm@ecmUser.com'); expect(person.email).toEqual('fakeEcm@ecmUser.com');
@@ -104,7 +104,7 @@ describe('PeopleContentService', () => {
}); });
it('should be able to call createPerson api with new person details', (done) => { it('should be able to call createPerson api with new person details', (done) => {
const createPersonSpy = spyOn(service.peopleApi, 'createPerson').and.returnValue(Promise.resolve({ entry: fakeEcmUser })); const createPersonSpy = spyOn(service.peopleApi, 'createPerson').and.returnValue(Promise.resolve(new PersonEntry({ entry: fakeEcmUser })));
service.createPerson(createNewPersonMock).subscribe((person) => { service.createPerson(createNewPersonMock).subscribe((person) => {
expect(person.id).toEqual('fake-id'); expect(person.id).toEqual('fake-id');
expect(person.email).toEqual('fakeEcm@ecmUser.com'); expect(person.email).toEqual('fakeEcm@ecmUser.com');
@@ -127,7 +127,7 @@ describe('PeopleContentService', () => {
}); });
it('Should make the api call to check if the user is a content admin only once', async () => { it('Should make the api call to check if the user is a content admin only once', async () => {
const getCurrentPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(of(getFakeUserWithContentAdminCapability())); const getCurrentPersonSpy = spyOn(service.peopleApi, 'getPerson').and.returnValue(Promise.resolve(getFakeUserWithContentAdminCapability()));
expect(await service.isContentAdmin()).toBe(true); expect(await service.isContentAdmin()).toBe(true);
expect(getCurrentPersonSpy.calls.count()).toEqual(1); expect(getCurrentPersonSpy.calls.count()).toEqual(1);
@@ -105,7 +105,7 @@ describe('User info component', () => {
contentService = TestBed.inject(ContentService); contentService = TestBed.inject(ContentService);
identityUserService = TestBed.inject(IdentityUserService); identityUserService = TestBed.inject(IdentityUserService);
spyOn(window, 'requestAnimationFrame').and.returnValue(true); spyOn(window, 'requestAnimationFrame').and.returnValue(1);
spyOn(bpmUserService, 'getCurrentUserProfileImage').and.returnValue('app/rest/admin/profile-picture'); spyOn(bpmUserService, 'getCurrentUserProfileImage').and.returnValue('app/rest/admin/profile-picture');
spyOn(contentService, 'getContentUrl').and.returnValue('alfresco-logo.svg'); spyOn(contentService, 'getContentUrl').and.returnValue('alfresco-logo.svg');
})); }));
@@ -175,12 +175,12 @@ describe('User info component', () => {
}); });
it('should show the username when showName attribute is true', async () => { it('should show the username when showName attribute is true', async () => {
await fixture.whenStable().then(() => { await fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
expect(component.showName).toBeTruthy(); expect(component.showName).toBeTruthy();
expect(element.querySelector('#adf-userinfo-ecm-name-display')).not.toBeNull(); expect(element.querySelector('#adf-userinfo-ecm-name-display')).not.toBeNull();
}); });
});
it('should hide the username when showName attribute is false', async () => { it('should hide the username when showName attribute is false', async () => {
component.showName = false; component.showName = false;
@@ -206,7 +206,6 @@ describe('User info component', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(element.querySelector('#userinfo_container').classList).not.toContain('adf-userinfo-name-right'); expect(element.querySelector('#userinfo_container').classList).not.toContain('adf-userinfo-name-right');
}); });
});
describe('and has image', () => { describe('and has image', () => {
@@ -22,7 +22,7 @@ import { setupTestBed } from '../../testing/setup-test-bed';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService } from '../../services'; import { AlfrescoApiService } from '../../services';
import { NodeEntry } from '@alfresco/js-api'; import { NodeEntry, RenditionPaging } from '@alfresco/js-api';
describe('Test Media player component ', () => { describe('Test Media player component ', () => {
@@ -52,13 +52,13 @@ describe('Test Media player component ', () => {
it('should generate tracks for media file when webvtt rendition exists', fakeAsync(() => { it('should generate tracks for media file when webvtt rendition exists', fakeAsync(() => {
const fakeRenditionUrl = 'http://fake.rendition.url'; const fakeRenditionUrl = 'http://fake.rendition.url';
spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValues( spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValue(
Promise.resolve(new NodeEntry({ entry: { name: 'file1', content: {} } })) Promise.resolve(new NodeEntry({ entry: { name: 'file1', content: {} } }))
); );
spyOn(alfrescoApiService.renditionsApi, 'getRenditions').and.returnValues( spyOn(alfrescoApiService.renditionsApi, 'getRenditions').and.returnValue(
{ list: { entries: [{ entry: { id: 'webvtt', status: 'CREATED' } }] } } Promise.resolve(new RenditionPaging({ list: { entries: [{ entry: { id: 'webvtt', status: 'CREATED' } }] } }))
); );
spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValues('http://iam-fake.url'); spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValue('http://iam-fake.url');
spyOn(alfrescoApiService.contentApi, 'getRenditionUrl').and.returnValue(fakeRenditionUrl); spyOn(alfrescoApiService.contentApi, 'getRenditionUrl').and.returnValue(fakeRenditionUrl);
component.ngOnChanges(change); component.ngOnChanges(change);
@@ -68,15 +68,15 @@ describe('Test Media player component ', () => {
})); }));
it('should not generate tracks for media file when webvtt rendition is not created', fakeAsync(() => { it('should not generate tracks for media file when webvtt rendition is not created', fakeAsync(() => {
spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValues( spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValue(
Promise.resolve(new NodeEntry({ entry: { name: 'file1', content: {} } })) Promise.resolve(new NodeEntry({ entry: { name: 'file1', content: {} } }))
); );
spyOn(alfrescoApiService.renditionsApi, 'getRenditions').and.returnValues( spyOn(alfrescoApiService.renditionsApi, 'getRenditions').and.returnValue(
{ list: { entries: [{ entry: { id: 'webvtt', status: 'NOT_CREATED' } }] } } Promise.resolve(new RenditionPaging({ list: { entries: [{ entry: { id: 'webvtt', status: 'NOT_CREATED' } }] } }))
); );
spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValues('http://iam-fake.url'); spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValue('http://iam-fake.url');
component.ngOnChanges(change); component.ngOnChanges(change);
tick(); tick();
@@ -85,15 +85,15 @@ describe('Test Media player component ', () => {
})); }));
it('should not generate tracks for media file when webvtt rendition does not exist', fakeAsync(() => { it('should not generate tracks for media file when webvtt rendition does not exist', fakeAsync(() => {
spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValues( spyOn(alfrescoApiService.nodesApi, 'getNode').and.returnValue(
Promise.resolve(new NodeEntry({ entry: { name: 'file1', content: {} } })) Promise.resolve(new NodeEntry({ entry: { name: 'file1', content: {} } }))
); );
spyOn(alfrescoApiService.renditionsApi, 'getRenditions').and.returnValues( spyOn(alfrescoApiService.renditionsApi, 'getRenditions').and.returnValue(
{ list: { entries: [] } } Promise.resolve(new RenditionPaging({ list: { entries: [] } }))
); );
spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValues('http://iam-fake.url'); spyOn(alfrescoApiService.contentApi, 'getContentUrl').and.returnValue('http://iam-fake.url');
component.ngOnChanges(change); component.ngOnChanges(change);
tick(); tick();
@@ -337,13 +337,13 @@ describe('Test PdfViewer component', () => {
if (context.data.reason === pdfjsLib.PasswordResponses.NEED_PASSWORD) { if (context.data.reason === pdfjsLib.PasswordResponses.NEED_PASSWORD) {
return { return {
afterClosed: () => of('wrong_password') afterClosed: () => of('wrong_password')
}; } as any;
} }
if (context.data.reason === pdfjsLib.PasswordResponses.INCORRECT_PASSWORD) { if (context.data.reason === pdfjsLib.PasswordResponses.INCORRECT_PASSWORD) {
return { return {
afterClosed: () => of('password') afterClosed: () => of('password')
}; } as any;
} }
return undefined; return undefined;
@@ -404,7 +404,7 @@ describe('Test PdfViewer component', () => {
done(); done();
return of(''); return of('');
} }
}; } as any;
}); });
spyOn(componentUrlTestPasswordComponent.pdfViewerComponent.close, 'emit'); spyOn(componentUrlTestPasswordComponent.pdfViewerComponent.close, 'emit');
@@ -293,7 +293,7 @@ describe('ViewerComponent', () => {
const displayName = 'the-name'; const displayName = 'the-name';
const nodeDetails = { name: displayName, id: '12' }; const nodeDetails = { name: displayName, id: '12' };
const contentUrl = '/content/url/path'; const contentUrl = '/content/url/path';
const alfrescoApiInstanceMock = { const alfrescoApiInstanceMock: any = {
nodes: { nodes: {
getNodeInfo: () => Promise.resolve(nodeDetails), getNodeInfo: () => Promise.resolve(nodeDetails),
getNode: () => Promise.resolve({ id: 'fake-node', entry: { content: {} } }) getNode: () => Promise.resolve({ id: 'fake-node', entry: { content: {} } })
@@ -687,7 +687,7 @@ describe('ViewerComponent', () => {
const node = new NodeEntry({ entry: { name: displayName, id: '12', content: { mimeType: 'txt' } } }); const node = new NodeEntry({ entry: { name: displayName, id: '12', content: { mimeType: 'txt' } } });
const nodeDetails = { name: displayName, id: '12', content: { mimeType: 'txt' } }; const nodeDetails = { name: displayName, id: '12', content: { mimeType: 'txt' } };
const contentUrl = '/content/url/path'; const contentUrl = '/content/url/path';
const alfrescoApiInstanceMock = { const alfrescoApiInstanceMock: any = {
nodes: { nodes: {
getNodeInfo: () => Promise.resolve(nodeDetails), getNodeInfo: () => Promise.resolve(nodeDetails),
getNode: () => Promise.resolve(node) getNode: () => Promise.resolve(node)
@@ -1066,7 +1066,7 @@ describe('ViewerComponent', () => {
const displayName = 'the-name'; const displayName = 'the-name';
const nodeDetails = new NodeEntry({ entry: { name: displayName, id: '12', content: { mimeType: 'txt' } } }); const nodeDetails = new NodeEntry({ entry: { name: displayName, id: '12', content: { mimeType: 'txt' } } });
const contentUrl = '/content/url/path'; const contentUrl = '/content/url/path';
const alfrescoApiInstanceMock = { const alfrescoApiInstanceMock: any = {
nodes: { nodes: {
getNode: () => Promise.resolve(nodeDetails) getNode: () => Promise.resolve(nodeDetails)
}, },
@@ -90,7 +90,7 @@ describe('ExtensionLoaderService', () => {
return of(pluginConfig3); return of(pluginConfig3);
} }
return of({}); return of(null);
}); });
}); });
@@ -342,7 +342,7 @@ describe('AnalyticsReportParametersComponent', () => {
it('Should load the task list when a process definition is selected', () => { it('Should load the task list when a process definition is selected', () => {
component.successReportParams.subscribe((res) => { component.successReportParams.subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res.length).toEqual(2); expect(res['length']).toEqual(2);
expect(res[0].id).toEqual('Fake task name 1'); expect(res[0].id).toEqual('Fake task name 1');
expect(res[0].name).toEqual('Fake task name 1'); expect(res[0].name).toEqual('Fake task name 1');
expect(res[1].id).toEqual('Fake task name 2'); expect(res[1].id).toEqual('Fake task name 2');
@@ -34,7 +34,7 @@ describe('AppListCloudComponent', () => {
let getAppsSpy: jasmine.Spy; let getAppsSpy: jasmine.Spy;
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve(fakeApplicationInstance) callCustomApi: () => Promise.resolve(fakeApplicationInstance)
}, },
@@ -30,7 +30,7 @@ describe('AppsProcessCloudService', () => {
let appConfigService: AppConfigService; let appConfigService: AppConfigService;
let apiService: AlfrescoApiService; let apiService: AlfrescoApiService;
const apiMock = { const apiMock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }}) callCustomApi: () => Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }})
}, },
@@ -53,7 +53,7 @@ import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { CloudFormRenderingService } from './cloud-form-rendering.service'; import { CloudFormRenderingService } from './cloud-form-rendering.service';
import { Node } from '@alfresco/js-api'; import { Node } from '@alfresco/js-api';
const mockOauth2Auth = { const mockOauth2Auth: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve() callCustomApi: () => Promise.resolve()
}, },
@@ -310,7 +310,7 @@ describe('FormCloudComponent', () => {
spyOn(formCloudService, 'getTaskVariables').and.returnValue(of([])); spyOn(formCloudService, 'getTaskVariables').and.returnValue(of([]));
spyOn(formCloudService, 'getTask').and.callFake((currentTaskId) => { spyOn(formCloudService, 'getTask').and.callFake((currentTaskId) => {
return new Observable((observer) => { return new Observable((observer) => {
observer.next({ formRepresentation: { taskId: currentTaskId } }); observer.next({ formRepresentation: { taskId: currentTaskId } } as any);
observer.complete(); observer.complete();
}); });
}); });
@@ -357,7 +357,7 @@ describe('FormCloudComponent', () => {
}); });
it('should refresh visibility when the form is loaded', () => { it('should refresh visibility when the form is loaded', () => {
spyOn(formCloudService, 'getForm').and.returnValue(of({ formRepresentation: {} })); spyOn(formCloudService, 'getForm').and.returnValue(of({ formRepresentation: {} } as any));
const formId = '123'; const formId = '123';
const appName = 'test-app'; const appName = 'test-app';
@@ -44,7 +44,7 @@ describe('FormDefinitionCloudComponent', () => {
fixture = TestBed.createComponent(FormDefinitionSelectorCloudComponent); fixture = TestBed.createComponent(FormDefinitionSelectorCloudComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
service = TestBed.inject(FormDefinitionSelectorCloudService); service = TestBed.inject(FormDefinitionSelectorCloudService);
getFormsSpy = spyOn(service, 'getStandAloneTaskForms').and.returnValue(of([{ id: 'fake-form', name: 'fakeForm' }])); getFormsSpy = spyOn(service, 'getStandAloneTaskForms').and.returnValue(of([{ id: 'fake-form', name: 'fakeForm' } as any]));
}); });
it('should load the forms by default', () => { it('should load the forms by default', () => {
@@ -227,11 +227,11 @@ export const expectedValues = {
pfx_property_two: true pfx_property_two: true
}; };
export const mockNodeId = new Promise(function(resolve) { export const mockNodeId = new Promise<string>(function(resolve) {
resolve('mock-node-id'); resolve('mock-node-id');
}); });
export const mockNodeIdBasedOnStringVariableValue = new Promise(function(resolve) { export const mockNodeIdBasedOnStringVariableValue = new Promise<string>(function(resolve) {
resolve('mock-string-value-node-id'); resolve('mock-string-value-node-id');
}); });
@@ -759,7 +759,7 @@ export const emptyFormRepresentationJSON = {
'version': 0 'version': 0
}; };
export const conditionalUploadWidgetsMock = { export const conditionalUploadWidgetsMock: any = {
'formRepresentation': { 'formRepresentation': {
'id': 'form-fb7858f7-5cf6-4afe-b462-c15a5dc0c34c', 'id': 'form-fb7858f7-5cf6-4afe-b462-c15a5dc0c34c',
'name': 'AttachVisibility', 'name': 'AttachVisibility',
@@ -847,7 +847,7 @@ export const conditionalUploadWidgetsMock = {
} }
}; };
export const multilingualForm = { export const multilingualForm: any = {
'formRepresentation': { 'formRepresentation': {
'id': 'form-2aaaf20e-43d3-46bf-89be-859d5f512dd2', 'id': 'form-2aaaf20e-43d3-46bf-89be-859d5f512dd2',
'name': 'multilingualform', 'name': 'multilingualform',
@@ -56,7 +56,7 @@ describe('Form Cloud service', () => {
return false; return false;
}, },
reply: jasmine.createSpy('reply') reply: jasmine.createSpy('reply')
}); } as any);
}); });
describe('Form tests', () => { describe('Form tests', () => {
@@ -195,8 +195,11 @@ describe('Form Cloud service', () => {
it('should fetch task form flattened', (done) => { it('should fetch task form flattened', (done) => {
spyOn(service, 'getTask').and.returnValue(of(responseBody.entry)); spyOn(service, 'getTask').and.returnValue(of(responseBody.entry));
spyOn(service, 'getForm').and.returnValue(of({ spyOn(service, 'getForm').and.returnValue(of({
formRepresentation: {name: 'task-form', formDefinition: {} } formRepresentation: {
})); name: 'task-form',
formDefinition: {}
}
} as any));
service.getTaskForm(appName, taskId).subscribe((result) => { service.getTaskForm(appName, taskId).subscribe((result) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
@@ -76,7 +76,7 @@ describe('Form Definition Selector Cloud Service', () => {
return false; return false;
}, },
reply: jasmine.createSpy('reply') reply: jasmine.createSpy('reply')
}); } as any);
}); });
it('should fetch all the forms when getForms is called', (done) => { it('should fetch all the forms when getForms is called', (done) => {
@@ -40,7 +40,7 @@ describe('GroupCloudComponent', () => {
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
let findGroupsByNameSpy: jasmine.Spy; let findGroupsByNameSpy: jasmine.Spy;
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve(mockIdentityGroups) callCustomApi: () => Promise.resolve(mockIdentityGroups)
}, },
@@ -648,7 +648,7 @@ describe('GroupCloudComponent', () => {
describe('Preselected groups and validation enabled', () => { describe('Preselected groups and validation enabled', () => {
it('should check validation only for the first group and emit warning when group is invalid - single mode', (done) => { it('should check validation only for the first group and emit warning when group is invalid - single mode', (done) => {
spyOn(identityGroupService, 'findGroupsByName').and.returnValue(Promise.resolve([])); spyOn(identityGroupService, 'findGroupsByName').and.returnValue(of([]));
const expectedWarning = { const expectedWarning = {
message: 'INVALID_PRESELECTED_GROUPS', message: 'INVALID_PRESELECTED_GROUPS',
@@ -671,7 +671,7 @@ describe('GroupCloudComponent', () => {
}); });
it('should check validation for all the groups and emit warning - multiple mode', (done) => { it('should check validation for all the groups and emit warning - multiple mode', (done) => {
spyOn(identityGroupService, 'findGroupsByName').and.returnValue(Promise.resolve(undefined)); spyOn(identityGroupService, 'findGroupsByName').and.returnValue(of(undefined));
const expectedWarning = { const expectedWarning = {
message: 'INVALID_PRESELECTED_GROUPS', message: 'INVALID_PRESELECTED_GROUPS',
@@ -40,7 +40,7 @@ describe('PeopleCloudComponent', () => {
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
let findUsersByNameSpy: jasmine.Spy; let findUsersByNameSpy: jasmine.Spy;
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve(mockUsers) callCustomApi: () => Promise.resolve(mockUsers)
}, },
@@ -740,7 +740,7 @@ describe('PeopleCloudComponent', () => {
describe('Preselected users and validation enabled', () => { describe('Preselected users and validation enabled', () => {
it('should check validation only for the first user and emit warning when user is invalid - single mode', (done) => { it('should check validation only for the first user and emit warning when user is invalid - single mode', (done) => {
spyOn(identityService, 'findUserById').and.returnValue(Promise.resolve([])); spyOn(identityService, 'findUserById').and.returnValue(of([]));
const expectedWarning = { const expectedWarning = {
message: 'INVALID_PRESELECTED_USERS', message: 'INVALID_PRESELECTED_USERS',
users: [{ users: [{
@@ -762,7 +762,7 @@ describe('PeopleCloudComponent', () => {
}); });
it('should skip warnings if validation disabled', () => { it('should skip warnings if validation disabled', () => {
spyOn(identityService, 'findUserById').and.returnValue(Promise.resolve([])); spyOn(identityService, 'findUserById').and.returnValue(of([]));
spyOn(component, 'compare').and.returnValue(false); spyOn(component, 'compare').and.returnValue(false);
let warnings = 0; let warnings = 0;
@@ -779,7 +779,7 @@ describe('PeopleCloudComponent', () => {
}); });
it('should check validation for all the users and emit warning - multiple mode', (done) => { it('should check validation for all the users and emit warning - multiple mode', (done) => {
spyOn(identityService, 'findUserById').and.returnValue(Promise.resolve(undefined)); spyOn(identityService, 'findUserById').and.returnValue(of(undefined));
const expectedWarning = { const expectedWarning = {
message: 'INVALID_PRESELECTED_USERS', message: 'INVALID_PRESELECTED_USERS',
@@ -30,7 +30,7 @@ describe('ProcessNameCloudPipe', () => {
const defaultName = 'default-name'; const defaultName = 'default-name';
const datetimeIdentifier = '%{datetime}'; const datetimeIdentifier = '%{datetime}';
const processDefinitionIdentifier = '%{processDefinition}'; const processDefinitionIdentifier = '%{processDefinition}';
const mockCurrentDate = 'Wed Oct 23 2019'; const mockCurrentDate = new Date('Wed Oct 23 2019');
const mockLocalizedCurrentDate = 'Oct 23, 2019, 12:00:00 AM'; const mockLocalizedCurrentDate = 'Oct 23, 2019, 12:00:00 AM';
const nameWithProcessDefinitionIdentifier = `${defaultName} - ${processDefinitionIdentifier}`; const nameWithProcessDefinitionIdentifier = `${defaultName} - ${processDefinitionIdentifier}`;
const nameWithDatetimeIdentifier = `${defaultName} - ${datetimeIdentifier}`; const nameWithDatetimeIdentifier = `${defaultName} - ${datetimeIdentifier}`;
@@ -39,6 +39,7 @@ import { ProcessCloudService } from '../../services/process-cloud.service';
import { DateCloudFilterType } from '../../../models/date-cloud-filter.model'; import { DateCloudFilterType } from '../../../models/date-cloud-filter.model';
import { ApplicationVersionModel } from '../../../models/application-version.model'; import { ApplicationVersionModel } from '../../../models/application-version.model';
import { MatIconTestingModule } from '@angular/material/icon/testing'; import { MatIconTestingModule } from '@angular/material/icon/testing';
import { ProcessDefinitionCloud } from '../../../models/process-definition-cloud.model';
describe('EditProcessFilterCloudComponent', () => { describe('EditProcessFilterCloudComponent', () => {
let component: EditProcessFilterCloudComponent; let component: EditProcessFilterCloudComponent;
@@ -64,7 +65,7 @@ describe('EditProcessFilterCloudComponent', () => {
sort: 'id' sort: 'id'
}); });
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve(fakeApplicationInstance) callCustomApi: () => Promise.resolve(fakeApplicationInstance)
}, },
@@ -103,7 +104,7 @@ describe('EditProcessFilterCloudComponent', () => {
name: 'fake-name' name: 'fake-name'
}); });
} }
}); } as any);
getProcessFilterByIdSpy = spyOn(service, 'getFilterById').and.returnValue(of(fakeFilter)); getProcessFilterByIdSpy = spyOn(service, 'getFilterById').and.returnValue(of(fakeFilter));
getRunningApplicationsSpy = spyOn(appsService, 'getDeployedApplicationsByStatus').and.returnValue(of(fakeApplicationInstance)); getRunningApplicationsSpy = spyOn(appsService, 'getDeployedApplicationsByStatus').and.returnValue(of(fakeApplicationInstance));
spyOn(alfrescoApiService, 'getInstance').and.returnValue(mock); spyOn(alfrescoApiService, 'getInstance').and.returnValue(mock);
@@ -535,7 +536,7 @@ describe('EditProcessFilterCloudComponent', () => {
}); });
it('should fetch process definitions when processDefinitionName filter property is set', async(() => { it('should fetch process definitions when processDefinitionName filter property is set', async(() => {
const processSpy = spyOn(processService, 'getProcessDefinitions').and.returnValue(of([{ id: 'fake-id', name: 'fake-name' }])); const processSpy = spyOn(processService, 'getProcessDefinitions').and.returnValue(of([new ProcessDefinitionCloud({ id: 'fake-id', name: 'fake-name' })]));
fixture.detectChanges(); fixture.detectChanges();
component.filterProperties = ['processDefinitionName']; component.filterProperties = ['processDefinitionName'];
fixture.detectChanges(); fixture.detectChanges();
@@ -633,14 +634,19 @@ describe('EditProcessFilterCloudComponent', () => {
beforeEach(() => { beforeEach(() => {
const processFilterIdChange = new SimpleChange(null, 'mock-process-filter-id', true); const processFilterIdChange = new SimpleChange(null, 'mock-process-filter-id', true);
component.ngOnChanges({ 'id': processFilterIdChange });
getProcessFilterByIdSpy.and.returnValue(of(fakeFilter)); getProcessFilterByIdSpy.and.returnValue(of(fakeFilter));
component.ngOnChanges({ 'id': processFilterIdChange });
fixture.detectChanges(); fixture.detectChanges();
}); });
afterEach(() => {
fixture.destroy();
});
it('should emit save event and save the filter on click save button', async(() => { it('should emit save event and save the filter on click save button', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const saveFilterSpy = spyOn(service, 'updateFilter').and.returnValue(of(fakeFilter)); const saveFilterSpy = spyOn(service, 'updateFilter').and.returnValue(of([fakeFilter]));
const saveSpy: jasmine.Spy = spyOn(component.action, 'emit'); const saveSpy: jasmine.Spy = spyOn(component.action, 'emit');
fixture.detectChanges(); fixture.detectChanges();
@@ -661,30 +667,33 @@ describe('EditProcessFilterCloudComponent', () => {
}); });
})); }));
it('should emit delete event and delete the filter on click of delete button', (done) => { it('should emit delete event and delete the filter on click of delete button', async () => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of({})); const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of({} as any));
const deleteSpy = spyOn(component.action, 'emit'); const deleteSpy = spyOn(component.action, 'emit');
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger'); const stateElement = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-cloud-edit-process-property-status"] .mat-select-trigger');
stateElement.click(); stateElement.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]'); const deleteButton = fixture.debugElement.nativeElement.querySelector('[data-automation-id="adf-filter-action-delete"]');
deleteButton.click(); deleteButton.click();
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { await fixture.whenStable();
expect(deleteFilterSpy).toHaveBeenCalled();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(deleteSpy).toHaveBeenCalled();
done();
});
}); expect(deleteFilterSpy).toHaveBeenCalled();
expect(deleteSpy).toHaveBeenCalled();
}); });
it('should emit saveAs event and add filter on click saveAs button', async(() => { it('should emit saveAs event and add filter on click saveAs button', async(() => {
@@ -910,7 +919,7 @@ describe('EditProcessFilterCloudComponent', () => {
it('should not call restore default filters service on deletion first filter', (done) => { it('should not call restore default filters service on deletion first filter', (done) => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of([{ name: 'mock-filter-name'}])); const deleteFilterSpy = spyOn(service, 'deleteFilter').and.returnValue(of([new ProcessFilterCloudModel({ name: 'mock-filter-name'})]));
const restoreFiltersSpy = spyOn(component, 'restoreDefaultProcessFilters').and.returnValue(of([])); const restoreFiltersSpy = spyOn(component, 'restoreDefaultProcessFilters').and.returnValue(of([]));
const deleteSpy: jasmine.Spy = spyOn(component.action, 'emit'); const deleteSpy: jasmine.Spy = spyOn(component.action, 'emit');
fixture.detectChanges(); fixture.detectChanges();
@@ -16,9 +16,9 @@
*/ */
import { SimpleChange } from '@angular/core'; import { SimpleChange } from '@angular/core';
import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { from, Observable } from 'rxjs'; import { of, throwError } from 'rxjs';
import { ProcessFilterCloudService } from '../services/process-filter-cloud.service'; import { ProcessFilterCloudService } from '../services/process-filter-cloud.service';
import { ProcessFiltersCloudComponent } from './process-filters-cloud.component'; import { ProcessFiltersCloudComponent } from './process-filters-cloud.component';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
@@ -30,27 +30,10 @@ import { TranslateModule } from '@ngx-translate/core';
import { mockProcessFilters } from '../mock/process-filters-cloud.mock'; import { mockProcessFilters } from '../mock/process-filters-cloud.mock';
describe('ProcessFiltersCloudComponent', () => { describe('ProcessFiltersCloudComponent', () => {
let processFilterService: ProcessFilterCloudService; let processFilterService: ProcessFilterCloudService;
const fakeGlobalFilterObservable =
new Observable(function(observer) {
observer.next(mockProcessFilters);
observer.complete();
});
const fakeGlobalFilterPromise = new Promise(function (resolve) {
resolve(mockProcessFilters);
});
const mockErrorFilterList = {
error: 'wrong request'
};
const mockErrorFilterPromise = Promise.reject(mockErrorFilterList);
let component: ProcessFiltersCloudComponent; let component: ProcessFiltersCloudComponent;
let fixture: ComponentFixture<ProcessFiltersCloudComponent>; let fixture: ComponentFixture<ProcessFiltersCloudComponent>;
let getProcessFiltersSpy: jasmine.Spy;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -68,16 +51,25 @@ describe('ProcessFiltersCloudComponent', () => {
component = fixture.componentInstance; component = fixture.componentInstance;
processFilterService = TestBed.inject(ProcessFilterCloudService); processFilterService = TestBed.inject(ProcessFilterCloudService);
getProcessFiltersSpy = spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(mockProcessFilters));
}); });
it('should attach specific icon for each filter if hasIcon is true', async(() => { afterEach(() => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable); fixture.destroy();
});
it('should attach specific icon for each filter if hasIcon is true', async () => {
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({'appName': change}); component.ngOnChanges({'appName': change});
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.showIcons = true; component.showIcons = true;
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
expect(component.filters.length).toBe(3); expect(component.filters.length).toBe(3);
const filters = fixture.nativeElement.querySelectorAll('.adf-icon'); const filters = fixture.nativeElement.querySelectorAll('.adf-icon');
expect(filters.length).toBe(3); expect(filters.length).toBe(3);
@@ -85,32 +77,31 @@ describe('ProcessFiltersCloudComponent', () => {
expect(filters[1].innerText).toContain('inbox'); expect(filters[1].innerText).toContain('inbox');
expect(filters[2].innerText).toContain('done'); expect(filters[2].innerText).toContain('done');
}); });
}));
it('should not attach icons for each filter if hasIcon is false', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(from(fakeGlobalFilterPromise));
it('should not attach icons for each filter if hasIcon is false', async () => {
component.showIcons = false; component.showIcons = false;
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({'appName': change}); component.ngOnChanges({'appName': change});
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon')); const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon'));
expect(filters.length).toBe(0); expect(filters.length).toBe(0);
done();
});
}); });
it('should display the filters', async(() => { it('should display the filters', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable);
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({'appName': change}); component.ngOnChanges({'appName': change});
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.showIcons = true; component.showIcons = true;
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const filters = fixture.debugElement.queryAll(By.css('.adf-filters__entry')); const filters = fixture.debugElement.queryAll(By.css('.adf-filters__entry'));
expect(component.filters.length).toBe(3); expect(component.filters.length).toBe(3);
expect(filters.length).toBe(3); expect(filters.length).toBe(3);
@@ -118,148 +109,125 @@ describe('ProcessFiltersCloudComponent', () => {
expect(filters[1].nativeElement.innerText).toContain('FakeRunningProcesses'); expect(filters[1].nativeElement.innerText).toContain('FakeRunningProcesses');
expect(filters[2].nativeElement.innerText).toContain('FakeCompletedProcesses'); expect(filters[2].nativeElement.innerText).toContain('FakeCompletedProcesses');
}); });
}));
it('should emit an error with a bad response', (done) => { it('should emit an error with a bad response', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(from(mockErrorFilterPromise)); const mockErrorFilterList = {
error: 'wrong request'
};
getProcessFiltersSpy.and.returnValue(throwError(mockErrorFilterList));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({'appName': change});
component.error.subscribe((err) => { component.error.subscribe((err) => {
expect(err).toBeDefined(); expect(err).toBeDefined();
done(); done();
}); });
component.ngOnChanges({'appName': change});
fixture.detectChanges();
}); });
it('should emit success with the filters when filters are loaded', (done) => { it('should emit success with the filters when filters are loaded', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(from(fakeGlobalFilterPromise));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { component.ngOnChanges({ 'appName': change });
expect(res).toBeDefined(); fixture.detectChanges();
await fixture.whenStable();
expect(component.filters).toBeDefined(); expect(component.filters).toBeDefined();
expect(component.filters[0].name).toEqual('FakeAllProcesses'); expect(component.filters[0].name).toEqual('FakeAllProcesses');
expect(component.filters[1].name).toEqual('FakeRunningProcesses'); expect(component.filters[1].name).toEqual('FakeRunningProcesses');
expect(component.filters[2].name).toEqual('FakeCompletedProcesses'); expect(component.filters[2].name).toEqual('FakeCompletedProcesses');
done();
});
}); });
it('should select the first filter as default', async(() => { it('should select the first process cloud filter as default', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable);
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
await fixture.whenStable();
component.success.subscribe((res) => {
expect(res).toBeDefined();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeAllProcesses'); expect(component.currentFilter.name).toEqual('FakeAllProcesses');
}); });
})); it('should select the filter based on the input by name param', async () => {
it('should select the filter based on the input by name param', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { name: 'FakeRunningProcesses' }; component.filterParam = { name: 'FakeRunningProcesses' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.filterSelected.subscribe((res) => { component.ngOnChanges({ 'appName': change });
expect(res).toBeDefined();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeRunningProcesses');
done();
});
fixture.detectChanges(); fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); await fixture.whenStable();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeRunningProcesses');
}); });
it('should select the filter based on the input by key param', (done) => { it('should select the filter based on the input by key param', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { key: 'completed-processes' }; component.filterParam = { key: 'completed-processes' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.filterSelected.subscribe((res) => {
expect(res).toBeDefined();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeCompletedProcesses'); expect(component.currentFilter.name).toEqual('FakeCompletedProcesses');
done();
}); });
component.ngOnChanges({ 'appName': change }); it('should select the filter based on the input by index param', async () => {
});
it('should select the filter based on the input by index param', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { index: 2 }; component.filterParam = { index: 2 };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.filterSelected.subscribe((res) => {
expect(res).toBeDefined();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeCompletedProcesses');
done();
});
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
await fixture.whenStable();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeCompletedProcesses');
}); });
it('should select the filter based on the input by id param', (done) => { it('should select the filter based on the input by id param', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { id: '12' }; component.filterParam = { id: '12' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.filterSelected.subscribe((res) => {
expect(res).toBeDefined();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeCompletedProcesses');
done();
});
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
await fixture.whenStable();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeCompletedProcesses');
}); });
it('should filterClicked emit when a filter is clicked from the UI', (done) => { it('should filterClicked emit when a filter is clicked from the UI', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { id: '10' }; component.filterParam = { id: '10' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
component.filterClicked.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeAllProcesses');
done();
});
const filterButton = fixture.debugElement.nativeElement.querySelector(`[data-automation-id="${mockProcessFilters[0].key}_filter"]`); const filterButton = fixture.debugElement.nativeElement.querySelector(`[data-automation-id="${mockProcessFilters[0].key}_filter"]`);
filterButton.click(); filterButton.click();
fixture.detectChanges();
await fixture.whenStable();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeAllProcesses');
}); });
it('should not emit a filter click event on binding changes', () => { it('should not emit a filter click event on binding changes', () => {
@@ -270,7 +238,7 @@ describe('ProcessFiltersCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(component.selectFilterAndEmit).toHaveBeenCalled(); expect(component.selectFilterAndEmit).toHaveBeenCalled();
expect(component.currentFilter).not.toBeDefined(); expect(component.currentFilter).toBe(mockProcessFilters[0]);
}); });
it('should reload filters by appName on binding changes', () => { it('should reload filters by appName on binding changes', () => {
@@ -94,8 +94,16 @@ export class ProcessFiltersCloudComponent implements OnInit, OnChanges, OnDestro
this.filters$.pipe(takeUntil(this.onDestroy$)).subscribe( this.filters$.pipe(takeUntil(this.onDestroy$)).subscribe(
(res: ProcessFilterCloudModel[]) => { (res: ProcessFilterCloudModel[]) => {
this.resetFilter(); this.resetFilter();
this.filters = Object.assign([], res); this.filters = res || [];
if (this.filterParam) {
this.selectFilterAndEmit(this.filterParam); this.selectFilterAndEmit(this.filterParam);
}
if (!this.currentFilter && this.filters.length > 0) {
this.currentFilter = this.filters[0];
}
this.success.emit(res); this.success.emit(res);
}, },
(err: any) => { (err: any) => {
@@ -51,28 +51,28 @@ export const fakeProcessCloudFilters = [
} }
]; ];
export const mockProcessFilters = [ export const mockProcessFilters: any[] = [
new ProcessFilterCloudModel({ {
name: 'FakeAllProcesses', name: 'FakeAllProcesses',
key: 'FakeAllProcesses', key: 'FakeAllProcesses',
icon: 'adjust', icon: 'adjust',
id: '10', id: '10',
status: '' status: ''
}), },
new ProcessFilterCloudModel({ {
name: 'FakeRunningProcesses', name: 'FakeRunningProcesses',
key: 'FakeRunningProcesses', key: 'FakeRunningProcesses',
icon: 'inbox', icon: 'inbox',
id: '11', id: '11',
status: 'RUNNING' status: 'RUNNING'
}), },
new ProcessFilterCloudModel({ {
name: 'FakeCompletedProcesses', name: 'FakeCompletedProcesses',
key: 'completed-processes', key: 'completed-processes',
icon: 'done', icon: 'done',
id: '12', id: '12',
status: 'COMPLETED' status: 'COMPLETED'
}) }
]; ];
export const fakeProcessFilter: ProcessFilterCloudModel = new ProcessFilterCloudModel({ export const fakeProcessFilter: ProcessFilterCloudModel = new ProcessFilterCloudModel({
@@ -24,16 +24,17 @@ import { ProcessHeaderCloudComponent } from './process-header-cloud.component';
import { ProcessHeaderCloudModule } from '../process-header-cloud.module'; import { ProcessHeaderCloudModule } from '../process-header-cloud.module';
import { ProcessCloudService } from '../../services/process-cloud.service'; import { ProcessCloudService } from '../../services/process-cloud.service';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { ProcessInstanceCloud } from '../../start-process/models/process-instance-cloud.model';
const processInstanceDetailsCloudMock = { const processInstanceDetailsCloudMock: ProcessInstanceCloud = {
appName: 'app-form-mau', appName: 'app-form-mau',
businessKey: 'MyBusinessKey', businessKey: 'MyBusinessKey',
id: '00fcc4ab-4290-11e9-b133-0a586460016a', id: '00fcc4ab-4290-11e9-b133-0a586460016a',
initiator: 'devopsuser', initiator: 'devopsuser',
lastModified: 1552152187081, lastModified: new Date(1552152187081),
name: 'new name', name: 'new name',
parentId: '00fcc4ab-4290-11e9-b133-0a586460016b', parentId: '00fcc4ab-4290-11e9-b133-0a586460016b',
startDate: 1552152187080, startDate: new Date(1552152187080),
status: 'RUNNING' status: 'RUNNING'
}; };
@@ -24,7 +24,7 @@ describe('ProcessListCloudService', () => {
let service: ProcessListCloudService; let service: ProcessListCloudService;
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
function returnCallQueryParameters() { function returnCallQueryParameters(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => { callCustomApi: (_queryUrl, _operation, _context, queryParams) => {
@@ -37,7 +37,7 @@ describe('ProcessListCloudService', () => {
}; };
} }
function returnCallUrl() { function returnCallUrl(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi: (queryUrl) => { callCustomApi: (queryUrl) => {
@@ -28,7 +28,7 @@ describe('StartProcessCloudService', () => {
let service: StartProcessCloudService; let service: StartProcessCloudService;
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve({ callCustomApi: () => Promise.resolve({
entry: { entry: {
@@ -86,7 +86,7 @@ describe('StartProcessCloudService', () => {
}); });
it('should be able to get all the process definitions', (done) => { it('should be able to get all the process definitions', (done) => {
spyOn(service, 'getProcessDefinitions').and.returnValue(of([{ id: 'fake-id', name: 'fake-name' }])); spyOn(service, 'getProcessDefinitions').and.returnValue(of([new ProcessDefinitionCloud({ id: 'fake-id', name: 'fake-name' })]));
service.getProcessDefinitions('appName1') service.getProcessDefinitions('appName1')
.subscribe( .subscribe(
(res: ProcessDefinitionCloud[]) => { (res: ProcessDefinitionCloud[]) => {
@@ -25,10 +25,10 @@ import { Apollo } from 'apollo-angular';
describe('NotificationCloudService', () => { describe('NotificationCloudService', () => {
let service: NotificationCloudService; let service: NotificationCloudService;
let apollo: Apollo; let apollo: Apollo;
let apolloCreateSpy; let apolloCreateSpy: jasmine.Spy;
let apolloSubscribeSpy; let apolloSubscribeSpy: jasmine.Spy;
let apiService: AlfrescoApiService; let apiService: AlfrescoApiService;
const useMock = { const useMock: any = {
subscribe() {} subscribe() {}
}; };
@@ -43,7 +43,7 @@ describe('NotificationCloudService', () => {
} }
`; `;
const apiServiceMock = { const apiServiceMock: any = {
oauth2Auth: { oauth2Auth: {
token: '1234567' token: '1234567'
}, },
@@ -33,7 +33,7 @@ describe('PreferenceService', () => {
state: 404, stateText: 'Not Found' state: 404, stateText: 'Not Found'
}; };
function apiMock(mockResponse) { function apiMock(mockResponse): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
@@ -47,7 +47,7 @@ describe('PreferenceService', () => {
}; };
} }
const apiErrorMock = { const apiErrorMock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.reject(errorResponse) callCustomApi: () => Promise.reject(errorResponse)
}, },
@@ -32,7 +32,7 @@ describe('Task Cloud Service', () => {
let identityUserService: IdentityUserService; let identityUserService: IdentityUserService;
let translateService: TranslationService; let translateService: TranslationService;
function returnFakeTaskCompleteResults() { function returnFakeTaskCompleteResults(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi : () => { callCustomApi : () => {
@@ -45,7 +45,7 @@ describe('Task Cloud Service', () => {
}; };
} }
function returnFakeTaskCompleteResultsError() { function returnFakeTaskCompleteResultsError(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi : () => { callCustomApi : () => {
@@ -58,7 +58,7 @@ describe('Task Cloud Service', () => {
}; };
} }
function returnFakeTaskDetailsResults() { function returnFakeTaskDetailsResults(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi : () => { callCustomApi : () => {
@@ -71,7 +71,7 @@ describe('Task Cloud Service', () => {
}; };
} }
function returnFakeCandidateUsersResults() { function returnFakeCandidateUsersResults(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi : () => { callCustomApi : () => {
@@ -84,7 +84,7 @@ describe('Task Cloud Service', () => {
}; };
} }
function returnFakeCandidateGroupResults() { function returnFakeCandidateGroupResults(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi : () => { callCustomApi : () => {
@@ -38,7 +38,7 @@ describe('StartTaskCloudComponent', () => {
let createNewTaskSpy: jasmine.Spy; let createNewTaskSpy: jasmine.Spy;
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve(taskDetailsMock) callCustomApi: () => Promise.resolve(taskDetailsMock)
}, },
@@ -68,7 +68,7 @@ describe('StartTaskCloudComponent', () => {
alfrescoApiService = TestBed.inject(AlfrescoApiService); alfrescoApiService = TestBed.inject(AlfrescoApiService);
formDefinitionSelectorCloudService = TestBed.inject(FormDefinitionSelectorCloudService); formDefinitionSelectorCloudService = TestBed.inject(FormDefinitionSelectorCloudService);
spyOn(alfrescoApiService, 'getInstance').and.returnValue(mock); spyOn(alfrescoApiService, 'getInstance').and.returnValue(mock);
createNewTaskSpy = spyOn(service, 'createNewTask').and.returnValue(of(taskDetailsMock)); createNewTaskSpy = spyOn(service, 'createNewTask').and.returnValue(of(taskDetailsMock as any));
spyOn(identityService, 'getCurrentUserInfo').and.returnValue(mockUser); spyOn(identityService, 'getCurrentUserInfo').and.returnValue(mockUser);
spyOn(formDefinitionSelectorCloudService, 'getForms').and.returnValue(of([])); spyOn(formDefinitionSelectorCloudService, 'getForms').and.returnValue(of([]));
fixture.detectChanges(); fixture.detectChanges();
@@ -34,6 +34,7 @@ import { fakeServiceFilter } from '../../mock/task-filters-cloud.mock';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { EditServiceTaskFilterCloudComponent } from './edit-service-task-filter-cloud.component'; import { EditServiceTaskFilterCloudComponent } from './edit-service-task-filter-cloud.component';
import { MatIconTestingModule } from '@angular/material/icon/testing'; import { MatIconTestingModule } from '@angular/material/icon/testing';
import { ProcessDefinitionCloud } from '../../../../models/process-definition-cloud.model';
describe('EditServiceTaskFilterCloudComponent', () => { describe('EditServiceTaskFilterCloudComponent', () => {
let component: EditServiceTaskFilterCloudComponent; let component: EditServiceTaskFilterCloudComponent;
@@ -71,7 +72,7 @@ describe('EditServiceTaskFilterCloudComponent', () => {
icon: 'icon', icon: 'icon',
name: 'fake-name' name: 'fake-name'
}) })
}); } as any);
getTaskFilterSpy = spyOn(service, 'getTaskFilterById').and.returnValue(of(fakeServiceFilter)); getTaskFilterSpy = spyOn(service, 'getTaskFilterById').and.returnValue(of(fakeServiceFilter));
getRunningApplicationsSpy = spyOn(appsService, 'getDeployedApplicationsByStatus').and.returnValue(of(fakeApplicationInstance)); getRunningApplicationsSpy = spyOn(appsService, 'getDeployedApplicationsByStatus').and.returnValue(of(fakeApplicationInstance));
fixture.detectChanges(); fixture.detectChanges();
@@ -94,7 +95,9 @@ describe('EditServiceTaskFilterCloudComponent', () => {
}); });
it('should fetch process definitions when processDefinitionName filter property is set', async(() => { it('should fetch process definitions when processDefinitionName filter property is set', async(() => {
const processSpy = spyOn(taskService, 'getProcessDefinitions').and.returnValue(of([{ id: 'fake-id', name: 'fake-name' }])); const processSpy = spyOn(taskService, 'getProcessDefinitions').and.returnValue(of([
new ProcessDefinitionCloud({ id: 'fake-id', name: 'fake-name' })
]));
fixture.detectChanges(); fixture.detectChanges();
component.filterProperties = ['processDefinitionName']; component.filterProperties = ['processDefinitionName'];
fixture.detectChanges(); fixture.detectChanges();
@@ -602,7 +605,7 @@ describe('EditServiceTaskFilterCloudComponent', () => {
it('should emit save event and save the filter on click save button', async(() => { it('should emit save event and save the filter on click save button', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
spyOn(service, 'updateFilter').and.returnValue(of({})); spyOn(service, 'updateFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
@@ -625,7 +628,7 @@ describe('EditServiceTaskFilterCloudComponent', () => {
it('should emit delete event and delete the filter on click of delete button', async(() => { it('should emit delete event and delete the filter on click of delete button', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
spyOn(service, 'deleteFilter').and.returnValue(of({})); spyOn(service, 'deleteFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
@@ -645,7 +648,7 @@ describe('EditServiceTaskFilterCloudComponent', () => {
it('should emit saveAs event and add filter on click saveAs button', async(() => { it('should emit saveAs event and add filter on click saveAs button', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
spyOn(service, 'addFilter').and.returnValue(of({})); spyOn(service, 'addFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
@@ -39,6 +39,7 @@ import { TranslateModule } from '@ngx-translate/core';
import { DateCloudFilterType } from '../../../../models/date-cloud-filter.model'; import { DateCloudFilterType } from '../../../../models/date-cloud-filter.model';
import { TaskFilterCloudModel } from '../../models/filter-cloud.model'; import { TaskFilterCloudModel } from '../../models/filter-cloud.model';
import { PeopleCloudModule } from '../../../../people/people-cloud.module'; import { PeopleCloudModule } from '../../../../people/people-cloud.module';
import { ProcessDefinitionCloud } from '../../../../models/process-definition-cloud.model';
describe('EditTaskFilterCloudComponent', () => { describe('EditTaskFilterCloudComponent', () => {
let component: EditTaskFilterCloudComponent; let component: EditTaskFilterCloudComponent;
@@ -51,7 +52,7 @@ describe('EditTaskFilterCloudComponent', () => {
let getRunningApplicationsSpy: jasmine.Spy; let getRunningApplicationsSpy: jasmine.Spy;
let taskService: TaskCloudService; let taskService: TaskCloudService;
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve(fakeApplicationInstance) callCustomApi: () => Promise.resolve(fakeApplicationInstance)
}, },
@@ -88,7 +89,7 @@ describe('EditTaskFilterCloudComponent', () => {
icon: 'icon', icon: 'icon',
name: 'fake-name' name: 'fake-name'
}) })
}); } as any);
spyOn(alfrescoApiService, 'getInstance').and.returnValue(mock); spyOn(alfrescoApiService, 'getInstance').and.returnValue(mock);
getTaskFilterSpy = spyOn(service, 'getTaskFilterById').and.returnValue(of(fakeFilter)); getTaskFilterSpy = spyOn(service, 'getTaskFilterById').and.returnValue(of(fakeFilter));
getRunningApplicationsSpy = spyOn(appsService, 'getDeployedApplicationsByStatus').and.returnValue(of(fakeApplicationInstance)); getRunningApplicationsSpy = spyOn(appsService, 'getDeployedApplicationsByStatus').and.returnValue(of(fakeApplicationInstance));
@@ -112,7 +113,7 @@ describe('EditTaskFilterCloudComponent', () => {
}); });
it('should fetch process definitions when processDefinitionName filter property is set', async(() => { it('should fetch process definitions when processDefinitionName filter property is set', async(() => {
const processSpy = spyOn(taskService, 'getProcessDefinitions').and.returnValue(of([{ id: 'fake-id', name: 'fake-name' }])); const processSpy = spyOn(taskService, 'getProcessDefinitions').and.returnValue(of([new ProcessDefinitionCloud({ id: 'fake-id', name: 'fake-name' })]));
fixture.detectChanges(); fixture.detectChanges();
component.filterProperties = ['processDefinitionName']; component.filterProperties = ['processDefinitionName'];
fixture.detectChanges(); fixture.detectChanges();
@@ -935,7 +936,7 @@ describe('EditTaskFilterCloudComponent', () => {
it('should emit save event and save the filter on click save button', async(() => { it('should emit save event and save the filter on click save button', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
spyOn(service, 'updateFilter').and.returnValue(of({})); spyOn(service, 'updateFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
@@ -958,7 +959,7 @@ describe('EditTaskFilterCloudComponent', () => {
it('should emit delete event and delete the filter on click of delete button', async(() => { it('should emit delete event and delete the filter on click of delete button', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
spyOn(service, 'deleteFilter').and.returnValue(of({})); spyOn(service, 'deleteFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
@@ -978,7 +979,7 @@ describe('EditTaskFilterCloudComponent', () => {
it('should emit saveAs event and add filter on click saveAs button', async(() => { it('should emit saveAs event and add filter on click saveAs button', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
spyOn(service, 'addFilter').and.returnValue(of({})); spyOn(service, 'addFilter').and.returnValue(of(null));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
expansionPanel.click(); expansionPanel.click();
@@ -1024,7 +1025,7 @@ describe('EditTaskFilterCloudComponent', () => {
it('should not call restore default filters service on deletion of first filter', async(() => { it('should not call restore default filters service on deletion of first filter', async(() => {
component.toggleFilterActions = true; component.toggleFilterActions = true;
spyOn(service, 'deleteFilter').and.returnValue(of([{ name: 'mock-filter-name' }])); spyOn(service, 'deleteFilter').and.returnValue(of([new TaskFilterCloudModel({ name: 'mock-filter-name' })]));
const restoreDefaultFiltersSpy = spyOn(component, 'restoreDefaultTaskFilters').and.returnValue(of([])); const restoreDefaultFiltersSpy = spyOn(component, 'restoreDefaultTaskFilters').and.returnValue(of([]));
fixture.detectChanges(); fixture.detectChanges();
const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header'); const expansionPanel = fixture.debugElement.nativeElement.querySelector('mat-expansion-panel-header');
@@ -16,9 +16,9 @@
*/ */
import { SimpleChange } from '@angular/core'; import { SimpleChange } from '@angular/core';
import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { from, Observable } from 'rxjs'; import { of, throwError } from 'rxjs';
import { TASK_FILTERS_SERVICE_TOKEN } from '../../../services/cloud-token.service'; import { TASK_FILTERS_SERVICE_TOKEN } from '../../../services/cloud-token.service';
import { LocalPreferenceCloudService } from '../../../services/local-preference-cloud.service'; import { LocalPreferenceCloudService } from '../../../services/local-preference-cloud.service';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
@@ -30,24 +30,8 @@ import { ServiceTaskFilterCloudService } from '../services/service-task-filter-c
import { ServiceTaskFiltersCloudComponent } from './service-task-filters-cloud.component'; import { ServiceTaskFiltersCloudComponent } from './service-task-filters-cloud.component';
describe('ServiceTaskFiltersCloudComponent', () => { describe('ServiceTaskFiltersCloudComponent', () => {
let serviceTaskFilterCloudService: ServiceTaskFilterCloudService; let serviceTaskFilterCloudService: ServiceTaskFilterCloudService;
let getTaskListFiltersSpy: jasmine.Spy;
const fakeGlobalFilterObservable =
new Observable(function(observer) {
observer.next(fakeGlobalServiceFilters);
observer.complete();
});
const fakeGlobalFilterPromise = new Promise(function (resolve) {
resolve(fakeGlobalServiceFilters);
});
const mockErrorFilterList = {
error: 'wrong request'
};
const mockErrorFilterPromise = Promise.reject(mockErrorFilterList);
let component: ServiceTaskFiltersCloudComponent; let component: ServiceTaskFiltersCloudComponent;
let fixture: ComponentFixture<ServiceTaskFiltersCloudComponent>; let fixture: ComponentFixture<ServiceTaskFiltersCloudComponent>;
@@ -68,49 +52,60 @@ describe('ServiceTaskFiltersCloudComponent', () => {
component = fixture.componentInstance; component = fixture.componentInstance;
serviceTaskFilterCloudService = TestBed.inject(ServiceTaskFilterCloudService); serviceTaskFilterCloudService = TestBed.inject(ServiceTaskFilterCloudService);
getTaskListFiltersSpy = spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(of(fakeGlobalServiceFilters));
}); });
it('should attach specific icon for each filter if hasIcon is true', async(() => { afterEach(() => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable); fixture.destroy();
});
it('should attach specific icon for each filter if hasIcon is true', async () => {
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({'appName': change}); component.ngOnChanges({'appName': change});
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.showIcons = true; component.showIcons = true;
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
expect(component.filters.length).toBe(3); expect(component.filters.length).toBe(3);
const filters = fixture.nativeElement.querySelectorAll('.adf-icon'); const filters = fixture.nativeElement.querySelectorAll('.adf-icon');
expect(filters.length).toBe(3); expect(filters.length).toBe(3);
expect(filters[0].innerText).toContain('adjust'); expect(filters[0].innerText).toContain('adjust');
expect(filters[1].innerText).toContain('done'); expect(filters[1].innerText).toContain('done');
expect(filters[2].innerText).toContain('inbox'); expect(filters[2].innerText).toContain('inbox');
}); });
}));
it('should not attach icons for each filter if hasIcon is false', (done) => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(from(fakeGlobalFilterPromise));
it('should not attach icons for each filter if hasIcon is false', async () => {
component.showIcons = false; component.showIcons = false;
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({'appName': change}); component.ngOnChanges({'appName': change});
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon')); const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon'));
expect(filters.length).toBe(0); expect(filters.length).toBe(0);
done();
});
}); });
it('should display the filters', async(() => { it('should display the filters', async () => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({'appName': change}); component.ngOnChanges({'appName': change});
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.showIcons = true; component.showIcons = true;
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const filters = fixture.debugElement.queryAll(By.css('.adf-task-filters__entry')); const filters = fixture.debugElement.queryAll(By.css('.adf-task-filters__entry'));
expect(component.filters.length).toBe(3); expect(component.filters.length).toBe(3);
expect(filters.length).toBe(3); expect(filters.length).toBe(3);
@@ -118,144 +113,125 @@ describe('ServiceTaskFiltersCloudComponent', () => {
expect(filters[1].nativeElement.innerText).toContain('FakeMyServiceTasks1'); expect(filters[1].nativeElement.innerText).toContain('FakeMyServiceTasks1');
expect(filters[2].nativeElement.innerText).toContain('FakeMyServiceTasks2'); expect(filters[2].nativeElement.innerText).toContain('FakeMyServiceTasks2');
}); });
}));
it('should emit an error with a bad response', (done) => { it('should emit an error with a bad response', (done) => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(from(mockErrorFilterPromise)); const mockErrorFilterList = {
error: 'wrong request'
};
getTaskListFiltersSpy.and.returnValue(throwError(mockErrorFilterList));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({'appName': change});
component.error.subscribe((err) => { component.error.subscribe((err) => {
expect(err).toBeDefined(); expect(err).toBeDefined();
done(); done();
}); });
component.ngOnChanges({'appName': change});
fixture.detectChanges();
}); });
it('should return the filter task list', (done) => { it('should return the filter task list', async () => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(from(fakeGlobalFilterPromise));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.filters).toBeDefined(); expect(component.filters).toBeDefined();
expect(component.filters.length).toEqual(3); expect(component.filters.length).toEqual(3);
done();
});
}); });
it('should return the filter task list, filtered By Name', (done) => { it('should return the filter task list, filtered By Name', async () => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(from(fakeGlobalFilterPromise));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.filters).toBeDefined(); expect(component.filters).toBeDefined();
expect(component.filters[0].name).toEqual('FakeServiceTasks'); expect(component.filters[0].name).toEqual('FakeServiceTasks');
expect(component.filters[1].name).toEqual('FakeMyServiceTasks1'); expect(component.filters[1].name).toEqual('FakeMyServiceTasks1');
expect(component.filters[2].name).toEqual('FakeMyServiceTasks2'); expect(component.filters[2].name).toEqual('FakeMyServiceTasks2');
done();
});
}); });
it('should select the first filter as default', async(() => { it('should select the first service task filter as default', async () => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeServiceTasks'); expect(component.currentFilter.name).toEqual('FakeServiceTasks');
}); });
})); it('should select the task filter based on the input by name param', async () => {
it('should select the task filter based on the input by name param', async(() => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { name: 'FakeMyServiceTasks1' }; component.filterParam = { name: 'FakeMyServiceTasks1' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeMyServiceTasks1'); expect(component.currentFilter.name).toEqual('FakeMyServiceTasks1');
}); });
})); it('should select the default task filter if filter input does not exist', async () => {
it('should select the default task filter if filter input does not exist', async(() => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { name: 'UnexistableFilter' }; component.filterParam = { name: 'UnexistableFilter' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter).toBeDefined('current filter not found');
expect(component.currentFilter.name).toEqual('FakeServiceTasks'); expect(component.currentFilter.name).toEqual('FakeServiceTasks');
}); });
})); it('should select the task filter based on the input by index param', async () => {
it('should select the task filter based on the input by index param', async(() => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { index: 2 }; component.filterParam = { index: 2 };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeMyServiceTasks2'); expect(component.currentFilter.name).toEqual('FakeMyServiceTasks2');
}); });
})); it('should select the task filter based on the input by id param', async () => {
it('should select the task filter based on the input by id param', async(() => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { id: '12' }; component.filterParam = { id: '12' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeMyServiceTasks2'); expect(component.currentFilter.name).toEqual('FakeMyServiceTasks2');
}); });
}));
it('should emit the selected filter based on the filterParam input', async () => { it('should emit the selected filter based on the filterParam input', async () => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(component.filterSelected, 'emit'); spyOn(component.filterSelected, 'emit');
const filterParam = { id: '10' }; const filterParam = { id: '10' };
@@ -264,12 +240,12 @@ describe('ServiceTaskFiltersCloudComponent', () => {
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
expect(component.filterSelected.emit).toHaveBeenCalledWith(fakeGlobalServiceFilters[0]); expect(component.filterSelected.emit).toHaveBeenCalledWith(fakeGlobalServiceFilters[0]);
}); });
it('should filterClicked emit when a filter is clicked from the UI', async () => { it('should filterClicked emit when a filter is clicked from the UI', async () => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(component.filterClicked, 'emit'); spyOn(component.filterClicked, 'emit');
fixture.detectChanges(); fixture.detectChanges();
@@ -284,9 +260,7 @@ describe('ServiceTaskFiltersCloudComponent', () => {
expect(component.filterClicked.emit).toHaveBeenCalledWith(fakeGlobalServiceFilters[0]); expect(component.filterClicked.emit).toHaveBeenCalledWith(fakeGlobalServiceFilters[0]);
}); });
it('should reset the filter when the param is undefined', async(() => { it('should reset the filter when the param is undefined', async () => {
spyOn(serviceTaskFilterCloudService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(component, 'selectFilterAndEmit');
component.currentFilter = null; component.currentFilter = null;
const filterName = undefined; const filterName = undefined;
@@ -294,9 +268,10 @@ describe('ServiceTaskFiltersCloudComponent', () => {
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.detectChanges(); fixture.detectChanges();
expect(component.selectFilterAndEmit).toHaveBeenCalledWith(undefined); await fixture.whenStable();
expect(component.currentFilter).toEqual(undefined);
})); expect(component.currentFilter).toBe(fakeGlobalServiceFilters[0]);
});
it('should reload filters by appName on binding changes', () => { it('should reload filters by appName on binding changes', () => {
spyOn(component, 'getFilters').and.stub(); spyOn(component, 'getFilters').and.stub();
@@ -312,37 +287,35 @@ describe('ServiceTaskFiltersCloudComponent', () => {
component.filters = fakeGlobalServiceFilters; component.filters = fakeGlobalServiceFilters;
component.currentFilter = null; component.currentFilter = null;
const change = new SimpleChange(null, { name: fakeGlobalServiceFilters[1].name }, true); const name = fakeGlobalServiceFilters[1].name;
const change = new SimpleChange(null, { name }, true);
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.whenStable().then(() => { expect(component.currentFilter).toBeDefined('current filter not found');
expect(component.currentFilter.name).toEqual(fakeGlobalServiceFilters[1].name); expect(component.currentFilter.name).toEqual(name);
});
}); });
it('should change current filter when filterParam (key) changes', () => { it('should change current filter when filterParam (key) changes', () => {
component.filters = fakeGlobalServiceFilters; component.filters = fakeGlobalServiceFilters;
component.currentFilter = null; component.currentFilter = null;
const change = new SimpleChange(null, { key: fakeGlobalServiceFilters[2].key }, true); const key = fakeGlobalServiceFilters[2].key;
const change = new SimpleChange(null, { key }, true);
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.whenStable().then(() => { expect(component.currentFilter.key).toEqual(key);
expect(component.currentFilter.key).toEqual(fakeGlobalServiceFilters[2].key);
});
}); });
it('should change current filter when filterParam (index) changes', () => { it('should change current filter when filterParam (index) changes', () => {
component.filters = fakeGlobalServiceFilters; component.filters = fakeGlobalServiceFilters;
component.currentFilter = null; component.currentFilter = null;
const position = 1;
const change = new SimpleChange(null, { index: position }, true); const change = new SimpleChange(null, { index: 1 }, true);
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.whenStable().then(() => { expect(component.currentFilter.name).toEqual(fakeGlobalServiceFilters[1].name);
expect(component.currentFilter.name).toEqual(fakeGlobalServiceFilters[position].name);
});
}); });
it('should reload filters by app name on binding changes', () => { it('should reload filters by app name on binding changes', () => {
@@ -69,8 +69,13 @@ export class ServiceTaskFiltersCloudComponent extends BaseTaskFiltersCloudCompon
this.filters$.pipe(takeUntil(this.onDestroy$)).subscribe( this.filters$.pipe(takeUntil(this.onDestroy$)).subscribe(
(res: ServiceTaskFilterCloudModel[]) => { (res: ServiceTaskFilterCloudModel[]) => {
this.resetFilter(); this.resetFilter();
this.filters = Object.assign([], res); this.filters = res || [];
if (this.filterParam) {
this.selectFilterAndEmit(this.filterParam); this.selectFilterAndEmit(this.filterParam);
}
this.ensureFilterSelected();
this.success.emit(res); this.success.emit(res);
}, },
(err: any) => { (err: any) => {
@@ -88,15 +93,24 @@ export class ServiceTaskFiltersCloudComponent extends BaseTaskFiltersCloudCompon
(paramFilter.name && (paramFilter.name &&
(paramFilter.name.toLocaleLowerCase() === this.translationService.instant(filter.name).toLocaleLowerCase()) (paramFilter.name.toLocaleLowerCase() === this.translationService.instant(filter.name).toLocaleLowerCase())
)); ));
if (this.currentFilter) {
this.filterSelected.emit(this.currentFilter);
}
} }
} }
public selectFilterAndEmit(newParamFilter: FilterParamsModel) { public selectFilterAndEmit(newParamFilter: FilterParamsModel) {
if (newParamFilter) { if (newParamFilter) {
this.selectFilter(newParamFilter); this.selectFilter(newParamFilter);
this.filterSelected.emit(this.currentFilter); }
} else {
this.currentFilter = undefined; this.ensureFilterSelected();
}
private ensureFilterSelected() {
if (!this.currentFilter && this.filters.length > 0) {
this.currentFilter = this.filters[0];
} }
} }
@@ -16,9 +16,9 @@
*/ */
import { SimpleChange } from '@angular/core'; import { SimpleChange } from '@angular/core';
import { ComponentFixture, TestBed, async, fakeAsync, tick } from '@angular/core/testing'; import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { AppConfigService, setupTestBed } from '@alfresco/adf-core'; import { AppConfigService, setupTestBed } from '@alfresco/adf-core';
import { from, Observable, of } from 'rxjs'; import { of, throwError } from 'rxjs';
import { TASK_FILTERS_SERVICE_TOKEN } from '../../../services/cloud-token.service'; import { TASK_FILTERS_SERVICE_TOKEN } from '../../../services/cloud-token.service';
import { LocalPreferenceCloudService } from '../../../services/local-preference-cloud.service'; import { LocalPreferenceCloudService } from '../../../services/local-preference-cloud.service';
import { TaskFilterCloudService } from '../services/task-filter-cloud.service'; import { TaskFilterCloudService } from '../services/task-filter-cloud.service';
@@ -30,29 +30,13 @@ import { fakeGlobalFilter, taskNotifications } from '../mock/task-filters-cloud.
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
describe('TaskFiltersCloudComponent', () => { describe('TaskFiltersCloudComponent', () => {
let taskFilterService: TaskFilterCloudService; let taskFilterService: TaskFilterCloudService;
let appConfigService: AppConfigService; let appConfigService: AppConfigService;
const fakeGlobalFilterObservable =
new Observable(function (observer) {
observer.next(fakeGlobalFilter);
observer.complete();
});
const fakeGlobalFilterPromise = new Promise(function (resolve) {
resolve(fakeGlobalFilter);
});
const mockErrorFilterList = {
error: 'wrong request'
};
const mockErrorFilterPromise = Promise.reject(mockErrorFilterList);
let component: TaskFiltersCloudComponent; let component: TaskFiltersCloudComponent;
let fixture: ComponentFixture<TaskFiltersCloudComponent>; let fixture: ComponentFixture<TaskFiltersCloudComponent>;
let getTaskFilterCounterSpy; let getTaskFilterCounterSpy: jasmine.Spy;
let getTaskListFiltersSpy: jasmine.Spy;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -66,57 +50,66 @@ describe('TaskFiltersCloudComponent', () => {
}); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(TaskFiltersCloudComponent);
component = fixture.componentInstance;
taskFilterService = TestBed.inject(TaskFilterCloudService); taskFilterService = TestBed.inject(TaskFilterCloudService);
getTaskFilterCounterSpy = spyOn(taskFilterService, 'getTaskFilterCounter').and.returnValue(of(11)); getTaskFilterCounterSpy = spyOn(taskFilterService, 'getTaskFilterCounter').and.returnValue(of(11));
spyOn(taskFilterService, 'getTaskNotificationSubscription').and.returnValue(of(taskNotifications)); spyOn(taskFilterService, 'getTaskNotificationSubscription').and.returnValue(of(taskNotifications));
getTaskListFiltersSpy = spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(of(fakeGlobalFilter));
appConfigService = TestBed.inject(AppConfigService); appConfigService = TestBed.inject(AppConfigService);
fixture = TestBed.createComponent(TaskFiltersCloudComponent);
component = fixture.componentInstance;
}); });
it('should attach specific icon for each filter if hasIcon is true', async(() => { afterEach(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable); fixture.destroy();
});
it('should attach specific icon for each filter if hasIcon is true', async () => {
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.showIcons = true; component.showIcons = true;
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
expect(component.filters.length).toBe(3); expect(component.filters.length).toBe(3);
const filters = fixture.nativeElement.querySelectorAll('.adf-icon'); const filters = fixture.nativeElement.querySelectorAll('.adf-icon');
expect(filters.length).toBe(3); expect(filters.length).toBe(3);
expect(filters[0].innerText).toContain('adjust'); expect(filters[0].innerText).toContain('adjust');
expect(filters[1].innerText).toContain('done'); expect(filters[1].innerText).toContain('done');
expect(filters[2].innerText).toContain('inbox'); expect(filters[2].innerText).toContain('inbox');
}); });
}));
it('should not attach icons for each filter if hasIcon is false', (done) => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(from(fakeGlobalFilterPromise));
it('should not attach icons for each filter if hasIcon is false', async () => {
component.showIcons = false; component.showIcons = false;
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon')); const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon'));
expect(filters.length).toBe(0); expect(filters.length).toBe(0);
done();
});
}); });
it('should display the filters', async(() => { it('should display the filters', async () => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.showIcons = true; component.showIcons = true;
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const filters = fixture.debugElement.queryAll(By.css('.adf-task-filters__entry')); const filters = fixture.debugElement.queryAll(By.css('.adf-task-filters__entry'));
expect(component.filters.length).toBe(3); expect(component.filters.length).toBe(3);
expect(filters.length).toBe(3); expect(filters.length).toBe(3);
@@ -124,144 +117,123 @@ describe('TaskFiltersCloudComponent', () => {
expect(filters[1].nativeElement.innerText).toContain('FakeMyTasks1'); expect(filters[1].nativeElement.innerText).toContain('FakeMyTasks1');
expect(filters[2].nativeElement.innerText).toContain('FakeMyTasks2'); expect(filters[2].nativeElement.innerText).toContain('FakeMyTasks2');
}); });
}));
it('should emit an error with a bad response', (done) => { it('should emit an error with a bad response', (done) => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(from(mockErrorFilterPromise)); const mockErrorFilterList = {
error: 'wrong request'
};
getTaskListFiltersSpy.and.returnValue(throwError(mockErrorFilterList));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change });
component.error.subscribe((err) => { component.error.subscribe((err) => {
expect(err).toBeDefined(); expect(err).toBeDefined();
done(); done();
}); });
component.ngOnChanges({ 'appName': change });
}); });
it('should return the filter task list', (done) => { it('should return the filter task list', async () => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(from(fakeGlobalFilterPromise));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.filters).toBeDefined(); expect(component.filters).toBeDefined();
expect(component.filters.length).toEqual(3); expect(component.filters.length).toEqual(3);
done();
});
}); });
it('should return the filter task list, filtered By Name', (done) => { it('should return the filter task list, filtered By Name', async () => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(from(fakeGlobalFilterPromise));
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.filters).toBeDefined(); expect(component.filters).toBeDefined();
expect(component.filters[0].name).toEqual('FakeInvolvedTasks'); expect(component.filters[0].name).toEqual('FakeInvolvedTasks');
expect(component.filters[1].name).toEqual('FakeMyTasks1'); expect(component.filters[1].name).toEqual('FakeMyTasks1');
expect(component.filters[2].name).toEqual('FakeMyTasks2'); expect(component.filters[2].name).toEqual('FakeMyTasks2');
done();
});
}); });
it('should select the first filter as default', async(() => { it('should select the first cloud task filter as default', async () => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
await fixture.whenStable();
component.success.subscribe((res) => { expect(component.filters.length).toBe(fakeGlobalFilter.length);
expect(res).toBeDefined(); expect(component.currentFilter).toBeDefined('current filter not found');
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeInvolvedTasks'); expect(component.currentFilter.name).toEqual('FakeInvolvedTasks');
}); });
})); it('should select the task filter based on the input by name param', async () => {
it('should select the task filter based on the input by name param', async(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { name: 'FakeMyTasks1' }; component.filterParam = { name: 'FakeMyTasks1' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
await fixture.whenStable();
component.success.subscribe((res) => {
expect(res).toBeDefined();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeMyTasks1'); expect(component.currentFilter.name).toEqual('FakeMyTasks1');
}); });
})); it('should select the default task filter if filter input does not exist', async () => {
it('should select the default task filter if filter input does not exist', async(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { name: 'UnexistableFilter' }; component.filterParam = { name: 'UnexistableFilter' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined();
expect(component.currentFilter).toBeDefined('current filter not found');
expect(component.currentFilter.name).toEqual('FakeInvolvedTasks'); expect(component.currentFilter.name).toEqual('FakeInvolvedTasks');
}); });
})); it('should select the task filter based on the input by index param', async () => {
it('should select the task filter based on the input by index param', async(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { index: 2 }; component.filterParam = { index: 2 };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeMyTasks2'); expect(component.currentFilter.name).toEqual('FakeMyTasks2');
}); });
})); it('should select the task filter based on the input by id param', async () => {
it('should select the task filter based on the input by id param', async(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.filterParam = { id: '12' }; component.filterParam = { id: '12' };
const appName = 'my-app-1'; const appName = 'my-app-1';
const change = new SimpleChange(null, appName, true); const change = new SimpleChange(null, appName, true);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
component.success.subscribe((res) => { fixture.detectChanges();
expect(res).toBeDefined(); await fixture.whenStable();
expect(component.currentFilter).toBeDefined(); expect(component.currentFilter).toBeDefined();
expect(component.currentFilter.name).toEqual('FakeMyTasks2'); expect(component.currentFilter.name).toEqual('FakeMyTasks2');
}); });
})); it('should emit the selected filter based on the filterParam input', async () => {
it('should emit the selected filter based on the filterParam input', async(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(component.filterSelected, 'emit'); spyOn(component.filterSelected, 'emit');
const filterParam = { id: '10' }; const filterParam = { id: '10' };
@@ -269,13 +241,14 @@ describe('TaskFiltersCloudComponent', () => {
component.filterParam = filterParam; component.filterParam = filterParam;
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
expect(component.filterSelected.emit).toHaveBeenCalledWith(fakeGlobalFilter[0]); expect(component.filterSelected.emit).toHaveBeenCalledWith(fakeGlobalFilter[0]);
})); });
it('should filterClicked emit when a filter is clicked from the UI', async () => { it('should filterClicked emit when a filter is clicked from the UI', async () => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(component.filterClicked, 'emit'); spyOn(component.filterClicked, 'emit');
fixture.detectChanges(); fixture.detectChanges();
@@ -290,9 +263,7 @@ describe('TaskFiltersCloudComponent', () => {
expect(component.filterClicked.emit).toHaveBeenCalledWith(fakeGlobalFilter[0]); expect(component.filterClicked.emit).toHaveBeenCalledWith(fakeGlobalFilter[0]);
}); });
it('should reset the filter when the param is undefined', async(() => { it('should reset the filter when the param is undefined', async () => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(component, 'selectFilterAndEmit');
component.currentFilter = null; component.currentFilter = null;
const filterName = undefined; const filterName = undefined;
@@ -300,9 +271,10 @@ describe('TaskFiltersCloudComponent', () => {
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.detectChanges(); fixture.detectChanges();
expect(component.selectFilterAndEmit).toHaveBeenCalledWith(undefined); await fixture.whenStable();
expect(component.currentFilter).toEqual(undefined);
})); expect(component.currentFilter).toEqual(fakeGlobalFilter[0]);
});
it('should reload filters by appName on binding changes', () => { it('should reload filters by appName on binding changes', () => {
spyOn(component, 'getFilters').and.stub(); spyOn(component, 'getFilters').and.stub();
@@ -333,10 +305,8 @@ describe('TaskFiltersCloudComponent', () => {
const change = new SimpleChange(null, { key: fakeGlobalFilter[2].key }, true); const change = new SimpleChange(null, { key: fakeGlobalFilter[2].key }, true);
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.whenStable().then(() => {
expect(component.currentFilter.key).toEqual(fakeGlobalFilter[2].key); expect(component.currentFilter.key).toEqual(fakeGlobalFilter[2].key);
}); });
});
it('should change current filter when filterParam (index) changes', () => { it('should change current filter when filterParam (index) changes', () => {
component.filters = fakeGlobalFilter; component.filters = fakeGlobalFilter;
@@ -346,10 +316,8 @@ describe('TaskFiltersCloudComponent', () => {
const change = new SimpleChange(null, { index: position }, true); const change = new SimpleChange(null, { index: position }, true);
component.ngOnChanges({ 'filterParam': change }); component.ngOnChanges({ 'filterParam': change });
fixture.whenStable().then(() => {
expect(component.currentFilter.name).toEqual(fakeGlobalFilter[position].name); expect(component.currentFilter.name).toEqual(fakeGlobalFilter[position].name);
}); });
});
it('should reload filters by app name on binding changes', () => { it('should reload filters by app name on binding changes', () => {
spyOn(component, 'getFilters').and.stub(); spyOn(component, 'getFilters').and.stub();
@@ -370,23 +338,25 @@ describe('TaskFiltersCloudComponent', () => {
expect(component.currentFilter).toBe(fakeGlobalFilter[0]); expect(component.currentFilter).toBe(fakeGlobalFilter[0]);
}); });
it('should display filter counter if property set to true', async(() => { it('should display filter counter if property set to true', async () => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
const change = new SimpleChange(undefined, 'my-app-1', true); const change = new SimpleChange(undefined, 'my-app-1', true);
component.ngOnChanges({ 'appName': change }); component.ngOnChanges({ 'appName': change });
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
component.showIcons = true; component.showIcons = true;
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const filterCounters = fixture.debugElement.queryAll(By.css('.adf-filter-action-button__counter')); const filterCounters = fixture.debugElement.queryAll(By.css('.adf-filter-action-button__counter'));
expect(component.filters.length).toBe(3); expect(component.filters.length).toBe(3);
expect(filterCounters.length).toBe(1); expect(filterCounters.length).toBe(1);
expect(filterCounters[0].nativeElement.innerText).toContain('11'); expect(filterCounters[0].nativeElement.innerText).toContain('11');
}); });
}));
it('should update filter counter when notification received', fakeAsync(() => { it('should update filter counter when notification received', fakeAsync(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(appConfigService, 'get').and.returnValue(true); spyOn(appConfigService, 'get').and.returnValue(true);
component.appName = 'my-app-1'; component.appName = 'my-app-1';
component.ngOnInit(); component.ngOnInit();
@@ -403,7 +373,6 @@ describe('TaskFiltersCloudComponent', () => {
})); }));
it('should not update filter counter when notifications are disabled from app.config.json', fakeAsync(() => { it('should not update filter counter when notifications are disabled from app.config.json', fakeAsync(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(appConfigService, 'get').and.returnValue(false); spyOn(appConfigService, 'get').and.returnValue(false);
component.appName = 'my-app-1'; component.appName = 'my-app-1';
component.ngOnInit(); component.ngOnInit();
@@ -418,7 +387,6 @@ describe('TaskFiltersCloudComponent', () => {
})); }));
it('should reset filter counter notification when filter is selected', fakeAsync(() => { it('should reset filter counter notification when filter is selected', fakeAsync(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
spyOn(appConfigService, 'get').and.returnValue(true); spyOn(appConfigService, 'get').and.returnValue(true);
let change = new SimpleChange(undefined, 'my-app-1', true); let change = new SimpleChange(undefined, 'my-app-1', true);
component.appName = 'my-app-1'; component.appName = 'my-app-1';
@@ -446,7 +414,6 @@ describe('TaskFiltersCloudComponent', () => {
})); }));
it('should update filter counter when filter is selected', fakeAsync(() => { it('should update filter counter when filter is selected', fakeAsync(() => {
spyOn(taskFilterService, 'getTaskListFilters').and.returnValue(fakeGlobalFilterObservable);
component.appName = 'my-app-1'; component.appName = 'my-app-1';
component.ngOnInit(); component.ngOnInit();
tick(5000); tick(5000);
@@ -79,8 +79,16 @@ export class TaskFiltersCloudComponent extends BaseTaskFiltersCloudComponent imp
this.filters$.pipe(takeUntil(this.onDestroy$)).subscribe( this.filters$.pipe(takeUntil(this.onDestroy$)).subscribe(
(res: TaskFilterCloudModel[]) => { (res: TaskFilterCloudModel[]) => {
this.resetFilter(); this.resetFilter();
this.filters = Object.assign([], res); this.filters = res || [];
if (this.filterParam) {
this.selectFilterAndEmit(this.filterParam); this.selectFilterAndEmit(this.filterParam);
}
if (!this.currentFilter && this.filters.length > 0) {
this.currentFilter = this.filters[0];
}
this.updateFilterCounters(); this.updateFilterCounters();
this.success.emit(res); this.success.emit(res);
}, },
@@ -145,12 +153,19 @@ export class TaskFiltersCloudComponent extends BaseTaskFiltersCloudComponent imp
public selectFilterAndEmit(newParamFilter: FilterParamsModel) { public selectFilterAndEmit(newParamFilter: FilterParamsModel) {
if (newParamFilter) { if (newParamFilter) {
this.selectFilter(newParamFilter); this.selectFilter(newParamFilter);
if (this.currentFilter) { if (this.currentFilter) {
this.resetFilterCounter(this.currentFilter.key); this.resetFilterCounter(this.currentFilter.key);
this.filterSelected.emit(this.currentFilter); this.filterSelected.emit(this.currentFilter);
} }
} else { }
this.currentFilter = undefined;
this.ensureFilterSelected();
}
private ensureFilterSelected() {
if (!this.currentFilter && this.filters.length > 0) {
this.currentFilter = this.filters[0];
} }
} }
@@ -18,8 +18,8 @@
import { assignedTaskDetailsCloudMock } from '../../task-header/mocks/task-details-cloud.mock'; import { assignedTaskDetailsCloudMock } from '../../task-header/mocks/task-details-cloud.mock';
import { TaskFilterCloudModel, ServiceTaskFilterCloudModel } from '../models/filter-cloud.model'; import { TaskFilterCloudModel, ServiceTaskFilterCloudModel } from '../models/filter-cloud.model';
export const fakeGlobalFilter = [ export const fakeGlobalFilter: any[] = [
new TaskFilterCloudModel({ {
name: 'FakeInvolvedTasks', name: 'FakeInvolvedTasks',
key: 'fake-involved-tasks', key: 'fake-involved-tasks',
icon: 'adjust', icon: 'adjust',
@@ -27,8 +27,8 @@ export const fakeGlobalFilter = [
status: 'ASSIGNED', status: 'ASSIGNED',
assignee: 'AssignedTaskUser', assignee: 'AssignedTaskUser',
showCounter: true showCounter: true
}), },
new TaskFilterCloudModel({ {
name: 'FakeMyTasks1', name: 'FakeMyTasks1',
key: 'fake-my-tast1', key: 'fake-my-tast1',
icon: 'done', icon: 'done',
@@ -36,18 +36,18 @@ export const fakeGlobalFilter = [
status: 'open', status: 'open',
assignee: 'fake-assignee', assignee: 'fake-assignee',
showCounter: false showCounter: false
}), },
new TaskFilterCloudModel({ {
name: 'FakeMyTasks2', name: 'FakeMyTasks2',
key: 'fake-my-tast2', key: 'fake-my-tast2',
icon: 'inbox', icon: 'inbox',
id: '12', id: '12',
status: 'open', status: 'open',
assignee: 'fake-assignee' assignee: 'fake-assignee'
}) }
]; ];
export const fakeGlobalServiceFilters = [ export const fakeGlobalServiceFilters: ServiceTaskFilterCloudModel[] = [
{ {
name: 'FakeServiceTasks', name: 'FakeServiceTasks',
key: 'fake-involved-tasks', key: 'fake-involved-tasks',
@@ -49,7 +49,7 @@ describe('TaskHeaderCloudComponent', () => {
const mockCandidateUsers = ['mockuser1', 'mockuser2', 'mockuser3']; const mockCandidateUsers = ['mockuser1', 'mockuser2', 'mockuser3'];
const mockCandidateGroups = ['mockgroup1', 'mockgroup2', 'mockgroup3']; const mockCandidateGroups = ['mockgroup1', 'mockgroup2', 'mockgroup3'];
const mock = { const mock: any = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => Promise.resolve({}) callCustomApi: () => Promise.resolve({})
}, },
@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
export const taskClaimCloudMock = { export const taskClaimCloudMock: any = {
'entry': { 'entry': {
'appName': 'simple-app', 'appName': 'simple-app',
'appVersion': '', 'appVersion': '',
@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
export const taskCompleteCloudMock = { export const taskCompleteCloudMock: any = {
'entry': { 'entry': {
'appName': 'simple-app', 'appName': 'simple-app',
'appVersion': '', 'appVersion': '',
@@ -26,7 +26,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
let service: ServiceTaskListCloudService; let service: ServiceTaskListCloudService;
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
function returnCallQueryParameters() { function returnCallQueryParameters(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => { callCustomApi: (_queryUrl, _operation, _context, queryParams) => {
@@ -40,7 +40,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
}; };
} }
function returnCallUrl() { function returnCallUrl(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi: (queryUrl) => { callCustomApi: (queryUrl) => {
@@ -27,7 +27,7 @@ describe('TaskListCloudService', () => {
let service: TaskListCloudService; let service: TaskListCloudService;
let alfrescoApiService: AlfrescoApiService; let alfrescoApiService: AlfrescoApiService;
function returnCallQueryParameters() { function returnCallQueryParameters(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi : (_queryUrl, _operation, _context, queryParams) => { callCustomApi : (_queryUrl, _operation, _context, queryParams) => {
@@ -41,7 +41,7 @@ describe('TaskListCloudService', () => {
}; };
} }
function returnCallUrl() { function returnCallUrl(): any {
return { return {
oauth2Auth: { oauth2Auth: {
callCustomApi : (queryUrl) => { callCustomApi : (queryUrl) => {
@@ -25,7 +25,7 @@ import { setupTestBed, AuthenticationService, SitesService, AlfrescoApiService,
import { AttachFileWidgetDialogComponentData } from './attach-file-widget-dialog-component.interface'; import { AttachFileWidgetDialogComponentData } from './attach-file-widget-dialog-component.interface';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { Node, SiteEntry, NodeEntry } from '@alfresco/js-api'; import { Node, SiteEntry, NodeEntry, SitePaging } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
describe('AttachFileWidgetDialogComponent', () => { describe('AttachFileWidgetDialogComponent', () => {
@@ -76,10 +76,10 @@ describe('AttachFileWidgetDialogComponent', () => {
spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } })); spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } }));
spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test')); spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test'));
spyOn(nodeService, 'getNode').and.returnValue(of({ id: 'fake-node', path: { elements: [{ nodeType: 'st:site', name: 'fake-site'}] } })); spyOn(nodeService, 'getNode').and.returnValue(of(new Node({ id: 'fake-node', path: { elements: [{ nodeType: 'st:site', name: 'fake-site'}] } })));
spyOn(siteService, 'getSite').and.returnValue(of(fakeSite)); spyOn(siteService, 'getSite').and.returnValue(of(fakeSite));
spyOn(siteService, 'getSites').and.returnValue(of({ list: { entries: [] } })); spyOn(siteService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
spyOn(widget, 'isLoggedIn').and.callFake(() => { spyOn(widget, 'isLoggedIn').and.callFake(() => {
return isLogged; return isLogged;
}); });
@@ -203,7 +203,7 @@ describe('AttachFileWidgetDialogComponent', () => {
it('should close the dialog immediately if user already loggedIn', () => { it('should close the dialog immediately if user already loggedIn', () => {
isLogged = true; isLogged = true;
fixture.detectChanges(); fixture.detectChanges();
spyOn(apiService, 'getInstance').and.returnValue({ isLoggedIn: () => true }); spyOn(apiService, 'getInstance').and.returnValue({ isLoggedIn: () => true } as any);
widget.updateExternalHost(); widget.updateExternalHost();
expect(matDialogRef.close).toHaveBeenCalled(); expect(matDialogRef.close).toHaveBeenCalled();
}); });
@@ -45,7 +45,7 @@ describe('AttachFileWidgetDialogService', () => {
componentInstance: { componentInstance: {
error: new Subject<any>() error: new Subject<any>()
} }
}); } as any);
}); });
it('should be able to open the dialog when node has permission', () => { it('should be able to open the dialog when node has permission', () => {
@@ -110,7 +110,7 @@ const fakeMinimalNode: Node = <Node> {
} }
}; };
const fakePngUpload = { const fakePngUpload: any = {
'id': 1166, 'id': 1166,
'name': 'fake-png.png', 'name': 'fake-png.png',
'created': '2017-07-25T17:17:37.099Z', 'created': '2017-07-25T17:17:37.099Z',
@@ -125,7 +125,7 @@ const fakePngUpload = {
'thumbnailStatus': 'queued' 'thumbnailStatus': 'queued'
}; };
const fakePngAnswer = { const fakePngAnswer: any = {
'id': 1155, 'id': 1155,
'name': 'a_png_file.png', 'name': 'a_png_file.png',
'created': '2017-07-25T17:17:37.099Z', 'created': '2017-07-25T17:17:37.099Z',
@@ -21,7 +21,8 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Observable, of, throwError } from 'rxjs'; import { Observable, of, throwError } from 'rxjs';
import { FormFieldModel, FormFieldTypes, FormModel, FormOutcomeEvent, FormOutcomeModel, import { FormFieldModel, FormFieldTypes, FormModel, FormOutcomeEvent, FormOutcomeModel,
FormService, WidgetVisibilityService, NodeService, ContainerModel, fakeForm, FormService, WidgetVisibilityService, NodeService, ContainerModel, fakeForm,
setupTestBed } from '@alfresco/adf-core'; setupTestBed,
NodeMetadata } from '@alfresco/adf-core';
import { FormComponent } from './form.component'; import { FormComponent } from './form.component';
import { ProcessFormRenderingService } from './process-form-rendering.service'; import { ProcessFormRenderingService } from './process-form-rendering.service';
import { ProcessTestingModule } from '../testing/process.testing.module'; import { ProcessTestingModule } from '../testing/process.testing.module';
@@ -235,7 +236,7 @@ describe('FormComponent', () => {
}); });
}); });
spyOn(visibilityService, 'getTaskProcessVariable').and.returnValue(of({})); spyOn(visibilityService, 'getTaskProcessVariable').and.returnValue(of(null));
spyOn(formService, 'getTask').and.callFake((currentTaskId) => { spyOn(formService, 'getTask').and.callFake((currentTaskId) => {
return new Observable((observer) => { return new Observable((observer) => {
observer.next({ taskId: currentTaskId, processDefinitionId: '10201' }); observer.next({ taskId: currentTaskId, processDefinitionId: '10201' });
@@ -258,7 +259,7 @@ describe('FormComponent', () => {
}); });
}); });
spyOn(visibilityService, 'getTaskProcessVariable').and.returnValue(of({})); spyOn(visibilityService, 'getTaskProcessVariable').and.returnValue(of(null));
spyOn(formService, 'getTask').and.callFake((currentTaskId) => { spyOn(formService, 'getTask').and.callFake((currentTaskId) => {
return new Observable((observer) => { return new Observable((observer) => {
observer.next({ taskId: currentTaskId, processDefinitionId: 'null' }); observer.next({ taskId: currentTaskId, processDefinitionId: 'null' });
@@ -758,10 +759,7 @@ describe('FormComponent', () => {
it('should load form for ecm node', () => { it('should load form for ecm node', () => {
const metadata = {}; const metadata = {};
spyOn(nodeService, 'getNodeMetadata').and.returnValue( spyOn(nodeService, 'getNodeMetadata').and.returnValue(
new Observable((observer) => { of(new NodeMetadata(metadata, null))
observer.next({ metadata: metadata });
observer.complete();
})
); );
spyOn(formComponent, 'loadFormFromActiviti').and.stub(); spyOn(formComponent, 'loadFormFromActiviti').and.stub();
@@ -15,8 +15,10 @@
* limitations under the License. * limitations under the License.
*/ */
import { CommentModel } from '@alfresco/adf-core';
export let mockProcessInstanceComments = [ export let mockProcessInstanceComments = [
{ message: 'Test1', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} }, new CommentModel({ message: 'Test1', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} }),
{ message: 'Test2', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} }, new CommentModel({ message: 'Test2', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} }),
{ message: 'Test3', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} } new CommentModel({ message: 'Test3', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} })
]; ];
@@ -15,7 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
export let fakeProcessInstance = { import { ProcessListModel } from '../../process-list/models/process-list.model';
export let fakeProcessInstance = new ProcessListModel({
size: 2, size: 2,
total: 2, total: 2,
start: 0, start: 0,
@@ -81,7 +83,7 @@ export let fakeProcessInstance = {
] ]
} }
] ]
}; });
export let fakeProcessInstancesWithNoName = { export let fakeProcessInstancesWithNoName = {
size: 2, size: 2,
@@ -123,12 +125,12 @@ export let fakeProcessInstancesWithNoName = {
] ]
}; };
export let fakeProcessInstancesEmpty = { export let fakeProcessInstancesEmpty = new ProcessListModel({
size: 0, size: 0,
total: 0, total: 0,
start: 0, start: 0,
data: [] data: []
}; });
export let fakeProcessCustomSchema = [ export let fakeProcessCustomSchema = [
{ {
@@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { UserRepresentation } from '@alfresco/js-api';
import { TaskDetailsModel } from '../../task-list/models/task-details.model'; import { TaskDetailsModel } from '../../task-list/models/task-details.model';
export let standaloneTaskWithForm = new TaskDetailsModel({ export let standaloneTaskWithForm = new TaskDetailsModel({
@@ -938,7 +939,7 @@ export const involvedGroupTaskForm = {
managerOfCandidateGroup: false managerOfCandidateGroup: false
}; };
export const fakeUser = { export const fakeUser = new UserRepresentation({
id: 1001, id: 1001,
email: 'fake-email@gmail.com', email: 'fake-email@gmail.com',
firstName: 'fake', firstName: 'fake',
@@ -972,4 +973,4 @@ export const fakeUser = {
apps: [], apps: [],
tenantPictureId: null, tenantPictureId: null,
tenantName: 'abc' tenantName: 'abc'
}; });
@@ -15,17 +15,15 @@
* limitations under the License. * limitations under the License.
*/ */
import { AppDefinitionRepresentationModel, FilterRepresentationModel } from '../../task-list/models/filter.model'; import { FilterRepresentationModel } from '../../task-list/models/filter.model';
export let fakeFiltersResponse = { export let fakeFiltersResponse: any = {
size: 2, total: 2, start: 0, size: 2, total: 2, start: 0,
data: [ data: [
new AppDefinitionRepresentationModel(
{ {
id: 1, name: 'FakeInvolvedTasks', recent: false, icon: 'glyphicon-align-left', id: 1, name: 'FakeInvolvedTasks', recent: false, icon: 'glyphicon-align-left',
filter: { sort: 'created-desc', name: '', state: 'open', assignment: 'fake-involved' } filter: { sort: 'created-desc', name: '', state: 'open', assignment: 'fake-involved' }
} },
),
{ {
id: 2, name: 'FakeMyTasks', recent: false, icon: 'glyphicon-align-left', id: 2, name: 'FakeMyTasks', recent: false, icon: 'glyphicon-align-left',
filter: { sort: 'created-desc', name: '', state: 'open', assignment: 'fake-assignee' } filter: { sort: 'created-desc', name: '', state: 'open', assignment: 'fake-assignee' }
@@ -15,7 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
export const fakeGlobalTask = { import { TaskListModel } from '../../task-list/models/task-list.model';
export const fakeGlobalTask = new TaskListModel({
size: 2, size: 2,
start: 0, start: 0,
total: 2, total: 2,
@@ -74,7 +76,7 @@ export const fakeGlobalTask = {
endDate: null endDate: null
} }
] ]
}; });
export let fakeCustomSchema = [ export let fakeCustomSchema = [
{ {
@@ -124,7 +126,7 @@ export let fakeEmptyTask = {
data: [] data: []
}; };
export const paginatedTask = { export const paginatedTask = new TaskListModel({
'size': 5, 'size': 5,
'total': 9, 'total': 9,
'start': 0, 'start': 0,
@@ -284,4 +286,4 @@ export const paginatedTask = {
'memberOfCandidateUsers': false, 'memberOfCandidateUsers': false,
'managerOfCandidateGroup': false 'managerOfCandidateGroup': false
}] }]
}; });
@@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { TaskListModel } from '../../task-list/models/task-list.model';
import { fakeAppFilter } from './task-filters.mock'; import { fakeAppFilter } from './task-filters.mock';
export let fakeApps = { export let fakeApps = {
@@ -35,7 +36,7 @@ export let fakeUser1 = { id: 1, email: 'fake-email@dom.com', firstName: 'firstNa
export let fakeUser2 = { id: 1001, email: 'some-one@somegroup.com', firstName: 'some', lastName: 'one' }; export let fakeUser2 = { id: 1001, email: 'some-one@somegroup.com', firstName: 'some', lastName: 'one' };
export let fakeTaskList = { export let fakeTaskList = new TaskListModel({
size: 1, total: 1, start: 0, size: 1, total: 1, start: 0,
data: [ data: [
{ {
@@ -44,7 +45,7 @@ export let fakeTaskList = {
created: '2016-07-15T11:19:17.440+0000' created: '2016-07-15T11:19:17.440+0000'
} }
] ]
}; });
export let fakeTaskListDifferentProcessDefinitionKey = { export let fakeTaskListDifferentProcessDefinitionKey = {
size: 2, total: 1, start: 0, size: 2, total: 1, start: 0,
@@ -188,16 +189,16 @@ export let fakeTaskCompleted2 = {
endDate: '2016-11-03T15:25:42.749+0000' endDate: '2016-11-03T15:25:42.749+0000'
}; };
export let fakeOpenTaskList = { export let fakeOpenTaskList = new TaskListModel({
size: 2, size: 2,
total: 2, total: 2,
start: 0, start: 0,
data: [fakeTaskOpen1, fakeTaskOpen2] data: [fakeTaskOpen1, fakeTaskOpen2]
}; });
export let fakeCompletedTaskList = { export let fakeCompletedTaskList = new TaskListModel({
size: 2, size: 2,
total: 2, total: 2,
start: 0, start: 0,
data: [fakeTaskCompleted1, fakeTaskCompleted2] data: [fakeTaskCompleted1, fakeTaskCompleted2]
}; });

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