[ACS-7688] Reduce the usage of LogService and TranslateModule (tests) (#9567)

This commit is contained in:
Denys Vuika
2024-04-19 12:14:33 -04:00
committed by GitHub
parent caa2166151
commit 54c3e12ad8
275 changed files with 4089 additions and 5550 deletions
@@ -1 +1 @@
<adf-host-settings (cancel)="onCancel()" (success)="onSuccess()" (error)="onError($event)"></adf-host-settings> <adf-host-settings (cancel)="onCancel()" (success)="onSuccess()"></adf-host-settings>
@@ -16,7 +16,6 @@
*/ */
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { LogService } from '@alfresco/adf-core';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
@Component({ @Component({
@@ -24,14 +23,7 @@ import { Router } from '@angular/router';
templateUrl: './settings.component.html' templateUrl: './settings.component.html'
}) })
export class SettingsComponent { export class SettingsComponent {
constructor(private router: Router) {}
constructor(private router: Router,
public logService: LogService) {
}
onError(error: string) {
this.logService.log(error);
}
onCancel() { onCancel() {
this.router.navigate(['/login']); this.router.navigate(['/login']);
@@ -16,9 +16,7 @@
*/ */
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { AppConfigService, LogService, import { AppConfigService, FormFieldOption, FormService, FormValues, FormModel, FormOutcomeModel, FormOutcomeEvent } from '@alfresco/adf-core';
FormFieldOption, FormService, FormValues, FormModel,
FormOutcomeModel, FormOutcomeEvent } from '@alfresco/adf-core';
import { Observable, Subject } from 'rxjs'; import { Observable, Subject } from 'rxjs';
interface ProcessServiceData { interface ProcessServiceData {
@@ -37,13 +35,11 @@ interface ProcessServiceData {
// //
@Injectable() @Injectable()
export class InMemoryFormService extends FormService { export class InMemoryFormService extends FormService {
private data: ProcessServiceData; private data: ProcessServiceData;
executeOutcome = new Subject<FormOutcomeEvent>(); executeOutcome = new Subject<FormOutcomeEvent>();
constructor(appConfig: AppConfigService, constructor(appConfig: AppConfigService) {
protected logService: LogService) {
super(); super();
this.data = appConfig.get<ProcessServiceData>('activiti'); this.data = appConfig.get<ProcessServiceData>('activiti');
} }
@@ -53,14 +49,10 @@ export class InMemoryFormService extends FormService {
// Uncomment this to use original call // Uncomment this to use original call
// return super.getRestFieldValues(taskId, fieldId); // return super.getRestFieldValues(taskId, fieldId);
this.logService.log(`getRestFieldValues: ${taskId} => ${field}`);
return new Observable<FormFieldOption[]>((observer) => { return new Observable<FormFieldOption[]>((observer) => {
const currentField = this.data.rest.fields.find( const currentField = this.data.rest.fields.find((f) => f.taskId === taskId && f.fieldId === field);
(f) => f.taskId === taskId && f.fieldId === field
);
if (currentField) { if (currentField) {
const values: FormFieldOption[] = currentField.values || []; const values: FormFieldOption[] = currentField.values || [];
this.logService.log(values);
observer.next(values); observer.next(values);
} }
}); });
@@ -75,7 +67,7 @@ export class InMemoryFormService extends FormService {
delete flattenForm.formDefinition; delete flattenForm.formDefinition;
const formValues: FormValues = {}; const formValues: FormValues = {};
(data || []).forEach(variable => { (data || []).forEach((variable) => {
formValues[variable.name] = variable.value; formValues[variable.name] = variable.value;
}); });
@@ -99,13 +91,11 @@ export class InMemoryFormService extends FormService {
// Uncomment this to use original call // Uncomment this to use original call
// return super.getRestFieldValuesByProcessId(processDefinitionId, fieldId); // return super.getRestFieldValuesByProcessId(processDefinitionId, fieldId);
this.logService.log(`getRestFieldValuesByProcessId: ${processDefinitionId} => ${fieldId}`);
return new Observable<FormFieldOption[]>((observer) => { return new Observable<FormFieldOption[]>((observer) => {
const field = this.data.rest.fields.find( const field = this.data.rest.fields.find(
(currentField) => currentField.processId === processDefinitionId && currentField.fieldId === fieldId (currentField) => currentField.processId === processDefinitionId && currentField.fieldId === fieldId
); );
const values: FormFieldOption[] = field.values || []; const values: FormFieldOption[] = field.values || [];
this.logService.log(values);
observer.next(values); observer.next(values);
}); });
} }
@@ -43,6 +43,10 @@ Displays users involved with a specified task
| readOnly | `boolean` | false | Should the data be read-only? | | readOnly | `boolean` | false | Should the data be read-only? |
| taskId | `string` | "" | The numeric ID of the task. | | taskId | `string` | "" | The numeric ID of the task. |
### Events
- `error`: Emitted when an error occurs.
## Details ## Details
### How to customize the people component behavior ### How to customize the people component behavior
@@ -16,7 +16,7 @@
*/ */
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core'; import { AlfrescoApiService, AppConfigService } from '@alfresco/adf-core';
import { from, Observable, of, zip } from 'rxjs'; import { from, Observable, of, zip } from 'rxjs';
import { catchError, map } from 'rxjs/operators'; import { catchError, map } from 'rxjs/operators';
import { AspectEntry, AspectPaging, AspectsApi } from '@alfresco/js-api'; import { AspectEntry, AspectPaging, AspectsApi } from '@alfresco/js-api';
@@ -25,17 +25,13 @@ import { AspectEntry, AspectPaging, AspectsApi } from '@alfresco/js-api';
providedIn: 'root' providedIn: 'root'
}) })
export class AspectListService { export class AspectListService {
private _aspectsApi: AspectsApi; private _aspectsApi: AspectsApi;
get aspectsApi(): AspectsApi { get aspectsApi(): AspectsApi {
this._aspectsApi = this._aspectsApi ?? new AspectsApi(this.alfrescoApiService.getInstance()); this._aspectsApi = this._aspectsApi ?? new AspectsApi(this.alfrescoApiService.getInstance());
return this._aspectsApi; return this._aspectsApi;
} }
constructor(private alfrescoApiService: AlfrescoApiService, constructor(private alfrescoApiService: AlfrescoApiService, private appConfigService: AppConfigService) {}
private appConfigService: AppConfigService,
private logService: LogService) {
}
getAspects(): Observable<AspectEntry[]> { getAspects(): Observable<AspectEntry[]> {
const visibleAspectList = this.getVisibleAspects(); const visibleAspectList = this.getVisibleAspects();
@@ -52,13 +48,10 @@ export class AspectListService {
where, where,
include: ['properties'] include: ['properties']
}; };
return from(this.aspectsApi.listAspects(opts))
.pipe( return from(this.aspectsApi.listAspects(opts)).pipe(
map((result: AspectPaging) => this.filterAspectByConfig(whiteList, result?.list?.entries)), map((result: AspectPaging) => this.filterAspectByConfig(whiteList, result?.list?.entries)),
catchError((error) => { catchError(() => of([]))
this.logService.error(error);
return of([]);
})
); );
} }
@@ -68,13 +61,9 @@ export class AspectListService {
where, where,
include: ['properties'] include: ['properties']
}; };
return from(this.aspectsApi.listAspects(opts)) return from(this.aspectsApi.listAspects(opts)).pipe(
.pipe(
map((result: AspectPaging) => this.filterAspectByConfig(whiteList, result?.list?.entries)), map((result: AspectPaging) => this.filterAspectByConfig(whiteList, result?.list?.entries)),
catchError((error) => { catchError(() => of([]))
this.logService.error(error);
return of([]);
})
); );
} }
@@ -96,5 +85,4 @@ export class AspectListService {
} }
return visibleAspectList; return visibleAspectList;
} }
} }
@@ -17,13 +17,12 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { ContentApi, RenditionEntry, RenditionPaging, RenditionsApi, VersionsApi } from '@alfresco/js-api'; import { ContentApi, RenditionEntry, RenditionPaging, RenditionsApi, VersionsApi } from '@alfresco/js-api';
import { AlfrescoApiService , LogService, Track,TranslationService, ViewUtilService } from '@alfresco/adf-core'; import { AlfrescoApiService, Track, TranslationService, ViewUtilService } from '@alfresco/adf-core';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class RenditionService { export class RenditionService {
static TARGET = '_new'; static TARGET = '_new';
/** /**
@@ -53,7 +52,6 @@ export class RenditionService {
*/ */
private TRY_TIMEOUT: number = 10000; private TRY_TIMEOUT: number = 10000;
_renditionsApi: RenditionsApi; _renditionsApi: RenditionsApi;
get renditionsApi(): RenditionsApi { get renditionsApi(): RenditionsApi {
this._renditionsApi = this._renditionsApi ?? new RenditionsApi(this.apiService.getInstance()); this._renditionsApi = this._renditionsApi ?? new RenditionsApi(this.apiService.getInstance());
@@ -74,17 +72,12 @@ export class RenditionService {
return this._versionsApi; return this._versionsApi;
} }
constructor(private apiService: AlfrescoApiService, constructor(private apiService: AlfrescoApiService, private translateService: TranslationService, private viewUtilsService: ViewUtilService) {}
private logService: LogService,
private translateService: TranslationService,
private viewUtilsService: ViewUtilService) {
}
getRenditionUrl(nodeId: string, type: string, renditionExists: boolean): string { getRenditionUrl(nodeId: string, type: string, renditionExists: boolean): string {
return (renditionExists && type !== RenditionService.ContentGroup.IMAGE) ? return renditionExists && type !== RenditionService.ContentGroup.IMAGE
this.contentApi.getRenditionUrl(nodeId, RenditionService.ContentGroup.PDF) : ? this.contentApi.getRenditionUrl(nodeId, RenditionService.ContentGroup.PDF)
this.contentApi.getContentUrl(nodeId, false); : this.contentApi.getContentUrl(nodeId, false);
} }
private async waitRendition(nodeId: string, renditionId: string, retries: number): Promise<RenditionEntry> { private async waitRendition(nodeId: string, renditionId: string, retries: number): Promise<RenditionEntry> {
@@ -110,7 +103,9 @@ export class RenditionService {
async getRendition(nodeId: string, renditionId: string): Promise<RenditionEntry> { async getRendition(nodeId: string, renditionId: string): Promise<RenditionEntry> {
const renditionPaging: RenditionPaging = await this.renditionsApi.listRenditions(nodeId); const renditionPaging: RenditionPaging = await this.renditionsApi.listRenditions(nodeId);
let rendition: RenditionEntry = renditionPaging.list.entries.find((renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId); let rendition: RenditionEntry = renditionPaging.list.entries.find(
(renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId
);
if (rendition) { if (rendition) {
const status = rendition.entry.status.toString(); const status = rendition.entry.status.toString();
@@ -119,9 +114,7 @@ export class RenditionService {
try { try {
await this.renditionsApi.createRendition(nodeId, { id: renditionId }); await this.renditionsApi.createRendition(nodeId, { id: renditionId });
rendition = await this.waitRendition(nodeId, renditionId, 0); rendition = await this.waitRendition(nodeId, renditionId, 0);
} catch (err) { } catch {}
this.logService.error(err);
}
} }
} }
return new Promise<RenditionEntry>((resolve) => resolve(rendition)); return new Promise<RenditionEntry>((resolve) => resolve(rendition));
@@ -129,10 +122,8 @@ export class RenditionService {
async getNodeRendition(nodeId: string, versionId?: string): Promise<{ url: string; mimeType: string }> { async getNodeRendition(nodeId: string, versionId?: string): Promise<{ url: string; mimeType: string }> {
try { try {
return versionId ? await this.resolveNodeRendition(nodeId, 'pdf', versionId) : return versionId ? await this.resolveNodeRendition(nodeId, 'pdf', versionId) : await this.resolveNodeRendition(nodeId, 'pdf');
await this.resolveNodeRendition(nodeId, 'pdf'); } catch {
} catch (err) {
this.logService.error(err);
return null; return null;
} }
} }
@@ -140,8 +131,9 @@ export class RenditionService {
private async resolveNodeRendition(nodeId: string, renditionId: string, versionId?: string): Promise<{ url: string; mimeType: string }> { private async resolveNodeRendition(nodeId: string, renditionId: string, versionId?: string): Promise<{ url: string; mimeType: string }> {
renditionId = renditionId.toLowerCase(); renditionId = renditionId.toLowerCase();
const supportedRendition: RenditionPaging = versionId ? await this.versionsApi.listVersionRenditions(nodeId, versionId) : const supportedRendition: RenditionPaging = versionId
await this.renditionsApi.listRenditions(nodeId); ? await this.versionsApi.listVersionRenditions(nodeId, versionId)
: await this.renditionsApi.listRenditions(nodeId);
let rendition = this.findRenditionById(supportedRendition, renditionId); let rendition = this.findRenditionById(supportedRendition, renditionId);
if (!rendition) { if (!rendition) {
@@ -175,16 +167,13 @@ export class RenditionService {
} catch (e) { } catch (e) {
return null; return null;
} }
} catch {
} catch (err) {
this.logService.error(err);
return null; return null;
} }
} }
private findRenditionById(supportedRendition: RenditionPaging, renditionId: string) { private findRenditionById(supportedRendition: RenditionPaging, renditionId: string) {
const rendition: RenditionEntry = supportedRendition.list.entries.find((renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId); return supportedRendition.list.entries.find((renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId);
return rendition;
} }
private async waitNodeRendition(nodeId: string, renditionId: string, versionId?: string): Promise<string> { private async waitNodeRendition(nodeId: string, renditionId: string, versionId?: string): Promise<string> {
@@ -194,23 +183,29 @@ export class RenditionService {
currentRetry++; currentRetry++;
if (this.maxRetries >= currentRetry) { if (this.maxRetries >= currentRetry) {
if (versionId) { if (versionId) {
this.versionsApi.getVersionRendition(nodeId, versionId, renditionId).then((rendition: RenditionEntry) => { this.versionsApi.getVersionRendition(nodeId, versionId, renditionId).then(
(rendition: RenditionEntry) => {
const status: string = rendition.entry.status.toString(); const status: string = rendition.entry.status.toString();
if (status === 'CREATED') { if (status === 'CREATED') {
clearInterval(intervalId); clearInterval(intervalId);
return resolve(this.handleNodeRendition(nodeId, rendition.entry.content.mimeType, versionId)); return resolve(this.handleNodeRendition(nodeId, rendition.entry.content.mimeType, versionId));
} }
}, () => reject(new Error('Error geting version rendition'))); },
() => reject(new Error('Error geting version rendition'))
);
} else { } else {
this.renditionsApi.getRendition(nodeId, renditionId).then((rendition: RenditionEntry) => { this.renditionsApi.getRendition(nodeId, renditionId).then(
(rendition: RenditionEntry) => {
const status: string = rendition.entry.status.toString(); const status: string = rendition.entry.status.toString();
if (status === 'CREATED') { if (status === 'CREATED') {
clearInterval(intervalId); clearInterval(intervalId);
return resolve(this.handleNodeRendition(nodeId, renditionId, versionId)); return resolve(this.handleNodeRendition(nodeId, renditionId, versionId));
} }
}, () => reject(new Error('Error getting rendition'))); },
() => reject(new Error('Error getting rendition'))
);
} }
} else { } else {
clearInterval(intervalId); clearInterval(intervalId);
@@ -221,11 +216,9 @@ export class RenditionService {
} }
private async handleNodeRendition(nodeId: string, renditionId: string, versionId?: string): Promise<string> { private async handleNodeRendition(nodeId: string, renditionId: string, versionId?: string): Promise<string> {
return versionId
const url = versionId ? this.contentApi.getVersionRenditionUrl(nodeId, versionId, renditionId) : ? this.contentApi.getVersionRenditionUrl(nodeId, versionId, renditionId)
this.contentApi.getRenditionUrl(nodeId, renditionId); : this.contentApi.getRenditionUrl(nodeId, renditionId);
return url;
} }
async generateMediaTracksRendition(nodeId: string): Promise<Track[]> { async generateMediaTracksRendition(nodeId: string): Promise<Track[]> {
@@ -241,16 +234,14 @@ export class RenditionService {
} }
return tracks; return tracks;
}) })
.catch((err) => { .catch(() => []);
this.logService.error('Error while retrieving ' + RenditionService.SUBTITLES_RENDITION_NAME + ' rendition');
this.logService.error(err);
return [];
});
} }
private async isRenditionAvailable(nodeId: string, renditionId: string): Promise<boolean> { private async isRenditionAvailable(nodeId: string, renditionId: string): Promise<boolean> {
const renditionPaging: RenditionPaging = await this.renditionsApi.listRenditions(nodeId); const renditionPaging: RenditionPaging = await this.renditionsApi.listRenditions(nodeId);
const rendition: RenditionEntry = renditionPaging.list.entries.find((renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId); const rendition: RenditionEntry = renditionPaging.list.entries.find(
(renditionEntry: RenditionEntry) => renditionEntry.entry.id.toLowerCase() === renditionId
);
return rendition?.entry?.status?.toString() === 'CREATED' || false; return rendition?.entry?.status?.toString() === 'CREATED' || false;
} }
@@ -297,15 +288,13 @@ export class RenditionService {
this.getRendition(nodeId, RenditionService.ContentGroup.PDF) this.getRendition(nodeId, RenditionService.ContentGroup.PDF)
.then((value) => { .then((value) => {
const url: string = this.getRenditionUrl(nodeId, type, (!!value)); const url: string = this.getRenditionUrl(nodeId, type, !!value);
const printType = (type === RenditionService.ContentGroup.PDF const printType =
|| type === RenditionService.ContentGroup.TEXT) type === RenditionService.ContentGroup.PDF || type === RenditionService.ContentGroup.TEXT
? RenditionService.ContentGroup.PDF : type; ? RenditionService.ContentGroup.PDF
: type;
this.printFile(url, printType); this.printFile(url, printType);
}) })
.catch((err) => { .catch(() => {});
this.logService.error('Error with Printing');
this.logService.error(err);
});
} }
} }
@@ -16,7 +16,7 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { AlfrescoApiService, LogService, TranslationService, ViewUtilService } from '@alfresco/adf-core'; import { AlfrescoApiService, TranslationService, ViewUtilService } from '@alfresco/adf-core';
import { Rendition, RenditionEntry, RenditionPaging, RenditionsApi } from '@alfresco/js-api'; import { Rendition, RenditionEntry, RenditionPaging, RenditionsApi } from '@alfresco/js-api';
import { RenditionService } from '@alfresco/adf-content-services'; import { RenditionService } from '@alfresco/adf-content-services';
@@ -43,14 +43,16 @@ describe('RenditionService', () => {
providers: [ providers: [
RenditionService, RenditionService,
{ provide: AlfrescoApiService, useValue: {} }, { provide: AlfrescoApiService, useValue: {} },
{ provide: LogService, useValue: { error: jasmine.createSpy('error') } },
{ provide: TranslationService, useValue: {} }, { provide: TranslationService, useValue: {} },
{ provide: ViewUtilService, useValue: {} }, { provide: ViewUtilService, useValue: {} },
{ provide: RenditionsApi, useValue: { {
provide: RenditionsApi,
useValue: {
listRenditions: jasmine.createSpy('listRenditions'), listRenditions: jasmine.createSpy('listRenditions'),
getRendition: jasmine.createSpy('getRendition'), getRendition: jasmine.createSpy('getRendition'),
createRendition: jasmine.createSpy('createRendition') createRendition: jasmine.createSpy('createRendition')
} } }
}
] ]
}); });
renditionService = TestBed.inject(RenditionService); renditionService = TestBed.inject(RenditionService);
@@ -98,5 +100,4 @@ describe('RenditionService', () => {
expect(result).toEqual(mockRenditionPaging.list.entries[0]); expect(result).toEqual(mockRenditionPaging.list.entries[0]);
expect(renditionsApi.getRendition).not.toHaveBeenCalled(); expect(renditionsApi.getRendition).not.toHaveBeenCalled();
}); });
}); });
@@ -16,7 +16,7 @@
*/ */
import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core'; import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core';
import { LogService, InfiniteSelectScrollDirective, AuthenticationService } from '@alfresco/adf-core'; import { InfiniteSelectScrollDirective, AuthenticationService } from '@alfresco/adf-core';
import { SitePaging, SiteEntry, Site } from '@alfresco/js-api'; import { SitePaging, SiteEntry, Site } from '@alfresco/js-api';
import { MatSelectChange } from '@angular/material/select'; import { MatSelectChange } from '@angular/material/select';
import { LiveAnnouncer } from '@angular/cdk/a11y'; import { LiveAnnouncer } from '@angular/cdk/a11y';
@@ -77,6 +77,9 @@ export class DropdownSitesComponent implements OnInit {
@Output() @Output()
change: EventEmitter<SiteEntry> = new EventEmitter(); change: EventEmitter<SiteEntry> = new EventEmitter();
@Output()
error = new EventEmitter<any>();
private loading = true; private loading = true;
private skipCount = 0; private skipCount = 0;
@@ -86,7 +89,6 @@ export class DropdownSitesComponent implements OnInit {
constructor( constructor(
private authService: AuthenticationService, private authService: AuthenticationService,
private sitesService: SitesService, private sitesService: SitesService,
private logService: LogService,
private liveAnnouncer: LiveAnnouncer, private liveAnnouncer: LiveAnnouncer,
private translateService: TranslateService private translateService: TranslateService
) {} ) {}
@@ -158,7 +160,7 @@ export class DropdownSitesComponent implements OnInit {
this.loading = false; this.loading = false;
}, },
(error) => { (error) => {
this.logService.error(error); this.error.emit(error);
} }
); );
} }
@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { EXTENDIBLE_COMPONENT, FileUtils, LogService } from '@alfresco/adf-core'; import { EXTENDIBLE_COMPONENT, FileUtils } from '@alfresco/adf-core';
import { Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output, SimpleChanges, ViewEncapsulation, inject } from '@angular/core'; import { Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output, SimpleChanges, ViewEncapsulation, inject } from '@angular/core';
import { NodesApiService } from '../../common/services/nodes-api.service'; import { NodesApiService } from '../../common/services/nodes-api.service';
import { ContentService } from '../../common/services/content.service'; import { ContentService } from '../../common/services/content.service';
@@ -36,7 +36,6 @@ import { NodeAllowableOperationSubject } from '../../interfaces/node-allowable-o
export class UploadButtonComponent extends UploadBase implements OnInit, OnChanges, NodeAllowableOperationSubject { export class UploadButtonComponent extends UploadBase implements OnInit, OnChanges, NodeAllowableOperationSubject {
private contentService = inject(ContentService); private contentService = inject(ContentService);
private nodesApiService = inject(NodesApiService); private nodesApiService = inject(NodesApiService);
protected logService = inject(LogService);
/** Allows/disallows upload folders (only for Chrome). */ /** Allows/disallows upload folders (only for Chrome). */
@Input() @Input()
@@ -32,7 +32,6 @@ import {
import { import {
AlfrescoApiService, AlfrescoApiService,
CloseButtonPosition, CloseButtonPosition,
LogService,
Track, Track,
ViewerComponent, ViewerComponent,
ViewerMoreActionsComponent, ViewerMoreActionsComponent,
@@ -241,7 +240,6 @@ export class AlfrescoViewerComponent implements OnChanges, OnInit, OnDestroy {
private nodesApiService: NodesApiService, private nodesApiService: NodesApiService,
private renditionService: RenditionService, private renditionService: RenditionService,
private viewUtilService: ViewUtilService, private viewUtilService: ViewUtilService,
private logService: LogService,
private contentService: ContentService, private contentService: ContentService,
private uploadService: UploadService, private uploadService: UploadService,
public dialog: MatDialog, public dialog: MatDialog,
@@ -256,9 +254,7 @@ export class AlfrescoViewerComponent implements OnChanges, OnInit, OnDestroy {
.pipe( .pipe(
filter( filter(
(node) => (node) =>
node && node && node.id === this.nodeId && this.getNodeVersionProperty(this.nodeEntry.entry) !== this.getNodeVersionProperty(node)
node.id === this.nodeId &&
this.getNodeVersionProperty(this.nodeEntry.entry) !== this.getNodeVersionProperty(node)
), ),
takeUntil(this.onDestroy$) takeUntil(this.onDestroy$)
) )
@@ -284,7 +280,6 @@ export class AlfrescoViewerComponent implements OnChanges, OnInit, OnDestroy {
const sharedLinkEntry = await this.sharedLinksApi.getSharedLink(this.sharedLinkId); const sharedLinkEntry = await this.sharedLinksApi.getSharedLink(this.sharedLinkId);
await this.setUpSharedLinkFile(sharedLinkEntry); await this.setUpSharedLinkFile(sharedLinkEntry);
} catch (error) { } catch (error) {
this.logService.error('This sharedLink does not exist');
this.invalidSharedLink.next(undefined); this.invalidSharedLink.next(undefined);
this.mimeType = 'invalid-link'; this.mimeType = 'invalid-link';
this.urlFileContent = 'invalid-file'; this.urlFileContent = 'invalid-file';
@@ -303,7 +298,6 @@ export class AlfrescoViewerComponent implements OnChanges, OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
this.urlFileContent = 'invalid-node'; this.urlFileContent = 'invalid-node';
this.logService.error('This node does not exist');
} }
} }
@@ -373,7 +367,6 @@ export class AlfrescoViewerComponent implements OnChanges, OnInit, OnDestroy {
return { url: urlFileContent, mimeType: 'application/pdf' }; return { url: urlFileContent, mimeType: 'application/pdf' };
} }
} catch (error) { } catch (error) {
this.logService.error(error);
try { try {
const rendition: RenditionEntry = await this.sharedLinksApi.getSharedLinkRendition(sharedId, 'imgpreview'); const rendition: RenditionEntry = await this.sharedLinksApi.getSharedLinkRendition(sharedId, 'imgpreview');
if (rendition.entry.status.toString() === 'CREATED') { if (rendition.entry.status.toString() === 'CREATED') {
@@ -381,7 +374,6 @@ export class AlfrescoViewerComponent implements OnChanges, OnInit, OnDestroy {
return { url: urlFileContent, mimeType: 'image/png' }; return { url: urlFileContent, mimeType: 'image/png' };
} }
} catch (renditionError) { } catch (renditionError) {
this.logService.error(renditionError);
return null; return null;
} }
} }
@@ -19,7 +19,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { AboutGithubLinkComponent } from './about-github-link.component'; import { AboutGithubLinkComponent } from './about-github-link.component';
import { aboutGithubDetails } from '../about.mock'; import { aboutGithubDetails } from '../about.mock';
import { TranslateModule } from '@ngx-translate/core';
describe('AboutGithubLinkComponent', () => { describe('AboutGithubLinkComponent', () => {
let fixture: ComponentFixture<AboutGithubLinkComponent>; let fixture: ComponentFixture<AboutGithubLinkComponent>;
@@ -27,7 +26,7 @@ describe('AboutGithubLinkComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [CoreTestingModule]
}); });
fixture = TestBed.createComponent(AboutGithubLinkComponent); fixture = TestBed.createComponent(AboutGithubLinkComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -20,7 +20,6 @@ import { CoreTestingModule } from '../../testing/core.testing.module';
import { AboutServerSettingsComponent } from './about-server-settings.component'; import { AboutServerSettingsComponent } from './about-server-settings.component';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.service';
import { aboutGithubDetails } from '../about.mock'; import { aboutGithubDetails } from '../about.mock';
import { TranslateModule } from '@ngx-translate/core';
describe('AboutServerSettingsComponent', () => { describe('AboutServerSettingsComponent', () => {
let fixture: ComponentFixture<AboutServerSettingsComponent>; let fixture: ComponentFixture<AboutServerSettingsComponent>;
@@ -29,10 +28,7 @@ describe('AboutServerSettingsComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(AboutServerSettingsComponent); fixture = TestBed.createComponent(AboutServerSettingsComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -25,7 +25,6 @@ import { catchError, map } from 'rxjs/operators';
import { from, Observable } from 'rxjs'; import { from, Observable } from 'rxjs';
import { RedirectionModel } from '../models/redirection.model'; import { RedirectionModel } from '../models/redirection.model';
import { BaseAuthenticationService } from '../services/base-authentication.service'; import { BaseAuthenticationService } from '../services/base-authentication.service';
import { LogService } from '../../common';
import { HttpHeaders } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http';
const REMEMBER_ME_COOKIE_KEY = 'ALFRESCO_REMEMBER_ME'; const REMEMBER_ME_COOKIE_KEY = 'ALFRESCO_REMEMBER_ME';
@@ -35,7 +34,6 @@ const REMEMBER_ME_UNTIL = 1000 * 60 * 60 * 24 * 30;
providedIn: 'root' providedIn: 'root'
}) })
export class BasicAlfrescoAuthService extends BaseAuthenticationService { export class BasicAlfrescoAuthService extends BaseAuthenticationService {
protected redirectUrl: RedirectionModel = null; protected redirectUrl: RedirectionModel = null;
authentications: Authentication = { authentications: Authentication = {
@@ -45,45 +43,52 @@ export class BasicAlfrescoAuthService extends BaseAuthenticationService {
type: 'basic' type: 'basic'
}; };
constructor( constructor(appConfig: AppConfigService, cookie: CookieService, private contentAuth: ContentAuth, private processAuth: ProcessAuth) {
logService: LogService, super(appConfig, cookie);
appConfig: AppConfigService,
cookie: CookieService,
private contentAuth: ContentAuth,
private processAuth: ProcessAuth
) {
super(appConfig, cookie, logService);
this.appConfig.onLoad this.appConfig.onLoad.subscribe(() => {
.subscribe(() => {
if (!this.isOauth() && this.isLoggedIn()) { if (!this.isOauth() && this.isLoggedIn()) {
this.requireAlfTicket().then(() => { this.requireAlfTicket()
.then(() => {
this.onLogin.next('logged-in'); this.onLogin.next('logged-in');
}).catch(() => { })
.catch(() => {
this.contentAuth.invalidateSession(); this.contentAuth.invalidateSession();
this.onLogout.next('logout'); this.onLogout.next('logout');
}); });
} }
}); });
this.contentAuth.onLogout.pipe(map((event) => { this.contentAuth.onLogout.pipe(
map((event) => {
this.onLogout.next(event); this.onLogout.next(event);
})); })
this.contentAuth.onLogin.pipe(map((event) => { );
this.contentAuth.onLogin.pipe(
map((event) => {
this.onLogin.next(event); this.onLogin.next(event);
})); })
this.contentAuth.onError.pipe(map((event) => { );
this.contentAuth.onError.pipe(
map((event) => {
this.onError.next(event); this.onError.next(event);
})); })
this.processAuth.onLogout.pipe(map((event) => { );
this.processAuth.onLogout.pipe(
map((event) => {
this.onLogout.next(event); this.onLogout.next(event);
})); })
this.processAuth.onLogin.pipe(map((event) => { );
this.processAuth.onLogin.pipe(
map((event) => {
this.onLogin.next(event); this.onLogin.next(event);
})); })
this.processAuth.onError.pipe(map((event) => { );
this.processAuth.onError.pipe(
map((event) => {
this.onError.next(event); this.onError.next(event);
})); })
);
} }
/** /**
@@ -130,20 +135,17 @@ export class BasicAlfrescoAuthService extends BaseAuthenticationService {
} catch (e) { } catch (e) {
return Promise.reject(e); return Promise.reject(e);
} }
} else if (this.isECMProvider()) { } else if (this.isECMProvider()) {
try { try {
return await this.contentAuth.login(username, password); return await this.contentAuth.login(username, password);
} catch (e) { } catch (e) {
return Promise.reject(e); return Promise.reject(e);
} }
} else if (this.isALLProvider()) { } else if (this.isALLProvider()) {
return this.loginBPMECM(username, password); return this.loginBPMECM(username, password);
} else { } else {
return Promise.reject(new Error('Unknown configuration')); return Promise.reject(new Error('Unknown configuration'));
} }
} }
private loginBPMECM(username: string, password: string): Promise<any> { private loginBPMECM(username: string, password: string): Promise<any> {
@@ -165,7 +167,8 @@ export class BasicAlfrescoAuthService extends BaseAuthenticationService {
} }
this.onError.next('error'); this.onError.next('error');
reject(error); reject(error);
}); }
);
}); });
} }
@@ -243,7 +246,7 @@ export class BasicAlfrescoAuthService extends BaseAuthenticationService {
} else if (this.isECMProvider()) { } else if (this.isECMProvider()) {
return authWithCredentials ? true : this.contentAuth.isLoggedIn(); return authWithCredentials ? true : this.contentAuth.isLoggedIn();
} else if (this.isALLProvider()) { } else if (this.isALLProvider()) {
return authWithCredentials ? true : (this.contentAuth.isLoggedIn() && this.processAuth.isLoggedIn()); return authWithCredentials ? true : this.contentAuth.isLoggedIn() && this.processAuth.isLoggedIn();
} else { } else {
return false; return false;
} }
@@ -281,12 +284,13 @@ export class BasicAlfrescoAuthService extends BaseAuthenticationService {
} }
this.onError.next('error'); this.onError.next('error');
reject(error); reject(error);
}
);
}); });
});
} }
reset(): void { reset(): void {
// do nothing
} }
/** /**
@@ -22,12 +22,10 @@ import { AuthenticationService } from '../services/authentication.service';
import { RouterStateSnapshot, Router } from '@angular/router'; import { RouterStateSnapshot, Router } from '@angular/router';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
import { OidcAuthenticationService } from '../services/oidc-authentication.service'; import { OidcAuthenticationService } from '../services/oidc-authentication.service';
describe('AuthGuardService BPM', () => { describe('AuthGuardService BPM', () => {
let authGuard: AuthGuardBpm; let authGuard: AuthGuardBpm;
let authService: AuthenticationService; let authService: AuthenticationService;
let basicAlfrescoAuthService: BasicAlfrescoAuthService; let basicAlfrescoAuthService: BasicAlfrescoAuthService;
@@ -38,13 +36,11 @@ describe('AuthGuardService BPM', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ {
provide: OidcAuthenticationService, useValue: { provide: OidcAuthenticationService,
useValue: {
ssoLogin: () => {}, ssoLogin: () => {},
isPublicUrl: () => false, isPublicUrl: () => false,
hasValidIdToken: () => false, hasValidIdToken: () => false,
@@ -154,7 +150,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url' provider: 'BPM',
url: 'some-url'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url');
}); });
@@ -167,7 +164,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url;q=123' provider: 'BPM',
url: 'some-url;q=123'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123');
}); });
@@ -180,7 +178,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: '/' provider: 'BPM',
url: '/'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('/'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('/');
}); });
@@ -194,7 +193,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url' provider: 'BPM',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url'));
}); });
@@ -211,7 +211,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url' provider: 'BPM',
url: 'some-url'
}); });
expect(materialDialog.closeAll).toHaveBeenCalled(); expect(materialDialog.closeAll).toHaveBeenCalled();
@@ -22,12 +22,10 @@ import { AuthenticationService } from '../services/authentication.service';
import { RouterStateSnapshot, Router } from '@angular/router'; import { RouterStateSnapshot, Router } from '@angular/router';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { OidcAuthenticationService } from '../services/oidc-authentication.service'; import { OidcAuthenticationService } from '../services/oidc-authentication.service';
import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
describe('AuthGuardService ECM', () => { describe('AuthGuardService ECM', () => {
let authGuard: AuthGuardEcm; let authGuard: AuthGuardEcm;
let authService: AuthenticationService; let authService: AuthenticationService;
let basicAlfrescoAuthService: BasicAlfrescoAuthService; let basicAlfrescoAuthService: BasicAlfrescoAuthService;
@@ -37,13 +35,11 @@ describe('AuthGuardService ECM', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ {
provide: OidcAuthenticationService, useValue: { provide: OidcAuthenticationService,
useValue: {
ssoLogin: () => {}, ssoLogin: () => {},
isPublicUrl: () => false, isPublicUrl: () => false,
hasValidIdToken: () => false, hasValidIdToken: () => false,
@@ -151,7 +147,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url' provider: 'ECM',
url: 'some-url'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url');
}); });
@@ -164,7 +161,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url;q=123' provider: 'ECM',
url: 'some-url;q=123'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123');
}); });
@@ -177,7 +175,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: '/' provider: 'ECM',
url: '/'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('/'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('/');
}); });
@@ -191,7 +190,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url' provider: 'ECM',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url'));
}); });
@@ -208,7 +208,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url' provider: 'ECM',
url: 'some-url'
}); });
expect(materialDialog.closeAll).toHaveBeenCalled(); expect(materialDialog.closeAll).toHaveBeenCalled();
@@ -21,20 +21,15 @@ import { CoreTestingModule } from '../../testing/core.testing.module';
import { AuthGuardSsoRoleService } from './auth-guard-sso-role.service'; import { AuthGuardSsoRoleService } from './auth-guard-sso-role.service';
import { JwtHelperService } from '../services/jwt-helper.service'; import { JwtHelperService } from '../services/jwt-helper.service';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
describe('Auth Guard SSO role service', () => { describe('Auth Guard SSO role service', () => {
let authGuard: AuthGuardSsoRoleService; let authGuard: AuthGuardSsoRoleService;
let jwtHelperService: JwtHelperService; let jwtHelperService: JwtHelperService;
let routerService: Router; let routerService: Router;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
localStorage.clear(); localStorage.clear();
authGuard = TestBed.inject(AuthGuardSsoRoleService); authGuard = TestBed.inject(AuthGuardSsoRoleService);
@@ -192,6 +187,5 @@ describe('Auth Guard SSO role service', () => {
router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'], excludedRoles: ['MOCK_ROOT_USER_ROLE'] }; router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'], excludedRoles: ['MOCK_ROOT_USER_ROLE'] };
expect(authGuard.canActivate(router)).toBeTruthy(); expect(authGuard.canActivate(router)).toBeTruthy();
}); });
}); });
}); });
@@ -21,7 +21,6 @@ import { AppConfigService } from '../../app-config/app-config.service';
import { AuthGuard } from './auth-guard.service'; import { AuthGuard } from './auth-guard.service';
import { AuthenticationService } from '../services/authentication.service'; import { AuthenticationService } from '../services/authentication.service';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
import { OidcAuthenticationService } from '../services/oidc-authentication.service'; import { OidcAuthenticationService } from '../services/oidc-authentication.service';
import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
@@ -38,13 +37,11 @@ describe('AuthGuardService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ {
provide: OidcAuthenticationService, useValue: { provide: OidcAuthenticationService,
useValue: {
ssoLogin: () => {}, ssoLogin: () => {},
isPublicUrl: () => false, isPublicUrl: () => false,
hasValidIdToken: () => false hasValidIdToken: () => false
@@ -144,7 +141,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: 'some-url' provider: 'ALL',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url'));
}); });
@@ -160,7 +158,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: 'some-url;q=query' provider: 'ALL',
url: 'some-url;q=query'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url;q=query')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url;q=query'));
}); });
@@ -175,7 +174,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: 'some-url' provider: 'ALL',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url'));
}); });
@@ -189,7 +189,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: '/' provider: 'ALL',
url: '/'
}); });
}); });
}); });
@@ -21,7 +21,6 @@ import { CookieService } from '../../common/services/cookie.service';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.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 { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
import { OidcAuthenticationService } from './oidc-authentication.service'; import { OidcAuthenticationService } from './oidc-authentication.service';
@@ -35,10 +34,7 @@ describe('AuthenticationService', () => {
let oidcAuthenticationService: OidcAuthenticationService; let oidcAuthenticationService: OidcAuthenticationService;
setupTestBed({ setupTestBed({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
beforeEach(() => { beforeEach(() => {
@@ -97,7 +93,6 @@ describe('AuthenticationService', () => {
}); });
describe('when the setting is ECM', () => { describe('when the setting is ECM', () => {
const fakeECMLoginResponse = { type: 'ECM', ticket: 'fake-post-ticket' }; const fakeECMLoginResponse = { type: 'ECM', ticket: 'fake-post-ticket' };
beforeEach(() => { beforeEach(() => {
@@ -216,7 +211,6 @@ describe('AuthenticationService', () => {
}); });
describe('when the setting is BPM', () => { describe('when the setting is BPM', () => {
beforeEach(() => { beforeEach(() => {
appConfigService.config.providers = 'BPM'; appConfigService.config.providers = 'BPM';
appConfigService.load(); appConfigService.load();
@@ -278,13 +272,13 @@ describe('AuthenticationService', () => {
it('[BPM] should return an error when the logout return error', (done) => { it('[BPM] should return an error when the logout return error', (done) => {
authService.logout().subscribe( authService.logout().subscribe(
() => { () => {},
},
(err: any) => { (err: any) => {
expect(err).toBeDefined(); expect(err).toBeDefined();
expect(authService.getToken()).toBe(null); expect(authService.getToken()).toBe(null);
done(); done();
}); }
);
jasmine.Ajax.requests.mostRecent().respondWith({ jasmine.Ajax.requests.mostRecent().respondWith({
status: 403 status: 403
@@ -323,7 +317,6 @@ describe('AuthenticationService', () => {
}); });
describe('remember me', () => { describe('remember me', () => {
beforeEach(() => { beforeEach(() => {
appConfigService.config.providers = 'ECM'; appConfigService.config.providers = 'ECM';
appConfigService.load(); appConfigService.load();
@@ -367,7 +360,8 @@ describe('AuthenticationService', () => {
expect(cookie['ALFRESCO_REMEMBER_ME']).toBeUndefined(); expect(cookie['ALFRESCO_REMEMBER_ME']).toBeUndefined();
disposableLogin.unsubscribe(); disposableLogin.unsubscribe();
done(); done();
}); }
);
jasmine.Ajax.requests.mostRecent().respondWith({ jasmine.Ajax.requests.mostRecent().respondWith({
status: 403, status: 403,
@@ -386,7 +380,6 @@ describe('AuthenticationService', () => {
}); });
describe('when the setting is both ECM and BPM ', () => { describe('when the setting is both ECM and BPM ', () => {
beforeEach(() => { beforeEach(() => {
appConfigService.config.providers = 'ALL'; appConfigService.config.providers = 'ALL';
appConfigService.load(); appConfigService.load();
@@ -426,7 +419,8 @@ describe('AuthenticationService', () => {
expect(authService.isEcmLoggedIn()).toBe(false, 'isEcmLoggedIn'); expect(authService.isEcmLoggedIn()).toBe(false, 'isEcmLoggedIn');
disposableLogin.unsubscribe(); disposableLogin.unsubscribe();
done(); done();
}); }
);
jasmine.Ajax.requests.at(0).respondWith({ jasmine.Ajax.requests.at(0).respondWith({
status: 403 status: 403
@@ -447,7 +441,8 @@ describe('AuthenticationService', () => {
expect(authService.isBpmLoggedIn()).toBe(false); expect(authService.isBpmLoggedIn()).toBe(false);
disposableLogin.unsubscribe(); disposableLogin.unsubscribe();
done(); done();
}); }
);
jasmine.Ajax.requests.at(0).respondWith({ jasmine.Ajax.requests.at(0).respondWith({
status: 201, status: 201,
@@ -471,7 +466,8 @@ describe('AuthenticationService', () => {
expect(authService.isEcmLoggedIn()).toBe(false); expect(authService.isEcmLoggedIn()).toBe(false);
disposableLogin.unsubscribe(); disposableLogin.unsubscribe();
done(); done();
}); }
);
jasmine.Ajax.requests.at(0).respondWith({ jasmine.Ajax.requests.at(0).respondWith({
status: 403 status: 403
@@ -510,6 +506,5 @@ describe('AuthenticationService', () => {
const username = authService.getUsername(); const username = authService.getUsername();
expect(username).toEqual('john.petrucci'); expect(username).toEqual('john.petrucci');
}); });
}); });
}); });
@@ -20,12 +20,10 @@ import { RedirectionModel } from '../models/redirection.model';
import { Observable, Observer, ReplaySubject, throwError } from 'rxjs'; import { Observable, Observer, ReplaySubject, throwError } from 'rxjs';
import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service'; import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service';
import { CookieService } from '../../common/services/cookie.service'; import { CookieService } from '../../common/services/cookie.service';
import { LogService } from '../../common/services/log.service';
import { AuthenticationServiceInterface } from '../interfaces/authentication-service.interface'; import { AuthenticationServiceInterface } from '../interfaces/authentication-service.interface';
import ee from 'event-emitter'; import ee from 'event-emitter';
export abstract class BaseAuthenticationService implements AuthenticationServiceInterface, ee.Emitter { export abstract class BaseAuthenticationService implements AuthenticationServiceInterface, ee.Emitter {
on: ee.EmitterMethod; on: ee.EmitterMethod;
off: ee.EmitterMethod; off: ee.EmitterMethod;
once: ee.EmitterMethod; once: ee.EmitterMethod;
@@ -37,11 +35,7 @@ export abstract class BaseAuthenticationService implements AuthenticationService
onLogin = new ReplaySubject<any>(1); onLogin = new ReplaySubject<any>(1);
onLogout = new ReplaySubject<any>(1); onLogout = new ReplaySubject<any>(1);
constructor( protected constructor(protected appConfig: AppConfigService, protected cookie: CookieService) {
protected appConfig: AppConfigService,
protected cookie: CookieService,
private logService: LogService
) {
ee(this); ee(this);
} }
@@ -77,7 +71,6 @@ export abstract class BaseAuthenticationService implements AuthenticationService
headers = new HttpHeaders(); headers = new HttpHeaders();
} }
try { try {
const header = this.getAuthHeaders(requestUrl, headers); const header = this.getAuthHeaders(requestUrl, headers);
observer.next(header); observer.next(header);
@@ -130,7 +123,6 @@ export abstract class BaseAuthenticationService implements AuthenticationService
*/ */
handleError(error: any): Observable<any> { handleError(error: any): Observable<any> {
this.onError.next(error || 'Server error'); this.onError.next(error || 'Server error');
this.logService.error('Error when logging in', error);
return throwError(error || 'Server error'); return throwError(error || 'Server error');
} }
@@ -28,7 +28,6 @@ import {
roleMappingMock roleMappingMock
} from '../mock/identity-group.mock'; } from '../mock/identity-group.mock';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '../../../../api/src'; import { AdfHttpClient } from '../../../../api/src';
describe('IdentityGroupService', () => { describe('IdentityGroupService', () => {
@@ -38,10 +37,7 @@ describe('IdentityGroupService', () => {
beforeEach(fakeAsync(() => { beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
service = TestBed.inject(IdentityGroupService); service = TestBed.inject(IdentityGroupService);
adfHttpClient = TestBed.inject(AdfHttpClient); adfHttpClient = TestBed.inject(AdfHttpClient);
@@ -84,28 +80,26 @@ describe('IdentityGroupService', () => {
it('should able to fetch group roles by groupId', (done) => { it('should able to fetch group roles by groupId', (done) => {
spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles)); spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles));
service.getGroupRoles('mock-group-id').subscribe( service.getGroupRoles('mock-group-id').subscribe((res: any) => {
(res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res.length).toEqual(3); expect(res.length).toEqual(3);
expect(res[0].name).toEqual('MOCK-ADMIN-ROLE'); expect(res[0].name).toEqual('MOCK-ADMIN-ROLE');
expect(res[1].name).toEqual('MOCK-USER-ROLE'); expect(res[1].name).toEqual('MOCK-USER-ROLE');
expect(res[2].name).toEqual('MOCK-ROLE-1'); expect(res[2].name).toEqual('MOCK-ROLE-1');
done(); done();
} });
);
}); });
it('Should not able to fetch group roles if error occurred', (done) => { it('Should not able to fetch group roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getGroupRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getGroupRoles').and.returnValue(throwError(errorResponse));
service.getGroupRoles('mock-group-id') service.getGroupRoles('mock-group-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not group roles'); fail('expected an error, not group roles');
}, },
@@ -120,48 +114,42 @@ describe('IdentityGroupService', () => {
it('should return true if group has given role', (done) => { it('should return true if group has given role', (done) => {
spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles)); spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles));
service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-ROLE']).subscribe( service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-ROLE']).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeTruthy(); expect(res).toBeTruthy();
done(); done();
} });
);
}); });
it('should return false if group does not have given role', (done) => { it('should return false if group does not have given role', (done) => {
spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles)); spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles));
service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-MODELER']).subscribe( service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-MODELER']).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeFalsy(); expect(res).toBeFalsy();
done(); done();
} });
);
}); });
it('should fetch client roles by groupId and clientId', (done) => { it('should fetch client roles by groupId and clientId', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles));
service.getClientRoles('mock-group-id', 'mock-client-id').subscribe( service.getClientRoles('mock-group-id', 'mock-client-id').subscribe((res: any) => {
(res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res.length).toEqual(2); expect(res.length).toEqual(2);
expect(res).toEqual(clientRoles); expect(res).toEqual(clientRoles);
done(); done();
} });
);
}); });
it('Should not fetch client roles if error occurred', (done) => { it('Should not fetch client roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getClientRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getClientRoles').and.returnValue(throwError(errorResponse));
service.getClientRoles('mock-group-id', 'mock-client-id') service.getClientRoles('mock-group-id', 'mock-client-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not client roles'); fail('expected an error, not client roles');
}, },
@@ -176,46 +164,38 @@ describe('IdentityGroupService', () => {
it('should return true if group has client access', (done) => { it('should return true if group has client access', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles));
service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe( service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeTruthy(); expect(res).toBeTruthy();
done(); done();
} });
);
}); });
it('should return false if group does not have client access', (done) => { it('should return false if group does not have client access', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe( service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeFalsy(); expect(res).toBeFalsy();
done(); done();
} });
);
}); });
it('should return true if group has any client role', (done) => { it('should return true if group has any client role', (done) => {
spyOn(service, 'checkGroupHasAnyClientAppRole').and.returnValue(of(true)); spyOn(service, 'checkGroupHasAnyClientAppRole').and.returnValue(of(true));
service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-USER-ROLE']).subscribe( service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-USER-ROLE']).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeTruthy(); expect(res).toBeTruthy();
done(); done();
} });
);
}); });
it('should return false if group does not have any client role', (done) => { it('should return false if group does not have any client role', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-ADMIN-MODELER']).subscribe( service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-ADMIN-MODELER']).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeFalsy(); expect(res).toBeFalsy();
done(); done();
} });
);
}); });
it('should be able to fetch the client id', (done) => { it('should be able to fetch the client id', (done) => {
@@ -245,13 +225,13 @@ describe('IdentityGroupService', () => {
it('Should not able to fetch all group if error occurred', (done) => { it('Should not able to fetch all group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getGroups').and.returnValue(throwError(errorResponse)); spyOn(service, 'getGroups').and.returnValue(throwError(errorResponse));
service.getGroups() service.getGroups().subscribe(
.subscribe(
() => { () => {
fail('expected an error, not groups'); fail('expected an error, not groups');
}, },
@@ -287,13 +267,13 @@ describe('IdentityGroupService', () => {
it('Should not able to query groups if error occurred', (done) => { it('Should not able to query groups if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'queryGroups').and.returnValue(throwError(errorResponse)); spyOn(service, 'queryGroups').and.returnValue(throwError(errorResponse));
service.queryGroups({first: 0, max: 5}) service.queryGroups({ first: 0, max: 5 }).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not query groups'); fail('expected an error, not query groups');
}, },
@@ -317,13 +297,13 @@ describe('IdentityGroupService', () => {
it('Should not able to create group if error occurred', (done) => { it('Should not able to create group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'createGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'createGroup').and.returnValue(throwError(errorResponse));
service.createGroup(mockIdentityGroup1) service.createGroup(mockIdentityGroup1).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to create group'); fail('expected an error, not to create group');
}, },
@@ -347,13 +327,13 @@ describe('IdentityGroupService', () => {
it('Should not able to update group if error occurred', (done) => { it('Should not able to update group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'updateGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'updateGroup').and.returnValue(throwError(errorResponse));
service.updateGroup('mock-group-id', mockIdentityGroup1) service.updateGroup('mock-group-id', mockIdentityGroup1).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to update group'); fail('expected an error, not to update group');
}, },
@@ -377,13 +357,13 @@ describe('IdentityGroupService', () => {
it('Should not able to delete group if error occurred', (done) => { it('Should not able to delete group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'deleteGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'deleteGroup').and.returnValue(throwError(errorResponse));
service.deleteGroup('mock-group-id') service.deleteGroup('mock-group-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to delete group'); fail('expected an error, not to delete group');
}, },
@@ -17,12 +17,11 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { throwError as observableThrowError, Observable, of } from 'rxjs'; import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { PaginationModel } from '../../models/pagination.model'; import { PaginationModel } from '../../models/pagination.model';
import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityRoleModel } from '../models/identity-role.model';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.service';
import { LogService } from '../../common/services/log.service';
export interface IdentityRoleResponseModel { export interface IdentityRoleResponseModel {
entries: IdentityRoleModel[]; entries: IdentityRoleModel[];
@@ -36,11 +35,7 @@ export class IdentityRoleService {
contextRoot = ''; contextRoot = '';
identityHost = ''; identityHost = '';
constructor( constructor(protected http: HttpClient, protected appConfig: AppConfigService) {
protected http: HttpClient,
protected appConfig: AppConfigService,
protected logService: LogService
) {
this.contextRoot = this.appConfig.get('apiHost', ''); this.contextRoot = this.appConfig.get('apiHost', '');
this.identityHost = this.appConfig.get('identityHost'); this.identityHost = this.appConfig.get('identityHost');
} }
@@ -52,21 +47,11 @@ export class IdentityRoleService {
* @param size page size * @param size page size
* @returns List of roles * @returns List of roles
*/ */
getRoles( getRoles(skipCount: number = 0, size: number = 5): Observable<IdentityRoleResponseModel> {
skipCount: number = 0, return this.http.get<any>(`${this.identityHost}/roles`).pipe(map((res) => this.preparePaginationWithRoles(res, skipCount, size)));
size: number = 5
): Observable<IdentityRoleResponseModel> {
return this.http.get<any>(`${this.identityHost}/roles`).pipe(
map(res => this.preparePaginationWithRoles(res, skipCount, size)),
catchError(error => this.handleError(error))
);
} }
private preparePaginationWithRoles( private preparePaginationWithRoles(roles: IdentityRoleModel[], skipCount: number = 0, size: number = 5): IdentityRoleResponseModel {
roles: IdentityRoleModel[],
skipCount: number = 0,
size: number = 5
): IdentityRoleResponseModel {
return { return {
entries: roles.slice(skipCount, skipCount + size), entries: roles.slice(skipCount, skipCount + size),
pagination: { pagination: {
@@ -87,10 +72,7 @@ export class IdentityRoleService {
*/ */
addRole(newRole: IdentityRoleModel): Observable<any> { addRole(newRole: IdentityRoleModel): Observable<any> {
if (newRole) { if (newRole) {
const request = newRole; return this.http.post(`${this.identityHost}/roles`, newRole);
return this.http
.post(`${this.identityHost}/roles`, request)
.pipe(catchError(error => this.handleError(error)));
} }
return of(); return of();
} }
@@ -102,9 +84,7 @@ export class IdentityRoleService {
* @returns Server result payload * @returns Server result payload
*/ */
deleteRole(deletedRole: IdentityRoleModel): Observable<any> { deleteRole(deletedRole: IdentityRoleModel): Observable<any> {
return this.http return this.http.delete(`${this.identityHost}/roles-by-id/${deletedRole.id}`);
.delete(`${this.identityHost}/roles-by-id/${deletedRole.id}`)
.pipe(catchError(error => this.handleError(error)));
} }
/** /**
@@ -114,21 +94,10 @@ export class IdentityRoleService {
* @param roleId Role id * @param roleId Role id
* @returns Server result payload * @returns Server result payload
*/ */
updateRole( updateRole(updatedRole: IdentityRoleModel, roleId: string): Observable<any> {
updatedRole: IdentityRoleModel,
roleId: string
): Observable<any> {
if (updatedRole && roleId) { if (updatedRole && roleId) {
const request = updatedRole; return this.http.put(`${this.identityHost}/roles-by-id/${roleId}`, updatedRole);
return this.http
.put(`${this.identityHost}/roles-by-id/${roleId}`, request)
.pipe(catchError(error => this.handleError(error)));
} }
return of(); return of();
} }
private handleError(error: any) {
this.logService.error(error);
return observableThrowError(error || 'Server error');
}
} }
@@ -33,12 +33,10 @@ import { JwtHelperService } from './jwt-helper.service';
import { mockToken } from '../mock/jwt-helper.service.spec'; import { mockToken } from '../mock/jwt-helper.service.spec';
import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityRoleModel } from '../models/identity-role.model';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '../../../../api/src'; import { AdfHttpClient } from '../../../../api/src';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
describe('IdentityUserService', () => { describe('IdentityUserService', () => {
const mockRoles = [ const mockRoles = [
{ id: 'id-1', name: 'MOCK-ADMIN-ROLE' }, { id: 'id-1', name: 'MOCK-ADMIN-ROLE' },
{ id: 'id-2', name: 'MOCK-USER-ROLE' }, { id: 'id-2', name: 'MOCK-USER-ROLE' },
@@ -54,10 +52,7 @@ describe('IdentityUserService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
storageService = TestBed.inject(StorageService); storageService = TestBed.inject(StorageService);
service = TestBed.inject(IdentityUserService); service = TestBed.inject(IdentityUserService);
@@ -87,8 +82,7 @@ describe('IdentityUserService', () => {
it('should fetch users ', (done) => { it('should fetch users ', (done) => {
spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers)); spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers));
service.getUsers().subscribe( service.getUsers().subscribe((res) => {
res => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res[0].id).toEqual('mock-user-id-1'); expect(res[0].id).toEqual('mock-user-id-1');
expect(res[0].username).toEqual('userName1'); expect(res[0].username).toEqual('userName1');
@@ -97,19 +91,18 @@ describe('IdentityUserService', () => {
expect(res[2].id).toEqual('mock-user-id-3'); expect(res[2].id).toEqual('mock-user-id-3');
expect(res[2].username).toEqual('userName3'); expect(res[2].username).toEqual('userName3');
done(); done();
} });
);
}); });
it('Should not fetch users if error occurred', (done) => { it('Should not fetch users if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse)); spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse));
service.getUsers() service.getUsers().subscribe(
.subscribe(
() => { () => {
fail('expected an error, not users'); fail('expected an error, not users');
}, },
@@ -124,27 +117,25 @@ describe('IdentityUserService', () => {
it('should fetch roles by userId', (done) => { it('should fetch roles by userId', (done) => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.getUserRoles('mock-user-id').subscribe( service.getUserRoles('mock-user-id').subscribe((res: IdentityRoleModel[]) => {
(res: IdentityRoleModel[]) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res[0].name).toEqual('MOCK-ADMIN-ROLE'); expect(res[0].name).toEqual('MOCK-ADMIN-ROLE');
expect(res[1].name).toEqual('MOCK-USER-ROLE'); expect(res[1].name).toEqual('MOCK-USER-ROLE');
expect(res[4].name).toEqual('MOCK-ROLE-2'); expect(res[4].name).toEqual('MOCK-ROLE-2');
done(); done();
} });
);
}); });
it('Should not fetch roles if error occurred', (done) => { it('Should not fetch roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getUserRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getUserRoles').and.returnValue(throwError(errorResponse));
service.getUserRoles('mock-user-id') service.getUserRoles('mock-user-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not users'); fail('expected an error, not users');
}, },
@@ -161,8 +152,7 @@ describe('IdentityUserService', () => {
spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers)); spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers));
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.getUsersByRolesWithCurrentUser([mockRoles[0].name]).then( service.getUsersByRolesWithCurrentUser([mockRoles[0].name]).then((res) => {
res => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res[0].id).toEqual('mock-user-id-1'); expect(res[0].id).toEqual('mock-user-id-1');
expect(res[0].username).toEqual('userName1'); expect(res[0].username).toEqual('userName1');
@@ -171,27 +161,24 @@ describe('IdentityUserService', () => {
expect(res[2].id).toEqual('mock-user-id-3'); expect(res[2].id).toEqual('mock-user-id-3');
expect(res[2].username).toEqual('userName3'); expect(res[2].username).toEqual('userName3');
done(); done();
} });
);
}); });
it('Should not fetch users by roles if error occurred', (done) => { it('Should not fetch users by roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse)); spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse));
service.getUsersByRolesWithCurrentUser([mockRoles[0].name]) service.getUsersByRolesWithCurrentUser([mockRoles[0].name]).catch((error) => {
.catch(
(error) => {
expect(error.status).toEqual(404); expect(error.status).toEqual(404);
expect(error.statusText).toEqual('Not Found'); expect(error.statusText).toEqual('Not Found');
expect(error.error).toEqual('Mock Error'); expect(error.error).toEqual('Mock Error');
done(); done();
} });
);
}); });
it('should fetch users by roles without current user', (done) => { it('should fetch users by roles without current user', (done) => {
@@ -199,86 +186,72 @@ describe('IdentityUserService', () => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
spyOn(service, 'getCurrentUserInfo').and.returnValue(mockIdentityUsers[0]); spyOn(service, 'getCurrentUserInfo').and.returnValue(mockIdentityUsers[0]);
service.getUsersByRolesWithoutCurrentUser([mockRoles[0].name]).then( service.getUsersByRolesWithoutCurrentUser([mockRoles[0].name]).then((res) => {
res => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res[0].id).toEqual('mock-user-id-2'); expect(res[0].id).toEqual('mock-user-id-2');
expect(res[0].username).toEqual('userName2'); expect(res[0].username).toEqual('userName2');
expect(res[1].id).toEqual('mock-user-id-3'); expect(res[1].id).toEqual('mock-user-id-3');
expect(res[1].username).toEqual('userName3'); expect(res[1].username).toEqual('userName3');
done(); done();
} });
);
}); });
it('should return true when user has access to an application', (done) => { it('should return true when user has access to an application', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles));
service.checkUserHasClientApp('user-id', 'app-name').subscribe( service.checkUserHasClientApp('user-id', 'app-name').subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeTruthy(); expect(res).toBeTruthy();
done(); done();
} });
);
}); });
it('should return false when user does not have access to an application', (done) => { it('should return false when user does not have access to an application', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkUserHasClientApp('user-id', 'app-name').subscribe( service.checkUserHasClientApp('user-id', 'app-name').subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeFalsy(); expect(res).toBeFalsy();
done(); done();
} });
);
}); });
it('should return true when user has any given application role', (done) => { it('should return true when user has any given application role', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles));
service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name] ).subscribe( service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name]).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeTruthy(); expect(res).toBeTruthy();
done(); done();
} });
);
}); });
it('should return false when user does not have any given application role', (done) => { it('should return false when user does not have any given application role', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name]).subscribe( service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name]).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeFalsy(); expect(res).toBeFalsy();
done(); done();
} });
);
}); });
it('should return true if user has given role', (done) => { it('should return true if user has given role', (done) => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-1']).subscribe( service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-1']).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeTruthy(); expect(res).toBeTruthy();
done(); done();
} });
);
}); });
it('should return false if user does not have given role', (done) => { it('should return false if user does not have given role', (done) => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-10']).subscribe( service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-10']).subscribe((res: boolean) => {
(res: boolean) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).toBeFalsy(); expect(res).toBeFalsy();
done(); done();
} });
);
}); });
it('should be able to query users based on query params (first & max params)', (done) => { it('should be able to query users based on query params (first & max params)', (done) => {
@@ -300,13 +273,13 @@ describe('IdentityUserService', () => {
it('Should not be able to query users if error occurred', (done) => { it('Should not be able to query users if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'queryUsers').and.returnValue(throwError(errorResponse)); spyOn(service, 'queryUsers').and.returnValue(throwError(errorResponse));
service.queryUsers({first: 0, max: 5}) service.queryUsers({ first: 0, max: 5 }).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not users'); fail('expected an error, not users');
}, },
@@ -330,13 +303,13 @@ describe('IdentityUserService', () => {
it('Should not able to create user if error occurred', (done) => { it('Should not able to create user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'createUser').and.returnValue(throwError(errorResponse)); spyOn(service, 'createUser').and.returnValue(throwError(errorResponse));
service.createUser(mockIdentityUser1) service.createUser(mockIdentityUser1).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to create user'); fail('expected an error, not to create user');
}, },
@@ -360,13 +333,13 @@ describe('IdentityUserService', () => {
it('Should not able to update user if error occurred', (done) => { it('Should not able to update user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'updateUser').and.returnValue(throwError(errorResponse)); spyOn(service, 'updateUser').and.returnValue(throwError(errorResponse));
service.updateUser('mock-id-2', mockIdentityUser2) service.updateUser('mock-id-2', mockIdentityUser2).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to update user'); fail('expected an error, not to update user');
}, },
@@ -390,13 +363,13 @@ describe('IdentityUserService', () => {
it('Should not able to delete user if error occurred', (done) => { it('Should not able to delete user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'deleteUser').and.returnValue(throwError(errorResponse)); spyOn(service, 'deleteUser').and.returnValue(throwError(errorResponse));
service.deleteUser('mock-user-id') service.deleteUser('mock-user-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to delete user'); fail('expected an error, not to delete user');
}, },
@@ -426,13 +399,13 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch involved groups if error occurred', (done) => { it('Should not be able to fetch involved groups if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getInvolvedGroups').and.returnValue(throwError(errorResponse)); spyOn(service, 'getInvolvedGroups').and.returnValue(throwError(errorResponse));
service.getInvolvedGroups('mock-user-id') service.getInvolvedGroups('mock-user-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not involved groups'); fail('expected an error, not involved groups');
}, },
@@ -456,13 +429,13 @@ describe('IdentityUserService', () => {
it('Should not able to join group if error occurred', (done) => { it('Should not able to join group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'joinGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'joinGroup').and.returnValue(throwError(errorResponse));
service.joinGroup(mockJoinGroupRequest) service.joinGroup(mockJoinGroupRequest).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to join group'); fail('expected an error, not to join group');
}, },
@@ -486,13 +459,13 @@ describe('IdentityUserService', () => {
it('Should not able to leave group if error occurred', (done) => { it('Should not able to leave group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'leaveGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'leaveGroup').and.returnValue(throwError(errorResponse));
service.leaveGroup('mock-user-id', 'mock-group-id') service.leaveGroup('mock-user-id', 'mock-group-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to leave group'); fail('expected an error, not to leave group');
}, },
@@ -524,13 +497,13 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch available roles based on user id if error occurred', (done) => { it('Should not be able to fetch available roles based on user id if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getAvailableRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getAvailableRoles').and.returnValue(throwError(errorResponse));
service.getAvailableRoles('mock-user-id') service.getAvailableRoles('mock-user-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not available roles'); fail('expected an error, not available roles');
}, },
@@ -562,13 +535,13 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch assigned roles based on user id if error occurred', (done) => { it('Should not be able to fetch assigned roles based on user id if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getAssignedRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getAssignedRoles').and.returnValue(throwError(errorResponse));
service.getAssignedRoles('mock-user-id') service.getAssignedRoles('mock-user-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not assigned roles'); fail('expected an error, not assigned roles');
}, },
@@ -600,13 +573,13 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch effective roles based on user id if error occurred', (done) => { it('Should not be able to fetch effective roles based on user id if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getEffectiveRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getEffectiveRoles').and.returnValue(throwError(errorResponse));
service.getEffectiveRoles('mock-user-id') service.getEffectiveRoles('mock-user-id').subscribe(
.subscribe(
() => { () => {
fail('expected an error, not effective roles'); fail('expected an error, not effective roles');
}, },
@@ -630,13 +603,13 @@ describe('IdentityUserService', () => {
it('Should not able to assign roles to the user if error occurred', (done) => { it('Should not able to assign roles to the user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'assignRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'assignRoles').and.returnValue(throwError(errorResponse));
service.assignRoles('mock-user-id', [mockIdentityRole]) service.assignRoles('mock-user-id', [mockIdentityRole]).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to assigen roles to the user'); fail('expected an error, not to assigen roles to the user');
}, },
@@ -660,13 +633,13 @@ describe('IdentityUserService', () => {
it('Should not able to remove roles if error occurred', (done) => { it('Should not able to remove roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'removeRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'removeRoles').and.returnValue(throwError(errorResponse));
service.removeRoles('mock-user-id', [mockIdentityRole]) service.removeRoles('mock-user-id', [mockIdentityRole]).subscribe(
.subscribe(
() => { () => {
fail('expected an error, not to remove roles'); fail('expected an error, not to remove roles');
}, },
@@ -24,7 +24,6 @@ import { OauthConfigModel } from '../models/oauth-config.model';
import { BaseAuthenticationService } from './base-authentication.service'; import { BaseAuthenticationService } from './base-authentication.service';
import { CookieService } from '../../common/services/cookie.service'; import { CookieService } from '../../common/services/cookie.service';
import { JwtHelperService } from './jwt-helper.service'; import { JwtHelperService } from './jwt-helper.service';
import { LogService } from '../../common/services/log.service';
import { AuthConfigService } from '../oidc/auth-config.service'; import { AuthConfigService } from '../oidc/auth-config.service';
import { AuthService } from '../oidc/auth.service'; import { AuthService } from '../oidc/auth.service';
import { Minimatch } from 'minimatch'; import { Minimatch } from 'minimatch';
@@ -34,18 +33,16 @@ import { HttpHeaders } from '@angular/common/http';
providedIn: 'root' providedIn: 'root'
}) })
export class OidcAuthenticationService extends BaseAuthenticationService { export class OidcAuthenticationService extends BaseAuthenticationService {
constructor( constructor(
appConfig: AppConfigService, appConfig: AppConfigService,
cookie: CookieService, cookie: CookieService,
logService: LogService,
private jwtHelperService: JwtHelperService, private jwtHelperService: JwtHelperService,
private authStorage: OAuthStorage, private authStorage: OAuthStorage,
private oauthService: OAuthService, private oauthService: OAuthService,
private readonly authConfig: AuthConfigService, private readonly authConfig: AuthConfigService,
private readonly auth: AuthService private readonly auth: AuthService
) { ) {
super(appConfig, cookie, logService); super(appConfig, cookie);
} }
isEcmLoggedIn(): boolean { isEcmLoggedIn(): boolean {
@@ -53,7 +50,6 @@ export class OidcAuthenticationService extends BaseAuthenticationService {
return this.isLoggedIn(); return this.isLoggedIn();
} }
return false; return false;
} }
isBpmLoggedIn(): boolean { isBpmLoggedIn(): boolean {
@@ -169,11 +165,13 @@ export class OidcAuthenticationService extends BaseAuthenticationService {
const oauth2 = this.appConfig.get<OauthConfigModel>(AppConfigValues.OAUTHCONFIG, null); const oauth2 = this.appConfig.get<OauthConfigModel>(AppConfigValues.OAUTHCONFIG, null);
if (Array.isArray(oauth2.publicUrls)) { if (Array.isArray(oauth2.publicUrls)) {
return oauth2.publicUrls.length > 0 && return (
oauth2.publicUrls.length > 0 &&
oauth2.publicUrls.some((urlPattern: string) => { oauth2.publicUrls.some((urlPattern: string) => {
const minimatch = new Minimatch(urlPattern); const minimatch = new Minimatch(urlPattern);
return minimatch.match(window.location.href); return minimatch.match(window.location.href);
}); })
);
} }
return false; return false;
} }
@@ -219,5 +217,4 @@ export class OidcAuthenticationService extends BaseAuthenticationService {
return undefined; return undefined;
} }
} }
} }
@@ -19,20 +19,16 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MaterialModule } from '../material.module'; import { MaterialModule } from '../material.module';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { CUSTOM_ELEMENTS_SCHEMA, Component } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA, Component } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
@Component({ @Component({
selector: 'adf-custom-container', selector: 'adf-custom-container',
template: ` template: `
<adf-buttons-action-menu> <adf-buttons-action-menu>
<button mat-menu-item (click)="assignValue()"> <button mat-menu-item (click)="assignValue()"><mat-icon>settings</mat-icon><span> Button </span></button>
<mat-icon>settings</mat-icon><span> Button </span>
</button>
</adf-buttons-action-menu> </adf-buttons-action-menu>
` `
}) })
export class CustomContainerComponent { export class CustomContainerComponent {
value: number; value: number;
assignValue() { assignValue() {
@@ -42,35 +38,21 @@ export class CustomContainerComponent {
@Component({ @Component({
selector: 'adf-custom-empty-container', selector: 'adf-custom-empty-container',
template: ` template: `<adf-buttons-action-menu></adf-buttons-action-menu>`
<adf-buttons-action-menu>
</adf-buttons-action-menu>
`
}) })
export class CustomEmptyContainerComponent { export class CustomEmptyContainerComponent {}
}
describe('ButtonsMenuComponent', () => { describe('ButtonsMenuComponent', () => {
describe('When Buttons are injected', () => { describe('When Buttons are injected', () => {
let fixture: ComponentFixture<CustomContainerComponent>; let fixture: ComponentFixture<CustomContainerComponent>;
let component: CustomContainerComponent; let component: CustomContainerComponent;
let element: HTMLElement; let element: HTMLElement;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, MaterialModule],
TranslateModule.forRoot(), declarations: [CustomContainerComponent],
CoreTestingModule, schemas: [CUSTOM_ELEMENTS_SCHEMA]
MaterialModule
],
declarations: [
CustomContainerComponent
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
}); });
fixture = TestBed.createComponent(CustomContainerComponent); fixture = TestBed.createComponent(CustomContainerComponent);
element = fixture.debugElement.nativeElement; element = fixture.debugElement.nativeElement;
@@ -111,17 +93,9 @@ describe('ButtonsMenuComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, MaterialModule],
TranslateModule.forRoot(), declarations: [CustomEmptyContainerComponent],
CoreTestingModule, schemas: [CUSTOM_ELEMENTS_SCHEMA]
MaterialModule
],
declarations: [
CustomEmptyContainerComponent
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
}); });
fixture = TestBed.createComponent(CustomEmptyContainerComponent); fixture = TestBed.createComponent(CustomEmptyContainerComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
@@ -21,7 +21,6 @@ import { CoreTestingModule } from '../../../testing/core.testing.module';
import { CardViewArrayItemComponent } from './card-view-arrayitem.component'; import { CardViewArrayItemComponent } from './card-view-arrayitem.component';
import { CardViewArrayItemModel, CardViewArrayItem } from '../../models/card-view-arrayitem.model'; import { CardViewArrayItemModel, CardViewArrayItem } from '../../models/card-view-arrayitem.model';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { CardViewUpdateService } from '../../services/card-view-update.service'; import { CardViewUpdateService } from '../../services/card-view-update.service';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@@ -52,7 +51,7 @@ describe('CardViewArrayItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [CoreTestingModule]
}); });
fixture = TestBed.createComponent(CardViewArrayItemComponent); fixture = TestBed.createComponent(CardViewArrayItemComponent);
service = TestBed.inject(CardViewUpdateService); service = TestBed.inject(CardViewUpdateService);
@@ -22,19 +22,14 @@ import { CardViewUpdateService } from '../../services/card-view-update.service';
import { CardViewBoolItemComponent } from './card-view-boolitem.component'; import { CardViewBoolItemComponent } from './card-view-boolitem.component';
import { CardViewBoolItemModel } from '../../models/card-view-boolitem.model'; import { CardViewBoolItemModel } from '../../models/card-view-boolitem.model';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('CardViewBoolItemComponent', () => { describe('CardViewBoolItemComponent', () => {
let fixture: ComponentFixture<CardViewBoolItemComponent>; let fixture: ComponentFixture<CardViewBoolItemComponent>;
let component: CardViewBoolItemComponent; let component: CardViewBoolItemComponent;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(CardViewBoolItemComponent); fixture = TestBed.createComponent(CardViewBoolItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -52,7 +47,6 @@ describe('CardViewBoolItemComponent', () => {
}); });
describe('Rendering', () => { describe('Rendering', () => {
it('should render the label and value if the property is editable', () => { it('should render the label and value if the property is editable', () => {
component.editable = true; component.editable = true;
component.property.editable = true; component.property.editable = true;
@@ -169,7 +163,6 @@ describe('CardViewBoolItemComponent', () => {
}); });
describe('Update', () => { describe('Update', () => {
beforeEach(() => { beforeEach(() => {
component.editable = true; component.editable = true;
component.property.editable = true; component.property.editable = true;
@@ -204,14 +197,12 @@ describe('CardViewBoolItemComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const property = { ...component.property }; const property = { ...component.property };
const disposableUpdate = cardViewUpdateService.itemUpdated$.subscribe( const disposableUpdate = cardViewUpdateService.itemUpdated$.subscribe((updateNotification) => {
(updateNotification) => {
expect(updateNotification.target).toEqual(property); expect(updateNotification.target).toEqual(property);
expect(updateNotification.changed).toEqual({ boolKey: true }); expect(updateNotification.changed).toEqual({ boolKey: true });
disposableUpdate.unsubscribe(); disposableUpdate.unsubscribe();
done(); done();
} });
);
const labelElement = fixture.debugElement.query(By.directive(MatCheckbox)).nativeElement.querySelector('label'); const labelElement = fixture.debugElement.query(By.directive(MatCheckbox)).nativeElement.querySelector('label');
labelElement.click(); labelElement.click();
@@ -24,6 +24,7 @@ import { CoreTestingModule } from '../../../testing/core.testing.module';
import { ClipboardService } from '../../../clipboard/clipboard.service'; import { ClipboardService } from '../../../clipboard/clipboard.service';
import { CardViewDatetimeItemModel } from '../../models/card-view-datetimeitem.model'; import { CardViewDatetimeItemModel } from '../../models/card-view-datetimeitem.model';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AppConfigService } from '../../../app-config/app-config.service';
import { MatDatetimepickerInputEvent } from '@mat-datetimepicker/core'; import { MatDatetimepickerInputEvent } from '@mat-datetimepicker/core';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@@ -33,11 +34,18 @@ describe('CardViewDateItemComponent', () => {
let loader: HarnessLoader; let loader: HarnessLoader;
let fixture: ComponentFixture<CardViewDateItemComponent>; let fixture: ComponentFixture<CardViewDateItemComponent>;
let component: CardViewDateItemComponent; let component: CardViewDateItemComponent;
let appConfigService: AppConfigService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [TranslateModule.forRoot(), CoreTestingModule]
}); });
appConfigService = TestBed.inject(AppConfigService);
appConfigService.config.dateValues = {
defaultDateFormat: 'shortDate',
defaultDateTimeFormat: 'M/d/yy, h:mm a',
defaultLocale: 'uk'
};
fixture = TestBed.createComponent(CardViewDateItemComponent); fixture = TestBed.createComponent(CardViewDateItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -21,10 +21,8 @@ import { CardViewKeyValuePairsItemModel } from '../../models/card-view-keyvaluep
import { CardViewKeyValuePairsItemComponent } from './card-view-keyvaluepairsitem.component'; import { CardViewKeyValuePairsItemComponent } from './card-view-keyvaluepairsitem.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { CardViewUpdateService } from '../../services/card-view-update.service'; import { CardViewUpdateService } from '../../services/card-view-update.service';
import { TranslateModule } from '@ngx-translate/core';
describe('CardViewKeyValuePairsItemComponent', () => { describe('CardViewKeyValuePairsItemComponent', () => {
let fixture: ComponentFixture<CardViewKeyValuePairsItemComponent>; let fixture: ComponentFixture<CardViewKeyValuePairsItemComponent>;
let component: CardViewKeyValuePairsItemComponent; let component: CardViewKeyValuePairsItemComponent;
let cardViewUpdateService: CardViewUpdateService; let cardViewUpdateService: CardViewUpdateService;
@@ -33,10 +31,7 @@ describe('CardViewKeyValuePairsItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(CardViewKeyValuePairsItemComponent); fixture = TestBed.createComponent(CardViewKeyValuePairsItemComponent);
cardViewUpdateService = TestBed.inject(CardViewUpdateService); cardViewUpdateService = TestBed.inject(CardViewUpdateService);
@@ -55,7 +50,6 @@ describe('CardViewKeyValuePairsItemComponent', () => {
}); });
describe('Component', () => { describe('Component', () => {
it('should render the label', () => { it('should render the label', () => {
fixture.detectChanges(); fixture.detectChanges();
@@ -22,7 +22,6 @@ import { CardViewMapItemModel } from '../../models/card-view-mapitem.model';
import { CardViewUpdateService } from '../../services/card-view-update.service'; import { CardViewUpdateService } from '../../services/card-view-update.service';
import { CardViewMapItemComponent } from './card-view-mapitem.component'; import { CardViewMapItemComponent } from './card-view-mapitem.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('CardViewMapItemComponent', () => { describe('CardViewMapItemComponent', () => {
let service: CardViewUpdateService; let service: CardViewUpdateService;
@@ -34,10 +33,7 @@ describe('CardViewMapItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(CardViewMapItemComponent); fixture = TestBed.createComponent(CardViewMapItemComponent);
service = TestBed.inject(CardViewUpdateService); service = TestBed.inject(CardViewUpdateService);
@@ -21,7 +21,6 @@ import { CardViewSelectItemModel } from '../../models/card-view-selectitem.model
import { CardViewSelectItemComponent } from './card-view-selectitem.component'; import { CardViewSelectItemComponent } from './card-view-selectitem.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
import { AppConfigService } from '../../../app-config/app-config.service'; import { AppConfigService } from '../../../app-config/app-config.service';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@@ -60,7 +59,7 @@ describe('CardViewSelectItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [CoreTestingModule]
}); });
fixture = TestBed.createComponent(CardViewSelectItemComponent); fixture = TestBed.createComponent(CardViewSelectItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { SelectFilterInputComponent } from './select-filter-input.component'; import { SelectFilterInputComponent } from './select-filter-input.component';
import { MatSelect } from '@angular/material/select'; import { MatSelect } from '@angular/material/select';
@@ -28,7 +27,7 @@ describe('SelectFilterInputComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule], imports: [CoreTestingModule],
providers: [MatSelect] providers: [MatSelect]
}); });
@@ -28,7 +28,6 @@ import { CardViewFloatItemModel } from '../../models/card-view-floatitem.model';
import { MatChipInputEvent, MatChipsModule } from '@angular/material/chips'; import { MatChipInputEvent, MatChipsModule } from '@angular/material/chips';
import { ClipboardService } from '../../../clipboard/clipboard.service'; import { ClipboardService } from '../../../clipboard/clipboard.service';
import { DebugElement, SimpleChange } from '@angular/core'; import { DebugElement, SimpleChange } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { CardViewItemValidator } from '../../interfaces/card-view-item-validator.interface'; import { CardViewItemValidator } from '../../interfaces/card-view-item-validator.interface';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@@ -113,7 +112,7 @@ describe('CardViewTextItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, MatChipsModule] imports: [CoreTestingModule, MatChipsModule]
}); });
fixture = TestBed.createComponent(CardViewTextItemComponent); fixture = TestBed.createComponent(CardViewTextItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -536,7 +535,9 @@ describe('CardViewTextItemComponent', () => {
component.ngOnChanges({}); component.ngOnChanges({});
loader = TestbedHarnessEnvironment.loader(fixture); loader = TestbedHarnessEnvironment.loader(fixture);
const inputHarness = await loader.getHarness(MatInputHarness.with({selector: `[data-automation-id="card-textitem-value-${component.property.key}"]`})); const inputHarness = await loader.getHarness(
MatInputHarness.with({ selector: `[data-automation-id="card-textitem-value-${component.property.key}"]` })
);
expect(component.isEditable).toBe(false); expect(component.isEditable).toBe(false);
expect(await inputHarness.isReadonly()).toBe(true); expect(await inputHarness.isReadonly()).toBe(true);
@@ -21,7 +21,6 @@ import { CardViewDateItemModel } from '../../models/card-view-dateitem.model';
import { CardViewTextItemModel } from '../../models/card-view-textitem.model'; import { CardViewTextItemModel } from '../../models/card-view-textitem.model';
import { CardViewComponent } from './card-view.component'; import { CardViewComponent } from './card-view.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { CardViewSelectItemModel } from '../../models/card-view-selectitem.model'; import { CardViewSelectItemModel } from '../../models/card-view-selectitem.model';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { CardViewSelectItemOption } from '../../interfaces/card-view-selectitem-properties.interface'; import { CardViewSelectItemOption } from '../../interfaces/card-view-selectitem-properties.interface';
@@ -38,7 +37,7 @@ describe('CardViewComponent', () => {
beforeEach(async () => { beforeEach(async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [CoreTestingModule]
}).compileComponents(); }).compileComponents();
fixture = TestBed.createComponent(CardViewComponent); fixture = TestBed.createComponent(CardViewComponent);
@@ -20,16 +20,11 @@ import { ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testin
import { ClipboardService } from './clipboard.service'; import { ClipboardService } from './clipboard.service';
import { ClipboardDirective } from './clipboard.directive'; import { ClipboardDirective } from './clipboard.directive';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
template: ` template: `
<button <button clipboard-notification="copy success" [adf-clipboard] [target]="ref">copy</button>
clipboard-notification="copy success"
[adf-clipboard] [target]="ref">
copy
</button>
<input #ref /> <input #ref />
` `
@@ -42,13 +37,8 @@ describe('ClipboardDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestTargetClipboardComponent]
CoreTestingModule
],
declarations: [
TestTargetClipboardComponent
]
}); });
fixture = TestBed.createComponent(TestTargetClipboardComponent); fixture = TestBed.createComponent(TestTargetClipboardComponent);
clipboardService = TestBed.inject(ClipboardService); clipboardService = TestBed.inject(ClipboardService);
@@ -73,13 +63,11 @@ describe('ClipboardDirective', () => {
}); });
describe('CopyClipboardDirective', () => { describe('CopyClipboardDirective', () => {
@Component({ @Component({
selector: 'adf-copy-conent-test-component', selector: 'adf-copy-conent-test-component',
template: `<span adf-clipboard="placeholder">{{ mockText }}</span>` template: `<span adf-clipboard="placeholder">{{ mockText }}</span>`
}) })
class TestCopyClipboardComponent { class TestCopyClipboardComponent {
mockText = 'text to copy'; mockText = 'text to copy';
placeholder = 'copy text'; placeholder = 'copy text';
@@ -92,27 +80,22 @@ describe('CopyClipboardDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestCopyClipboardComponent]
CoreTestingModule
],
declarations: [
TestCopyClipboardComponent
]
}); });
fixture = TestBed.createComponent(TestCopyClipboardComponent); fixture = TestBed.createComponent(TestCopyClipboardComponent);
element = fixture.debugElement.nativeElement; element = fixture.debugElement.nativeElement;
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should show tooltip when hover element', (() => { it('should show tooltip when hover element', () => {
const spanHTMLElement = element.querySelector<HTMLInputElement>('span'); const spanHTMLElement = element.querySelector<HTMLInputElement>('span');
spanHTMLElement.dispatchEvent(new Event('mouseenter')); spanHTMLElement.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('.adf-copy-tooltip')).not.toBeNull(); expect(fixture.debugElement.nativeElement.querySelector('.adf-copy-tooltip')).not.toBeNull();
})); });
it('should not show tooltip when element it is not hovered', (() => { it('should not show tooltip when element it is not hovered', () => {
const spanHTMLElement = element.querySelector<HTMLInputElement>('span'); const spanHTMLElement = element.querySelector<HTMLInputElement>('span');
spanHTMLElement.dispatchEvent(new Event('mouseenter')); spanHTMLElement.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges(); fixture.detectChanges();
@@ -121,7 +104,7 @@ describe('CopyClipboardDirective', () => {
spanHTMLElement.dispatchEvent(new Event('mouseleave')); spanHTMLElement.dispatchEvent(new Event('mouseleave'));
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('.adf-copy-tooltip')).toBeNull(); expect(fixture.debugElement.nativeElement.querySelector('.adf-copy-tooltip')).toBeNull();
})); });
it('should copy the content of element when click it', fakeAsync(() => { it('should copy the content of element when click it', fakeAsync(() => {
const spanHTMLElement = element.querySelector<HTMLInputElement>('span'); const spanHTMLElement = element.querySelector<HTMLInputElement>('span');
@@ -20,7 +20,6 @@ import { TestBed } from '@angular/core/testing';
import { ClipboardService } from './clipboard.service'; import { ClipboardService } from './clipboard.service';
import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBarModule } from '@angular/material/snack-bar';
import { CoreTestingModule } from '../testing'; import { CoreTestingModule } from '../testing';
import { TranslateModule } from '@ngx-translate/core';
describe('ClipboardService', () => { describe('ClipboardService', () => {
let clipboardService: ClipboardService; let clipboardService: ClipboardService;
@@ -29,11 +28,7 @@ describe('ClipboardService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, MatSnackBarModule]
TranslateModule.forRoot(),
CoreTestingModule,
MatSnackBarModule
]
}); });
clipboardService = TestBed.inject(ClipboardService); clipboardService = TestBed.inject(ClipboardService);
notificationService = TestBed.inject(NotificationService); notificationService = TestBed.inject(NotificationService);
@@ -61,8 +56,7 @@ describe('ClipboardService', () => {
clipboardService.copyToClipboard(inputElement); clipboardService.copyToClipboard(inputElement);
expect(inputElement.select).toHaveBeenCalledWith(); expect(inputElement.select).toHaveBeenCalledWith();
expect(inputElement.setSelectionRange) expect(inputElement.setSelectionRange).toHaveBeenCalledWith(0, inputElement.value.length);
.toHaveBeenCalledWith(0, inputElement.value.length);
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('some text'); expect(navigator.clipboard.writeText).toHaveBeenCalledWith('some text');
}); });
@@ -17,16 +17,11 @@
import { Injectable, Inject } from '@angular/core'; import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common'; import { DOCUMENT } from '@angular/common';
import { LogService } from '../common/services/log.service';
import { NotificationService } from '../notifications/services/notification.service'; import { NotificationService } from '../notifications/services/notification.service';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class ClipboardService { export class ClipboardService {
constructor(@Inject(DOCUMENT) private document: any, private notificationService: NotificationService) {}
constructor(
@Inject(DOCUMENT) private document: any,
private logService: LogService,
private notificationService: NotificationService) { }
/** /**
* Checks if the target element can have its text copied. * Checks if the target element can have its text copied.
@@ -58,9 +53,7 @@ export class ClipboardService {
this.document.execCommand('copy'); this.document.execCommand('copy');
} }
this.notify(message); this.notify(message);
} catch (error) { } catch {}
this.logService.error(error);
}
} }
} }
@@ -76,16 +69,14 @@ export class ClipboardService {
navigator.clipboard.writeText(content); navigator.clipboard.writeText(content);
} else { } else {
document.addEventListener('copy', (e: ClipboardEvent) => { document.addEventListener('copy', (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', (content)); e.clipboardData.setData('text/plain', content);
e.preventDefault(); e.preventDefault();
document.removeEventListener('copy', null); document.removeEventListener('copy', null);
}); });
document.execCommand('copy'); document.execCommand('copy');
} }
this.notify(message); this.notify(message);
} catch (error) { } catch {}
this.logService.error(error);
}
} }
private notify(message) { private notify(message) {
@@ -93,5 +84,4 @@ export class ClipboardService {
this.notificationService.openSnackMessage(message); this.notificationService.openSnackMessage(message);
} }
} }
} }
@@ -20,28 +20,18 @@ import { CommentModel } from '../../models/comment.model';
import { CommentListComponent } from './comment-list.component'; import { CommentListComponent } from './comment-list.component';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { commentUserNoPictureDefined, commentUserPictureDefined, mockCommentOne, testUser } from './mocks/comment-list.mock';
import {
commentUserNoPictureDefined,
commentUserPictureDefined,
mockCommentOne,
testUser
} from './mocks/comment-list.mock';
import { CommentListServiceMock } from './mocks/comment-list.service.mock'; import { CommentListServiceMock } from './mocks/comment-list.service.mock';
import { ADF_COMMENTS_SERVICE } from '../interfaces/comments.token'; import { ADF_COMMENTS_SERVICE } from '../interfaces/comments.token';
describe('CommentListComponent', () => { describe('CommentListComponent', () => {
let commentList: CommentListComponent; let commentList: CommentListComponent;
let fixture: ComponentFixture<CommentListComponent>; let fixture: ComponentFixture<CommentListComponent>;
let element: HTMLElement; let element: HTMLElement;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ {
provide: ADF_COMMENTS_SERVICE, provide: ADF_COMMENTS_SERVICE,
@@ -123,7 +113,7 @@ describe('CommentListComponent', () => {
it('comment date time should start with Yesterday when comment date is yesterday', async () => { it('comment date time should start with Yesterday when comment date is yesterday', async () => {
const commentOld = new CommentModel(mockCommentOne); const commentOld = new CommentModel(mockCommentOne);
commentOld.created = new Date((Date.now() - 24 * 3600 * 1000)); commentOld.created = new Date(Date.now() - 24 * 3600 * 1000);
commentList.comments = [commentOld]; commentList.comments = [commentOld];
fixture.detectChanges(); fixture.detectChanges();
@@ -135,7 +125,7 @@ describe('CommentListComponent', () => {
it('comment date time should not start with Today/Yesterday when comment date is before yesterday', async () => { it('comment date time should not start with Today/Yesterday when comment date is before yesterday', async () => {
const commentOld = new CommentModel(mockCommentOne); const commentOld = new CommentModel(mockCommentOne);
commentOld.created = new Date((Date.now() - 24 * 3600 * 1000 * 2)); commentOld.created = new Date(Date.now() - 24 * 3600 * 1000 * 2);
commentList.comments = [commentOld]; commentList.comments = [commentOld];
fixture.detectChanges(); fixture.detectChanges();
@@ -19,7 +19,6 @@ import { SimpleChange } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CommentsComponent } from './comments.component'; import { CommentsComponent } from './comments.component';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { CommentsServiceMock, commentsResponseMock } from './mocks/comments.service.mock'; import { CommentsServiceMock, commentsResponseMock } from './mocks/comments.service.mock';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { ADF_COMMENTS_SERVICE } from './interfaces/comments.token'; import { ADF_COMMENTS_SERVICE } from './interfaces/comments.token';
@@ -34,10 +33,7 @@ describe('CommentsComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ {
provide: ADF_COMMENTS_SERVICE, provide: ADF_COMMENTS_SERVICE,
@@ -157,7 +153,6 @@ describe('CommentsComponent', () => {
}); });
describe('Add comment', () => { describe('Add comment', () => {
beforeEach(() => { beforeEach(() => {
component.id = '123'; component.id = '123';
fixture.detectChanges(); fixture.detectChanges();
@@ -18,19 +18,13 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { UserPreferencesService } from './user-preferences.service'; import { UserPreferencesService } from './user-preferences.service';
import { TranslateModule } from '@ngx-translate/core';
import { CoreModule } from '../../core.module';
describe('DirectionalityConfigService', () => { describe('DirectionalityConfigService', () => {
let userPreferencesService: UserPreferencesService; let userPreferencesService: UserPreferencesService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreModule.forRoot(),
CoreTestingModule
]
}); });
userPreferencesService = TestBed.inject(UserPreferencesService); userPreferencesService = TestBed.inject(UserPreferencesService);
}); });
@@ -22,11 +22,13 @@ import { AppConfigService, AppConfigValues } from '../../app-config/app-config.s
import { logLevels, LogLevelsEnum } from '../models/log-levels.model'; import { logLevels, LogLevelsEnum } from '../models/log-levels.model';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
/**
* @deprecated This service is deprecated and will be removed in future versions.
*/
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class LogService { export class LogService {
get currentLogLevel() { get currentLogLevel() {
const configLevel: string = this.appConfig.get<string>(AppConfigValues.LOG_LEVEL); const configLevel: string = this.appConfig.get<string>(AppConfigValues.LOG_LEVEL);
@@ -51,7 +53,6 @@ export class LogService {
*/ */
error(message?: any, ...optionalParams: any[]) { error(message?: any, ...optionalParams: any[]) {
if (this.currentLogLevel >= LogLevelsEnum.ERROR) { if (this.currentLogLevel >= LogLevelsEnum.ERROR) {
this.messageBus(message, 'ERROR'); this.messageBus(message, 'ERROR');
console.error(message, ...optionalParams); console.error(message, ...optionalParams);
@@ -66,7 +67,6 @@ export class LogService {
*/ */
debug(message?: any, ...optionalParams: any[]) { debug(message?: any, ...optionalParams: any[]) {
if (this.currentLogLevel >= LogLevelsEnum.DEBUG) { if (this.currentLogLevel >= LogLevelsEnum.DEBUG) {
this.messageBus(message, 'DEBUG'); this.messageBus(message, 'DEBUG');
console.debug(message, ...optionalParams); console.debug(message, ...optionalParams);
@@ -81,7 +81,6 @@ export class LogService {
*/ */
info(message?: any, ...optionalParams: any[]) { info(message?: any, ...optionalParams: any[]) {
if (this.currentLogLevel >= LogLevelsEnum.INFO) { if (this.currentLogLevel >= LogLevelsEnum.INFO) {
this.messageBus(message, 'INFO'); this.messageBus(message, 'INFO');
console.info(message, ...optionalParams); console.info(message, ...optionalParams);
@@ -96,7 +95,6 @@ export class LogService {
*/ */
log(message?: any, ...optionalParams: any[]) { log(message?: any, ...optionalParams: any[]) {
if (this.currentLogLevel >= LogLevelsEnum.TRACE) { if (this.currentLogLevel >= LogLevelsEnum.TRACE) {
this.messageBus(message, 'LOG'); this.messageBus(message, 'LOG');
console.log(message, ...optionalParams); console.log(message, ...optionalParams);
@@ -111,7 +109,6 @@ export class LogService {
*/ */
trace(message?: any, ...optionalParams: any[]) { trace(message?: any, ...optionalParams: any[]) {
if (this.currentLogLevel >= LogLevelsEnum.TRACE) { if (this.currentLogLevel >= LogLevelsEnum.TRACE) {
this.messageBus(message, 'TRACE'); this.messageBus(message, 'TRACE');
console.trace(message, ...optionalParams); console.trace(message, ...optionalParams);
@@ -126,7 +123,6 @@ export class LogService {
*/ */
warn(message?: any, ...optionalParams: any[]) { warn(message?: any, ...optionalParams: any[]) {
if (this.currentLogLevel >= LogLevelsEnum.WARN) { if (this.currentLogLevel >= LogLevelsEnum.WARN) {
this.messageBus(message, 'WARN'); this.messageBus(message, 'WARN');
console.warn(message, ...optionalParams); console.warn(message, ...optionalParams);
@@ -142,7 +138,6 @@ export class LogService {
*/ */
assert(test?: boolean, message?: string, ...optionalParams: any[]) { assert(test?: boolean, message?: string, ...optionalParams: any[]) {
if (this.currentLogLevel !== LogLevelsEnum.SILENT) { if (this.currentLogLevel !== LogLevelsEnum.SILENT) {
this.messageBus(message, 'ASSERT'); this.messageBus(message, 'ASSERT');
console.assert(test, message, ...optionalParams); console.assert(test, message, ...optionalParams);
@@ -20,10 +20,8 @@ import { AppConfigService } from '../../app-config/app-config.service';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { AppConfigServiceMock } from '../mock/app-config.service.mock'; import { AppConfigServiceMock } from '../mock/app-config.service.mock';
import { TranslateModule } from '@ngx-translate/core';
describe('StorageService', () => { describe('StorageService', () => {
let storage: StorageService; let storage: StorageService;
let appConfig: AppConfigServiceMock; let appConfig: AppConfigServiceMock;
const key = 'test_key'; const key = 'test_key';
@@ -32,9 +30,7 @@ describe('StorageService', () => {
describe('StorageService', () => { describe('StorageService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
CoreTestingModule
]
}); });
appConfig = TestBed.inject(AppConfigService); appConfig = TestBed.inject(AppConfigService);
appConfig.config = { appConfig.config = {
@@ -78,10 +74,7 @@ describe('StorageService', () => {
describe('StorageService', () => { describe('StorageService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
appConfig = TestBed.inject(AppConfigService); appConfig = TestBed.inject(AppConfigService);
@@ -16,7 +16,7 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { TranslateService, TranslateModule } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.service';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
import { UserPreferencesService, UserPreferenceValues } from '../../common/services/user-preferences.service'; import { UserPreferencesService, UserPreferenceValues } from '../../common/services/user-preferences.service';
@@ -26,7 +26,6 @@ import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { AlfrescoApiServiceMock } from '../../mock'; import { AlfrescoApiServiceMock } from '../../mock';
describe('UserPreferencesService', () => { describe('UserPreferencesService', () => {
const supportedPaginationSize = [5, 10, 15, 20]; const supportedPaginationSize = [5, 10, 15, 20];
let preferences: UserPreferencesService; let preferences: UserPreferencesService;
let storage: StorageService; let storage: StorageService;
@@ -36,10 +35,7 @@ describe('UserPreferencesService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
appConfig = TestBed.inject(AppConfigService); appConfig = TestBed.inject(AppConfigService);
appConfig.config = { appConfig.config = {
@@ -20,7 +20,6 @@ import { CoreTestingModule } from '../testing/core.testing.module';
import { ContextMenuOverlayService } from './context-menu-overlay.service'; import { ContextMenuOverlayService } from './context-menu-overlay.service';
import { Injector } from '@angular/core'; import { Injector } from '@angular/core';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
describe('ContextMenuOverlayService', () => { describe('ContextMenuOverlayService', () => {
let contextMenuOverlayService: ContextMenuOverlayService; let contextMenuOverlayService: ContextMenuOverlayService;
@@ -36,10 +35,7 @@ describe('ContextMenuOverlayService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [Overlay] providers: [Overlay]
}); });
overlay = TestBed.inject(Overlay); overlay = TestBed.inject(Overlay);
@@ -48,10 +44,7 @@ describe('ContextMenuOverlayService', () => {
describe('Overlay', () => { describe('Overlay', () => {
beforeEach(() => { beforeEach(() => {
contextMenuOverlayService = new ContextMenuOverlayService( contextMenuOverlayService = new ContextMenuOverlayService(injector, overlay);
injector,
overlay
);
}); });
it('should create a custom overlay', () => { it('should create a custom overlay', () => {
@@ -19,16 +19,13 @@ import { Component } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing'; import { TestBed, ComponentFixture } from '@angular/core/testing';
import { ContextMenuModule } from './context-menu.module'; import { ContextMenuModule } from './context-menu.module';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { MatIconHarness } from '@angular/material/icon/testing'; import { MatIconHarness } from '@angular/material/icon/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
template: ` template: ` <div id="target" [adf-context-menu]="actions" [adf-context-menu-enabled]="true"></div> `
<div id="target" [adf-context-menu]="actions" [adf-context-menu-enabled]="true"></div>
`
}) })
class TestComponent { class TestComponent {
actions; actions;
@@ -83,14 +80,8 @@ describe('ContextMenuDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, ContextMenuModule],
TranslateModule.forRoot(), declarations: [TestComponent]
CoreTestingModule,
ContextMenuModule
],
declarations: [
TestComponent
]
}); });
fixture = TestBed.createComponent(TestComponent); fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.actions = actions; fixture.componentInstance.actions = actions;
@@ -118,7 +109,9 @@ describe('ContextMenuDirective', () => {
it('should reset DOM element reference on Escape event', () => { it('should reset DOM element reference on Escape event', () => {
const event = new KeyboardEvent('keydown', { const event = new KeyboardEvent('keydown', {
bubbles : true, cancelable : true, key : 'Escape' bubbles: true,
cancelable: true,
key: 'Escape'
}); });
document.querySelector('.cdk-overlay-backdrop')?.dispatchEvent(event); document.querySelector('.cdk-overlay-backdrop')?.dispatchEvent(event);
@@ -169,9 +162,16 @@ describe('ContextMenuDirective', () => {
}); });
it('should not render item icon if not set', async () => { it('should not render item icon if not set', async () => {
expect((await loader.getAllHarnesses(MatIconHarness.with({ expect(
ancestor: 'adf-context-menu', name: 'Action 1' (
}))).length).toBe(0); await loader.getAllHarnesses(
MatIconHarness.with({
ancestor: 'adf-context-menu',
name: 'Action 1'
})
)
).length
).toBe(0);
}); });
}); });
}); });
@@ -21,7 +21,6 @@ import { DataColumn } from '../../data/data-column.model';
import { Observable, Subject } from 'rxjs'; import { Observable, Subject } from 'rxjs';
import { MatMenuTrigger } from '@angular/material/menu'; import { MatMenuTrigger } from '@angular/material/menu';
import { CoreTestingModule } from '../../../testing'; import { CoreTestingModule } from '../../../testing';
import { TranslateModule } from '@ngx-translate/core';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
@@ -41,10 +40,7 @@ describe('ColumnsSelectorComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
declarations: [ColumnsSelectorComponent] declarations: [ColumnsSelectorComponent]
}).compileComponents(); }).compileComponents();
@@ -52,32 +48,38 @@ describe('ColumnsSelectorComponent', () => {
loader = TestbedHarnessEnvironment.loader(fixture); loader = TestbedHarnessEnvironment.loader(fixture);
component = fixture.componentInstance; component = fixture.componentInstance;
inputColumns = [{ inputColumns = [
{
id: 'id0', id: 'id0',
key: 'key0', key: 'key0',
title: 'title0', title: 'title0',
type: 'text' type: 'text'
}, { },
{
id: 'id1', id: 'id1',
key: 'key1', key: 'key1',
title: 'title1', title: 'title1',
type: 'text' type: 'text'
}, { },
{
id: 'id2', id: 'id2',
key: 'key2', key: 'key2',
title: 'title2', title: 'title2',
type: 'text' type: 'text'
}, { },
{
id: 'id3', id: 'id3',
key: 'NoTitle', key: 'NoTitle',
type: 'text' type: 'text'
}, { },
{
id: 'id4', id: 'id4',
key: 'IsHidden', key: 'IsHidden',
type: 'text', type: 'text',
title: 'title4', title: 'title4',
isHidden: true isHidden: true
}]; }
];
mainMenuTrigger = { mainMenuTrigger = {
menuOpened: menuOpenedTrigger.asObservable(), menuOpened: menuOpenedTrigger.asObservable(),
@@ -114,13 +116,13 @@ describe('ColumnsSelectorComponent', () => {
const checkboxes = await loader.getAllHarnesses(MatCheckboxHarness); const checkboxes = await loader.getAllHarnesses(MatCheckboxHarness);
const inputColumnsWithTitle = inputColumns.filter(column => !!column.title); const inputColumnsWithTitle = inputColumns.filter((column) => !!column.title);
expect(checkboxes.length).toBe(inputColumnsWithTitle.length); expect(checkboxes.length).toBe(inputColumnsWithTitle.length);
for await (const checkbox of checkboxes) { for await (const checkbox of checkboxes) {
const checkboxLabel = await checkbox.getLabelText(); const checkboxLabel = await checkbox.getLabelText();
const inputColumn = inputColumnsWithTitle.find(inputColumnWithTitle => inputColumnWithTitle.title === checkboxLabel); const inputColumn = inputColumnsWithTitle.find((inputColumnWithTitle) => inputColumnWithTitle.title === checkboxLabel);
expect(inputColumn).toBeTruthy('Should have all columns with title'); expect(inputColumn).toBeTruthy('Should have all columns with title');
} }
}); });
@@ -149,14 +151,13 @@ describe('ColumnsSelectorComponent', () => {
const firstColumnCheckbox = await loader.getHarness(MatCheckboxHarness); const firstColumnCheckbox = await loader.getHarness(MatCheckboxHarness);
const checkBoxName = await firstColumnCheckbox.getLabelText(); const checkBoxName = await firstColumnCheckbox.getLabelText();
const toggledColumnItem = component.columnItems.find(item => item.title === checkBoxName); const toggledColumnItem = component.columnItems.find((item) => item.title === checkBoxName);
expect(toggledColumnItem.isHidden).toBeFalsy(); expect(toggledColumnItem.isHidden).toBeFalsy();
await firstColumnCheckbox.toggle(); await firstColumnCheckbox.toggle();
expect(toggledColumnItem.isHidden).toBe(true); expect(toggledColumnItem.isHidden).toBe(true);
}); });
describe('checkboxes', () => { describe('checkboxes', () => {
it('should have set proper default state', async () => { it('should have set proper default state', async () => {
menuOpenedTrigger.next(); menuOpenedTrigger.next();
@@ -27,7 +27,6 @@ import { DataTableComponent, ShowHeaderMode } from './datatable.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { DataColumnListComponent } from '../../data-column/data-column-list.component'; import { DataColumnListComponent } from '../../data-column/data-column-list.component';
import { DataColumnComponent } from '../../data-column/data-column.component'; import { DataColumnComponent } from '../../data-column/data-column.component';
import { TranslateModule } from '@ngx-translate/core';
import { domSanitizerMock } from '../../../mock/dom-sanitizer-mock'; import { domSanitizerMock } from '../../../mock/dom-sanitizer-mock';
import { matIconRegistryMock } from '../../../mock/mat-icon-registry-mock'; import { matIconRegistryMock } from '../../../mock/mat-icon-registry-mock';
import { CdkDrag, CdkDragDrop, CdkDropList } from '@angular/cdk/drag-drop'; import { CdkDrag, CdkDragDrop, CdkDropList } from '@angular/cdk/drag-drop';
@@ -140,7 +139,7 @@ describe('DataTable', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule], imports: [CoreTestingModule],
declarations: [CustomColumnHeaderComponent] declarations: [CustomColumnHeaderComponent]
}); });
fixture = TestBed.createComponent(DataTableComponent); fixture = TestBed.createComponent(DataTableComponent);
@@ -1280,7 +1279,7 @@ describe('Accesibility', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule], imports: [CoreTestingModule],
declarations: [CustomColumnTemplateComponent], declarations: [CustomColumnTemplateComponent],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}); });
@@ -1483,7 +1482,7 @@ describe('Drag&Drop column header', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule], imports: [CoreTestingModule],
declarations: [CustomColumnTemplateComponent], declarations: [CustomColumnTemplateComponent],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}); });
@@ -1584,7 +1583,7 @@ describe('Show/hide columns', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule], imports: [CoreTestingModule],
declarations: [CustomColumnTemplateComponent], declarations: [CustomColumnTemplateComponent],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}); });
@@ -1691,7 +1690,7 @@ describe('Column Resizing', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule], imports: [CoreTestingModule],
declarations: [CustomColumnTemplateComponent], declarations: [CustomColumnTemplateComponent],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}); });
@@ -18,17 +18,13 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { EmptyListComponent } from './empty-list.component'; import { EmptyListComponent } from './empty-list.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('EmptyListComponentComponent', () => { describe('EmptyListComponentComponent', () => {
let fixture: ComponentFixture<EmptyListComponent>; let fixture: ComponentFixture<EmptyListComponent>;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(EmptyListComponent); fixture = TestBed.createComponent(EmptyListComponent);
}); });
@@ -20,7 +20,6 @@ import { ObjectDataTableAdapter } from '../../data/object-datatable-adapter';
import { ObjectDataColumn } from '../../data/object-datacolumn.model'; import { ObjectDataColumn } from '../../data/object-datacolumn.model';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { JsonCellComponent } from './json-cell.component'; import { JsonCellComponent } from './json-cell.component';
import { TranslateModule } from '@ngx-translate/core';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { MatButtonHarness } from '@angular/material/button/testing'; import { MatButtonHarness } from '@angular/material/button/testing';
@@ -35,7 +34,7 @@ describe('JsonCellComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [CoreTestingModule]
}); });
fixture = TestBed.createComponent(JsonCellComponent); fixture = TestBed.createComponent(JsonCellComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -17,16 +17,12 @@
import { DataColumnComponent } from './data-column.component'; import { DataColumnComponent } from './data-column.component';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
describe('DataColumnListComponent', () => { describe('DataColumnListComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
}); });
@@ -19,20 +19,15 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { DataTableComponent } from '../components/datatable/datatable.component'; import { DataTableComponent } from '../components/datatable/datatable.component';
import { HeaderFilterTemplateDirective } from './header-filter-template.directive'; import { HeaderFilterTemplateDirective } from './header-filter-template.directive';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('HeaderFilterTemplateDirective', () => { describe('HeaderFilterTemplateDirective', () => {
let fixture: ComponentFixture<DataTableComponent>; let fixture: ComponentFixture<DataTableComponent>;
let dataTable: DataTableComponent; let dataTable: DataTableComponent;
let directive: HeaderFilterTemplateDirective; let directive: HeaderFilterTemplateDirective;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(DataTableComponent); fixture = TestBed.createComponent(DataTableComponent);
dataTable = fixture.componentInstance; dataTable = fixture.componentInstance;
@@ -19,20 +19,15 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { DataTableComponent } from '../components/datatable/datatable.component'; import { DataTableComponent } from '../components/datatable/datatable.component';
import { LoadingContentTemplateDirective } from './loading-template.directive'; import { LoadingContentTemplateDirective } from './loading-template.directive';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('LoadingContentTemplateDirective', () => { describe('LoadingContentTemplateDirective', () => {
let fixture: ComponentFixture<DataTableComponent>; let fixture: ComponentFixture<DataTableComponent>;
let dataTable: DataTableComponent; let dataTable: DataTableComponent;
let directive: LoadingContentTemplateDirective; let directive: LoadingContentTemplateDirective;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(DataTableComponent); fixture = TestBed.createComponent(DataTableComponent);
dataTable = fixture.componentInstance; dataTable = fixture.componentInstance;
@@ -19,20 +19,15 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { DataTableComponent } from '../components/datatable/datatable.component'; import { DataTableComponent } from '../components/datatable/datatable.component';
import { NoContentTemplateDirective } from './no-content-template.directive'; import { NoContentTemplateDirective } from './no-content-template.directive';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('NoContentTemplateDirective', () => { describe('NoContentTemplateDirective', () => {
let fixture: ComponentFixture<DataTableComponent>; let fixture: ComponentFixture<DataTableComponent>;
let dataTable: DataTableComponent; let dataTable: DataTableComponent;
let directive: NoContentTemplateDirective; let directive: NoContentTemplateDirective;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(DataTableComponent); fixture = TestBed.createComponent(DataTableComponent);
dataTable = fixture.componentInstance; dataTable = fixture.componentInstance;
@@ -19,20 +19,15 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { DataTableComponent } from '../components/datatable/datatable.component'; import { DataTableComponent } from '../components/datatable/datatable.component';
import { NoPermissionTemplateDirective } from './no-permission-template.directive'; import { NoPermissionTemplateDirective } from './no-permission-template.directive';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('NoPermissionTemplateDirective', () => { describe('NoPermissionTemplateDirective', () => {
let fixture: ComponentFixture<DataTableComponent>; let fixture: ComponentFixture<DataTableComponent>;
let dataTable: DataTableComponent; let dataTable: DataTableComponent;
let directive: NoPermissionTemplateDirective; let directive: NoPermissionTemplateDirective;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(DataTableComponent); fixture = TestBed.createComponent(DataTableComponent);
dataTable = fixture.componentInstance; dataTable = fixture.componentInstance;
@@ -21,7 +21,6 @@ import { By } from '@angular/platform-browser';
import { HighlightTransformService } from '../common/services/highlight-transform.service'; import { HighlightTransformService } from '../common/services/highlight-transform.service';
import { HighlightDirective } from './highlight.directive'; import { HighlightDirective } from './highlight.directive';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
/* spellchecker: disable */ /* spellchecker: disable */
const template: string = ` const template: string = `
@@ -41,19 +40,13 @@ class TestComponent {
} }
describe('HighlightDirective', () => { describe('HighlightDirective', () => {
let fixture: ComponentFixture<TestComponent>; let fixture: ComponentFixture<TestComponent>;
let component: TestComponent; let component: TestComponent;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestComponent]
CoreTestingModule
],
declarations: [
TestComponent
]
}); });
fixture = TestBed.createComponent(TestComponent); fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -77,8 +70,12 @@ describe('HighlightDirective', () => {
const containerElement2 = fixture.debugElement.query(By.css('#innerDiv14')); const containerElement2 = fixture.debugElement.query(By.css('#innerDiv14'));
expect(containerElement1).not.toBeNull(); expect(containerElement1).not.toBeNull();
expect(containerElement2).not.toBeNull(); expect(containerElement2).not.toBeNull();
expect(containerElement1.nativeElement.innerHTML).toBe('Lorem ipsum <span class="highlight-for-free-willy">salana-eyong-aysis</span> dolor sit amet'); expect(containerElement1.nativeElement.innerHTML).toBe(
expect(containerElement2.nativeElement.innerHTML).toBe('sed do eiusmod <span class="highlight-for-free-willy">salana-eyong-aysis</span> tempor incididunt'); 'Lorem ipsum <span class="highlight-for-free-willy">salana-eyong-aysis</span> dolor sit amet'
);
expect(containerElement2.nativeElement.innerHTML).toBe(
'sed do eiusmod <span class="highlight-for-free-willy">salana-eyong-aysis</span> tempor incididunt'
);
}); });
it('should NOT replace the searched text in an element without the proper selector class', () => { it('should NOT replace the searched text in an element without the proper selector class', () => {
@@ -23,12 +23,9 @@ import { AuthenticationService } from '../auth/services/authentication.service';
import { AppConfigService } from '../app-config/app-config.service'; import { AppConfigService } from '../app-config/app-config.service';
import { LogoutDirective } from './logout.directive'; import { LogoutDirective } from './logout.directive';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('LogoutDirective', () => { describe('LogoutDirective', () => {
describe('No input', () => { describe('No input', () => {
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
template: '<button adf-logout></button>' template: '<button adf-logout></button>'
@@ -45,13 +42,8 @@ describe('LogoutDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestComponent]
CoreTestingModule
],
declarations: [
TestComponent
]
}); });
router = TestBed.inject(Router); router = TestBed.inject(Router);
authService = TestBed.inject(AuthenticationService); authService = TestBed.inject(AuthenticationService);
@@ -110,7 +102,6 @@ describe('LogoutDirective', () => {
}); });
describe('redirectUri', () => { describe('redirectUri', () => {
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
template: '<button adf-logout redirectUri="/myCustomUri"></button>' template: '<button adf-logout redirectUri="/myCustomUri"></button>'
@@ -126,13 +117,8 @@ describe('LogoutDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestComponent]
CoreTestingModule
],
declarations: [
TestComponent
]
}); });
router = TestBed.inject(Router); router = TestBed.inject(Router);
authService = TestBed.inject(AuthenticationService); authService = TestBed.inject(AuthenticationService);
@@ -153,7 +139,6 @@ describe('LogoutDirective', () => {
}); });
describe('enableRedirect', () => { describe('enableRedirect', () => {
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
template: '<button adf-logout [enableRedirect]="false"></button>' template: '<button adf-logout [enableRedirect]="false"></button>'
@@ -169,13 +154,8 @@ describe('LogoutDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestComponent]
CoreTestingModule
],
declarations: [
TestComponent
]
}); });
router = TestBed.inject(Router); router = TestBed.inject(Router);
authService = TestBed.inject(AuthenticationService); authService = TestBed.inject(AuthenticationService);
@@ -192,6 +172,5 @@ describe('LogoutDirective', () => {
expect(authService.logout).toHaveBeenCalled(); expect(authService.logout).toHaveBeenCalled();
expect(router.navigate).not.toHaveBeenCalled(); expect(router.navigate).not.toHaveBeenCalled();
}); });
}); });
}); });
@@ -16,24 +16,28 @@
*/ */
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { Chip, CoreTestingModule, DynamicChipListComponent } from '@alfresco/adf-core'; import { Chip, CoreTestingModule, DynamicChipListComponent } from '@alfresco/adf-core';
import { SimpleChange } from '@angular/core'; import { SimpleChange } from '@angular/core';
describe('DynamicChipListComponent', () => { describe('DynamicChipListComponent', () => {
let chips: Chip[] = [{ let chips: Chip[] = [
{
name: 'test1', name: 'test1',
id: '0ee933fa-57fc-4587-8a77-b787e814f1d2' id: '0ee933fa-57fc-4587-8a77-b787e814f1d2'
}, { },
{
name: 'test2', name: 'test2',
id: 'fcb92659-1f10-41b4-9b17-851b72a3b597' id: 'fcb92659-1f10-41b4-9b17-851b72a3b597'
}, { },
{
name: 'test3', name: 'test3',
id: 'fb4213c0-729d-466c-9a6c-ee2e937273bf' id: 'fb4213c0-729d-466c-9a6c-ee2e937273bf'
}, { },
{
name: 'test4', name: 'test4',
id: 'as4213c0-729d-466c-9a6c-ee2e937273as' id: 'as4213c0-729d-466c-9a6c-ee2e937273as'
}]; }
];
let component: DynamicChipListComponent; let component: DynamicChipListComponent;
let fixture: ComponentFixture<DynamicChipListComponent>; let fixture: ComponentFixture<DynamicChipListComponent>;
let element: HTMLElement; let element: HTMLElement;
@@ -59,10 +63,7 @@ describe('DynamicChipListComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
const resizeObserverSpy = spyOn(window, 'ResizeObserver').and.callThrough(); const resizeObserverSpy = spyOn(window, 'ResizeObserver').and.callThrough();
fixture = TestBed.createComponent(DynamicChipListComponent); fixture = TestBed.createComponent(DynamicChipListComponent);
@@ -210,10 +211,12 @@ describe('DynamicChipListComponent', () => {
})); }));
it('should not render view more button when chip takes more than one line and there are no more chips', fakeAsync(() => { it('should not render view more button when chip takes more than one line and there are no more chips', fakeAsync(() => {
renderChips([{ renderChips([
{
name: 'VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag', name: 'VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag',
id: '0ee933fa-57fc-4587-8a77-b787e814f1d2' id: '0ee933fa-57fc-4587-8a77-b787e814f1d2'
}]); }
]);
component.ngOnChanges({ component.ngOnChanges({
chips: new SimpleChange(undefined, component.chips, true) chips: new SimpleChange(undefined, component.chips, true)
}); });
@@ -225,13 +228,16 @@ describe('DynamicChipListComponent', () => {
})); }));
it('should render view more button when chip takes more than one line and there are more chips', fakeAsync(() => { it('should render view more button when chip takes more than one line and there are more chips', fakeAsync(() => {
renderChips([{ renderChips([
{
name: 'VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag', name: 'VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag VeryLongTag',
id: '0ee933fa-57fc-4587-8a77-b787e814f1d2' id: '0ee933fa-57fc-4587-8a77-b787e814f1d2'
}, { },
{
name: 'Some other tag', name: 'Some other tag',
id: '0ee933fa-57fc-4587-8a77-b787e814f1d3' id: '0ee933fa-57fc-4587-8a77-b787e814f1d3'
}]); }
]);
component.ngOnChanges({ component.ngOnChanges({
chips: new SimpleChange(undefined, component.chips, true) chips: new SimpleChange(undefined, component.chips, true)
}); });
@@ -22,10 +22,8 @@ import { TextWidgetComponent, CheckboxWidgetComponent } from '../widgets';
import { FormFieldComponent } from './form-field.component'; import { FormFieldComponent } from './form-field.component';
import { FormBaseModule } from '../../form-base.module'; import { FormBaseModule } from '../../form-base.module';
import { CoreTestingModule } from '../../../testing'; import { CoreTestingModule } from '../../../testing';
import { TranslateModule } from '@ngx-translate/core';
describe('FormFieldComponent', () => { describe('FormFieldComponent', () => {
let fixture: ComponentFixture<FormFieldComponent>; let fixture: ComponentFixture<FormFieldComponent>;
let component: FormFieldComponent; let component: FormFieldComponent;
let form: FormModel; let form: FormModel;
@@ -34,11 +32,7 @@ describe('FormFieldComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, FormBaseModule]
TranslateModule.forRoot(),
CoreTestingModule,
FormBaseModule
]
}); });
fixture = TestBed.createComponent(FormFieldComponent); fixture = TestBed.createComponent(FormFieldComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -43,7 +43,6 @@ import {
} from './mock/form-renderer.component.mock'; } from './mock/form-renderer.component.mock';
import { FormService } from '../services/form.service'; import { FormService } from '../services/form.service';
import { CoreTestingModule } from '../../testing'; import { CoreTestingModule } from '../../testing';
import { TranslateModule } from '@ngx-translate/core';
import { FormRenderingService } from '../services/form-rendering.service'; import { FormRenderingService } from '../services/form-rendering.service';
import { TextWidgetComponent } from './widgets'; import { TextWidgetComponent } from './widgets';
import { FormRulesManager } from '../models/form-rules.model'; import { FormRulesManager } from '../models/form-rules.model';
@@ -88,7 +87,7 @@ describe('Form Renderer Component', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, FormBaseModule] imports: [CoreTestingModule, FormBaseModule]
}); });
fixture = TestBed.createComponent(FormRendererComponent); fixture = TestBed.createComponent(FormRendererComponent);
formRendererComponent = fixture.componentInstance; formRendererComponent = fixture.componentInstance;
@@ -430,9 +429,7 @@ describe('Form Renderer Component', () => {
const twoSpanTextWidgetContainerId = '#field-1ff21afc-7df4-4607-8363-1dc8576e1c8e-container'; const twoSpanTextWidgetContainerId = '#field-1ff21afc-7df4-4607-8363-1dc8576e1c8e-container';
const oneSpanTextWidgetContainerId = '#field-f4285ad-g123-1a73-521d-7nm4a7231aul0-container'; const oneSpanTextWidgetContainerId = '#field-f4285ad-g123-1a73-521d-7nm4a7231aul0-container';
const formSizedElement = fixture.nativeElement.querySelector( const formSizedElement = fixture.nativeElement.querySelector(`${oneSpanTextWidgetContainerId} section.adf-grid-list-column-view`);
`${oneSpanTextWidgetContainerId} section.adf-grid-list-column-view`
);
expectElementToBeVisible(formSizedElement); expectElementToBeVisible(formSizedElement);
const sectionGridElement: HTMLElement[] = fixture.nativeElement.querySelectorAll( const sectionGridElement: HTMLElement[] = fixture.nativeElement.querySelectorAll(
`${oneSpanTextWidgetContainerId} section .adf-grid-list-single-column` `${oneSpanTextWidgetContainerId} section .adf-grid-list-single-column`
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UntypedFormControl } from '@angular/forms'; import { UntypedFormControl } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { InplaceFormInputComponent } from './inplace-form-input.component'; import { InplaceFormInputComponent } from './inplace-form-input.component';
@@ -28,10 +27,7 @@ describe('InplaceFormInputComponent', () => {
beforeEach(async () => { beforeEach(async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
declarations: [InplaceFormInputComponent] declarations: [InplaceFormInputComponent]
}).compileComponents(); }).compileComponents();
}); });
@@ -48,9 +44,7 @@ describe('InplaceFormInputComponent', () => {
formControl.setValue('New Value'); formControl.setValue('New Value');
fixture.detectChanges(); fixture.detectChanges();
const input = fixture.nativeElement.querySelector( const input = fixture.nativeElement.querySelector('[data-automation-id="adf-inplace-input"]');
'[data-automation-id="adf-inplace-input"]'
);
expect(input.value).toBe('New Value'); expect(input.value).toBe('New Value');
}); });
@@ -63,9 +57,7 @@ describe('InplaceFormInputComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const error = fixture.nativeElement.querySelector( const error = fixture.nativeElement.querySelector('[data-automation-id="adf-inplace-input-error"]');
'[data-automation-id="adf-inplace-input-error"]'
);
expect(error).toBeTruthy(); expect(error).toBeTruthy();
}); });
@@ -75,9 +67,7 @@ describe('InplaceFormInputComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const error = fixture.nativeElement.querySelector( const error = fixture.nativeElement.querySelector('[data-automation-id="adf-inplace-input-label"]');
'[data-automation-id="adf-inplace-input-label"]'
);
expect(error).toBeTruthy(); expect(error).toBeTruthy();
}); });
@@ -21,7 +21,6 @@ import { AmountWidgetComponent, ADF_AMOUNT_SETTINGS } from './amount.widget';
import { FormBaseModule } from '../../../form-base.module'; import { FormBaseModule } from '../../../form-base.module';
import { FormFieldTypes } from '../core/form-field-types'; import { FormFieldTypes } from '../core/form-field-types';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { FormModel } from '../core/form.model'; import { FormModel } from '../core/form.model';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@@ -37,7 +36,7 @@ describe('AmountWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, FormBaseModule] imports: [CoreTestingModule, FormBaseModule]
}); });
fixture = TestBed.createComponent(AmountWidgetComponent); fixture = TestBed.createComponent(AmountWidgetComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;
@@ -145,7 +144,7 @@ describe('AmountWidgetComponent - rendering', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, FormBaseModule] imports: [CoreTestingModule, FormBaseModule]
}); });
fixture = TestBed.createComponent(AmountWidgetComponent); fixture = TestBed.createComponent(AmountWidgetComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;
@@ -340,7 +339,7 @@ describe('AmountWidgetComponent settings', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, FormBaseModule], imports: [CoreTestingModule, FormBaseModule],
providers: [ providers: [
{ {
provide: ADF_AMOUNT_SETTINGS, provide: ADF_AMOUNT_SETTINGS,
@@ -16,7 +16,6 @@
*/ */
import { FormModel } from '../core/form.model'; import { FormModel } from '../core/form.model';
import { TranslateModule } from '@ngx-translate/core';
import { FormFieldModel } from '../core/form-field.model'; import { FormFieldModel } from '../core/form-field.model';
import { FormService } from '../../../services/form.service'; import { FormService } from '../../../services/form.service';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
@@ -46,10 +45,7 @@ describe('BaseViewerWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
CoreTestingModule,
TranslateModule.forRoot()
],
declarations: [BaseViewerWidgetComponent], declarations: [BaseViewerWidgetComponent],
providers: [{ provide: FormService, useValue: formServiceStub }] providers: [{ provide: FormService, useValue: formServiceStub }]
}); });
@@ -82,7 +78,14 @@ describe('BaseViewerWidgetComponent', () => {
* @param fixture test fixture * @param fixture test fixture
* @param done callback * @param done callback
*/ */
function assertFileId(value: any, expectedFileId: string, fakeForm: FormModel, widget: BaseViewerWidgetComponent, fixture: ComponentFixture<BaseViewerWidgetComponent>, done: DoneFn) { function assertFileId(
value: any,
expectedFileId: string,
fakeForm: FormModel,
widget: BaseViewerWidgetComponent,
fixture: ComponentFixture<BaseViewerWidgetComponent>,
done: DoneFn
) {
const fakeField = new FormFieldModel(fakeForm, { id: 'fakeField', value }); const fakeField = new FormFieldModel(fakeForm, { id: 'fakeField', value });
widget.field = fakeField; widget.field = fakeField;
@@ -93,4 +96,3 @@ function assertFileId(value: any, expectedFileId: string, fakeForm: FormModel, w
done(); done();
}); });
} }
@@ -21,7 +21,7 @@ import { FormFieldModel } from '../core/form-field.model';
import { FormModel } from '../core/form.model'; import { FormModel } from '../core/form.model';
import { CheckboxWidgetComponent } from './checkbox.widget'; import { CheckboxWidgetComponent } from './checkbox.widget';
import { FormBaseModule } from '../../../form-base.module'; import { FormBaseModule } from '../../../form-base.module';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateLoader } from '@ngx-translate/core';
import { TranslateLoaderService } from '../../../../translation/translate-loader.service'; import { TranslateLoaderService } from '../../../../translation/translate-loader.service';
import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatCheckboxModule } from '@angular/material/checkbox';
import { CoreTestingModule } from '../../../../testing'; import { CoreTestingModule } from '../../../../testing';
@@ -39,7 +39,7 @@ describe('CheckboxWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, FormBaseModule, MatCheckboxModule, MatTooltipModule], imports: [CoreTestingModule, FormBaseModule, MatCheckboxModule, MatTooltipModule],
providers: [{ provide: TranslateLoader, useClass: TranslateLoaderService }] providers: [{ provide: TranslateLoader, useClass: TranslateLoaderService }]
}); });
fixture = TestBed.createComponent(CheckboxWidgetComponent); fixture = TestBed.createComponent(CheckboxWidgetComponent);
@@ -20,7 +20,6 @@ import { FormFieldModel } from '../core/form-field.model';
import { FormModel } from '../core/form.model'; import { FormModel } from '../core/form.model';
import { DateTimeWidgetComponent } from './date-time.widget'; import { DateTimeWidgetComponent } from './date-time.widget';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { FormFieldTypes } from '../core/form-field-types'; import { FormFieldTypes } from '../core/form-field-types';
import { DateFieldValidator, DateTimeFieldValidator } from '../core'; import { DateFieldValidator, DateTimeFieldValidator } from '../core';
@@ -38,7 +37,7 @@ describe('DateTimeWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, MatTooltipModule] imports: [CoreTestingModule, MatTooltipModule]
}); });
fixture = TestBed.createComponent(DateTimeWidgetComponent); fixture = TestBed.createComponent(DateTimeWidgetComponent);
@@ -21,7 +21,6 @@ import { FormFieldModel } from '../core/form-field.model';
import { FormModel } from '../core/form.model'; import { FormModel } from '../core/form.model';
import { DateWidgetComponent } from './date.widget'; import { DateWidgetComponent } from './date.widget';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { FormFieldTypes } from '../core/form-field-types'; import { FormFieldTypes } from '../core/form-field-types';
import { DateFieldValidator, MaxDateFieldValidator, MinDateFieldValidator } from '../core/form-field-validator'; import { DateFieldValidator, MaxDateFieldValidator, MinDateFieldValidator } from '../core/form-field-validator';
@@ -34,10 +33,7 @@ describe('DateWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
form = new FormModel(); form = new FormModel();
@@ -168,7 +164,6 @@ describe('DateWidgetComponent', () => {
}); });
describe('when is required', () => { describe('when is required', () => {
beforeEach(() => { beforeEach(() => {
widget.field = new FormFieldModel(new FormModel({ taskId: '<id>' }), { widget.field = new FormFieldModel(new FormModel({ taskId: '<id>' }), {
type: FormFieldTypes.DATE, type: FormFieldTypes.DATE,
@@ -190,7 +185,6 @@ describe('DateWidgetComponent', () => {
}); });
describe('template check', () => { describe('template check', () => {
afterEach(() => { afterEach(() => {
fixture.destroy(); fixture.destroy();
TestBed.resetTestingModule(); TestBed.resetTestingModule();
@@ -25,7 +25,6 @@ import { FormFieldModel, FormFieldTypes, FormModel } from '../core';
import { MatInputHarness } from '@angular/material/input/testing'; import { MatInputHarness } from '@angular/material/input/testing';
import { MatTooltipHarness } from '@angular/material/tooltip/testing'; import { MatTooltipHarness } from '@angular/material/tooltip/testing';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { TranslateModule } from '@ngx-translate/core';
import { CoreTestingModule } from '../../../../testing'; import { CoreTestingModule } from '../../../../testing';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
@@ -37,12 +36,7 @@ describe('DecimalComponent', () => {
beforeEach(async () => { beforeEach(async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, MatInputModule, FormsModule],
TranslateModule.forRoot(),
CoreTestingModule,
MatInputModule,
FormsModule
],
declarations: [DecimalWidgetComponent], declarations: [DecimalWidgetComponent],
providers: [FormService] providers: [FormService]
}).compileComponents(); }).compileComponents();
@@ -21,22 +21,16 @@ import { FormFieldModel } from '../core/form-field.model';
import { FormModel } from '../core/form.model'; import { FormModel } from '../core/form.model';
import { HyperlinkWidgetComponent } from './hyperlink.widget'; import { HyperlinkWidgetComponent } from './hyperlink.widget';
import { CoreTestingModule } from '../../../../testing'; import { CoreTestingModule } from '../../../../testing';
import { TranslateModule } from '@ngx-translate/core';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
describe('HyperlinkWidgetComponent', () => { describe('HyperlinkWidgetComponent', () => {
let widget: HyperlinkWidgetComponent; let widget: HyperlinkWidgetComponent;
let fixture: ComponentFixture<HyperlinkWidgetComponent>; let fixture: ComponentFixture<HyperlinkWidgetComponent>;
let element: HTMLElement; let element: HTMLElement;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, MatTooltipModule]
TranslateModule.forRoot(),
CoreTestingModule,
MatTooltipModule
]
}); });
fixture = TestBed.createComponent(HyperlinkWidgetComponent); fixture = TestBed.createComponent(HyperlinkWidgetComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;
@@ -16,7 +16,6 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { MultilineTextWidgetComponentComponent } from './multiline-text.widget'; import { MultilineTextWidgetComponentComponent } from './multiline-text.widget';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { FormFieldModel } from '../core/form-field.model'; import { FormFieldModel } from '../core/form-field.model';
@@ -35,7 +34,7 @@ describe('MultilineTextWidgetComponentComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [CoreTestingModule]
}); });
fixture = TestBed.createComponent(MultilineTextWidgetComponentComponent); fixture = TestBed.createComponent(MultilineTextWidgetComponentComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;
@@ -19,7 +19,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { TranslateModule } from '@ngx-translate/core';
import { CoreTestingModule } from '../../../../testing'; import { CoreTestingModule } from '../../../../testing';
import { FormFieldModel, FormFieldTypes, FormModel } from '../core'; import { FormFieldModel, FormFieldTypes, FormModel } from '../core';
import { NumberWidgetComponent } from './number.widget'; import { NumberWidgetComponent } from './number.widget';
@@ -36,7 +35,7 @@ describe('NumberWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, MatInputModule, FormsModule, MatIconModule] imports: [CoreTestingModule, MatInputModule, FormsModule, MatIconModule]
}); });
fixture = TestBed.createComponent(NumberWidgetComponent); fixture = TestBed.createComponent(NumberWidgetComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;
@@ -24,7 +24,6 @@ import { FormsModule } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { CoreTestingModule } from '../../../../testing'; import { CoreTestingModule } from '../../../../testing';
import { TranslateModule } from '@ngx-translate/core';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatInputHarness } from '@angular/material/input/testing'; import { MatInputHarness } from '@angular/material/input/testing';
@@ -42,7 +41,7 @@ describe('TextWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, MatInputModule, FormsModule, MatIconModule] imports: [CoreTestingModule, MatInputModule, FormsModule, MatIconModule]
}); });
fixture = TestBed.createComponent(TextWidgetComponent); fixture = TestBed.createComponent(TextWidgetComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;
@@ -20,22 +20,17 @@ import { FormFieldModel } from './core/form-field.model';
import { FormModel } from './core/form.model'; import { FormModel } from './core/form.model';
import { WidgetComponent } from './widget.component'; import { WidgetComponent } from './widget.component';
import { CoreTestingModule } from '../../../testing'; import { CoreTestingModule } from '../../../testing';
import { TranslateModule } from '@ngx-translate/core';
import { filter } from 'rxjs/operators'; import { filter } from 'rxjs/operators';
import { FormRulesEvent } from '../../events/form-rules.event'; import { FormRulesEvent } from '../../events/form-rules.event';
describe('WidgetComponent', () => { describe('WidgetComponent', () => {
let widget: WidgetComponent; let widget: WidgetComponent;
let fixture: ComponentFixture<WidgetComponent>; let fixture: ComponentFixture<WidgetComponent>;
let element: HTMLElement; let element: HTMLElement;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(WidgetComponent); fixture = TestBed.createComponent(WidgetComponent);
@@ -46,7 +41,6 @@ describe('WidgetComponent', () => {
}); });
describe('Events', () => { describe('Events', () => {
it('should click event be redirect on the form event service', fakeAsync(() => { it('should click event be redirect on the form event service', fakeAsync(() => {
widget.formService.formEvents.subscribe((event) => { widget.formService.formEvents.subscribe((event) => {
expect(event).toBeTruthy(); expect(event).toBeTruthy();
@@ -56,7 +50,7 @@ describe('WidgetComponent', () => {
})); }));
it('should click event be redirect on the form rules event service', fakeAsync(() => { it('should click event be redirect on the form rules event service', fakeAsync(() => {
widget.formService.formRulesEvent.pipe(filter(event => event.type === 'click')).subscribe((event) => { widget.formService.formRulesEvent.pipe(filter((event) => event.type === 'click')).subscribe((event) => {
expect(event).toBeTruthy(); expect(event).toBeTruthy();
}); });
@@ -77,7 +71,7 @@ describe('WidgetComponent', () => {
let lastValue: FormFieldModel; let lastValue: FormFieldModel;
widget.fieldChanged.subscribe((field) => lastValue = field); widget.fieldChanged.subscribe((field) => (lastValue = field));
widget.ngAfterViewInit(); widget.ngAfterViewInit();
expect(lastValue).not.toBe(null); expect(lastValue).not.toBe(null);
@@ -90,7 +84,7 @@ describe('WidgetComponent', () => {
const fakeField = new FormFieldModel(fakeForm, { id: 'fakeField', value: 'fakeValue' }); const fakeField = new FormFieldModel(fakeForm, { id: 'fakeField', value: 'fakeValue' });
let lastValue: FormFieldModel; let lastValue: FormFieldModel;
widget.fieldChanged.subscribe((field) => lastValue = field); widget.fieldChanged.subscribe((field) => (lastValue = field));
widget.onFieldChanged(fakeField); widget.onFieldChanged(fakeField);
expect(lastValue).not.toBe(null); expect(lastValue).not.toBe(null);
@@ -103,7 +97,7 @@ describe('WidgetComponent', () => {
const fakeField = new FormFieldModel(fakeForm, { id: 'fakeField', value: 'fakeValue' }); const fakeField = new FormFieldModel(fakeForm, { id: 'fakeField', value: 'fakeValue' });
let lastValue: FormRulesEvent; let lastValue: FormRulesEvent;
widget.formService.formRulesEvent.subscribe((event) => lastValue = event); widget.formService.formRulesEvent.subscribe((event) => (lastValue = event));
widget.onFieldChanged(fakeField); widget.onFieldChanged(fakeField);
expect(lastValue.type).toEqual('fieldValueChanged'); expect(lastValue.type).toEqual('fieldValueChanged');
@@ -55,7 +55,10 @@ export class WidgetComponent implements AfterViewInit {
* Emitted when a field value changes. * Emitted when a field value changes.
*/ */
@Output() @Output()
fieldChanged: EventEmitter<FormFieldModel> = new EventEmitter<FormFieldModel>(); fieldChanged = new EventEmitter<FormFieldModel>();
@Output()
widgetError = new EventEmitter<any>();
touched: boolean = false; touched: boolean = false;
@@ -17,7 +17,6 @@
import { FormBaseModule } from '../form-base.module'; import { FormBaseModule } from '../form-base.module';
import { CoreTestingModule } from '../../testing'; import { CoreTestingModule } from '../../testing';
import { TranslateModule } from '@ngx-translate/core';
import { ByPassFormRuleManager, FormRulesManager, formRulesManagerFactory, FORM_RULES_MANAGER } from './form-rules.model'; import { ByPassFormRuleManager, FormRulesManager, formRulesManagerFactory, FORM_RULES_MANAGER } from './form-rules.model';
import { Injector } from '@angular/core'; import { Injector } from '@angular/core';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
@@ -34,11 +33,9 @@ class CustomRuleManager extends FormRulesManager<any> {
protected handleRuleEvent(): void { protected handleRuleEvent(): void {
return; return;
} }
} }
describe('Form Rules', () => { describe('Form Rules', () => {
let injector: Injector; let injector: Injector;
const customRuleManager = new CustomRuleManager(null); const customRuleManager = new CustomRuleManager(null);
let formService: FormService; let formService: FormService;
@@ -46,11 +43,7 @@ describe('Form Rules', () => {
describe('Injection token provided', () => { describe('Injection token provided', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, FormBaseModule],
TranslateModule.forRoot(),
CoreTestingModule,
FormBaseModule
],
providers: [ providers: [
{ {
provide: FORM_RULES_MANAGER, provide: FORM_RULES_MANAGER,
@@ -115,11 +108,7 @@ describe('Form Rules', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, FormBaseModule]
TranslateModule.forRoot(),
CoreTestingModule,
FormBaseModule
]
}); });
injector = TestBed.inject(Injector); injector = TestBed.inject(Injector);
rulesManager = formRulesManagerFactory<any>(injector); rulesManager = formRulesManagerFactory<any>(injector);
@@ -19,28 +19,22 @@ import { TestBed } from '@angular/core/testing';
import { formModelTabs } from '../../mock'; import { formModelTabs } from '../../mock';
import { FormService } from './form.service'; import { FormService } from './form.service';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('Form service', () => { describe('Form service', () => {
let service: FormService; let service: FormService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
service = TestBed.inject(FormService); service = TestBed.inject(FormService);
}); });
describe('parseForm', () => { describe('parseForm', () => {
it('should parse a Form Definition with tabs', () => { it('should parse a Form Definition with tabs', () => {
expect(formModelTabs.formRepresentation.formDefinition).toBeDefined(); expect(formModelTabs.formRepresentation.formDefinition).toBeDefined();
const formParsed = service.parseForm(formModelTabs); const formParsed = service.parseForm(formModelTabs);
expect(formParsed).toBeDefined(); expect(formParsed).toBeDefined();
}); });
}); });
}); });
@@ -16,24 +16,19 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { import { ContainerModel, FormFieldModel, FormFieldTypes, FormModel, TabModel, FormOutcomeModel } from '../components/widgets/core';
ContainerModel,
FormFieldModel,
FormFieldTypes,
FormModel,
TabModel,
FormOutcomeModel
} from '../components/widgets/core';
import { WidgetVisibilityModel, WidgetTypeEnum } from '../models/widget-visibility.model'; import { WidgetVisibilityModel, WidgetTypeEnum } from '../models/widget-visibility.model';
import { WidgetVisibilityService } from './widget-visibility.service'; import { WidgetVisibilityService } from './widget-visibility.service';
import { import {
fakeFormJson, fakeFormJson,
formTest, formValues, complexVisibilityJsonVisible, formTest,
nextConditionForm, complexVisibilityJsonNotVisible, formValues,
complexVisibilityJsonVisible,
nextConditionForm,
complexVisibilityJsonNotVisible,
headerVisibilityCond headerVisibilityCond
} from '../../mock/form/widget-visibility-cloud.service.mock'; } from '../../mock/form/widget-visibility-cloud.service.mock';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
declare let jasmine: any; declare let jasmine: any;
@@ -45,10 +40,7 @@ describe('WidgetVisibilityCloudService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
service = TestBed.inject(WidgetVisibilityService); service = TestBed.inject(WidgetVisibilityService);
jasmine.Ajax.install(); jasmine.Ajax.install();
@@ -59,7 +51,6 @@ describe('WidgetVisibilityCloudService', () => {
}); });
describe('should be able to evaluate next condition operations', () => { describe('should be able to evaluate next condition operations', () => {
it('using == and return true', () => { it('using == and return true', () => {
booleanResult = service.evaluateCondition('test', 'test', '=='); booleanResult = service.evaluateCondition('test', 'test', '==');
expect(booleanResult).toBeTruthy(); expect(booleanResult).toBeTruthy();
@@ -167,7 +158,8 @@ describe('WidgetVisibilityCloudService', () => {
name: 'FORM_VARIABLE_TEST', name: 'FORM_VARIABLE_TEST',
type: 'string', type: 'string',
value: 'form_value_test' value: 'form_value_test'
}] }
]
}); });
beforeEach(() => { beforeEach(() => {
@@ -484,7 +476,6 @@ describe('WidgetVisibilityCloudService', () => {
}); });
it('should use the process variables when they are passed to check the visibility', () => { it('should use the process variables when they are passed to check the visibility', () => {
visibilityObjTest.leftType = WidgetTypeEnum.field; visibilityObjTest.leftType = WidgetTypeEnum.field;
visibilityObjTest.leftValue = 'FIELD_FORM_EMPTY'; visibilityObjTest.leftValue = 'FIELD_FORM_EMPTY';
visibilityObjTest.operator = '=='; visibilityObjTest.operator = '==';
@@ -560,13 +551,15 @@ describe('WidgetVisibilityCloudService', () => {
visibilityObjTest.leftType = 'FIELD_TEST'; visibilityObjTest.leftType = 'FIELD_TEST';
visibilityObjTest.operator = '=='; visibilityObjTest.operator = '==';
visibilityObjTest.rightType = 'LEFT_FORM_FIELD_ID'; visibilityObjTest.rightType = 'LEFT_FORM_FIELD_ID';
const contModel = new ContainerModel(new FormFieldModel(fakeFormWithField, { const contModel = new ContainerModel(
new FormFieldModel(fakeFormWithField, {
id: 'fake-container-id', id: 'fake-container-id',
type: FormFieldTypes.GROUP, type: FormFieldTypes.GROUP,
name: 'fake-container-name', name: 'fake-container-name',
isVisible: true, isVisible: true,
visibilityCondition: visibilityObjTest visibilityCondition: visibilityObjTest
})); })
);
fakeFormWithField.fieldsCache.push(contModel.field); fakeFormWithField.fieldsCache.push(contModel.field);
service.refreshVisibility(fakeFormWithField); service.refreshVisibility(fakeFormWithField);
@@ -579,13 +572,15 @@ describe('WidgetVisibilityCloudService', () => {
visibilityObjTest.operator = '!='; visibilityObjTest.operator = '!=';
visibilityObjTest.rightType = WidgetTypeEnum.field; visibilityObjTest.rightType = WidgetTypeEnum.field;
visibilityObjTest.rightValue = 'RIGHT_FORM_FIELD_ID'; visibilityObjTest.rightValue = 'RIGHT_FORM_FIELD_ID';
const contModel = new ContainerModel(new FormFieldModel(fakeFormWithField, { const contModel = new ContainerModel(
new FormFieldModel(fakeFormWithField, {
id: 'fake-container-id', id: 'fake-container-id',
type: FormFieldTypes.GROUP, type: FormFieldTypes.GROUP,
name: 'fake-container-name', name: 'fake-container-name',
isVisible: true, isVisible: true,
visibilityCondition: visibilityObjTest visibilityCondition: visibilityObjTest
})); })
);
service.refreshEntityVisibility(contModel.field); service.refreshEntityVisibility(contModel.field);
expect(contModel.isVisible).toBeFalsy(); expect(contModel.isVisible).toBeFalsy();
}); });
@@ -633,7 +628,8 @@ describe('WidgetVisibilityCloudService', () => {
name: 'No' name: 'No'
} }
] ]
}, { },
{
id: 'textBoxTest', id: 'textBoxTest',
name: 'textbox test', name: 'textbox test',
type: 'people', type: 'people',
@@ -661,7 +657,6 @@ describe('WidgetVisibilityCloudService', () => {
}); });
describe('Visibility based on form variables', () => { describe('Visibility based on form variables', () => {
const fakeFormWithVariables = new FormModel(fakeFormJson); const fakeFormWithVariables = new FormModel(fakeFormJson);
const complexVisibilityModel = new FormModel(complexVisibilityJsonVisible); const complexVisibilityModel = new FormModel(complexVisibilityJsonVisible);
const complexVisibilityJsonNotVisibleModel = new FormModel(complexVisibilityJsonNotVisible); const complexVisibilityJsonNotVisibleModel = new FormModel(complexVisibilityJsonNotVisible);
@@ -682,15 +677,19 @@ describe('WidgetVisibilityCloudService', () => {
}); });
it('should be able to analyze a complex visibility JSON truthy', () => { it('should be able to analyze a complex visibility JSON truthy', () => {
const isVisible = service.isFieldVisible(complexVisibilityModel, const isVisible = service.isFieldVisible(
complexVisibilityJsonVisible.formDefinition.fields[2].fields[2][0].visibilityCondition); complexVisibilityModel,
complexVisibilityJsonVisible.formDefinition.fields[2].fields[2][0].visibilityCondition
);
expect(isVisible).toBe(true); expect(isVisible).toBe(true);
}); });
it('should be able to analyze a complex visibility JSON false', () => { it('should be able to analyze a complex visibility JSON false', () => {
const isVisible = service.isFieldVisible(complexVisibilityJsonNotVisibleModel, const isVisible = service.isFieldVisible(
complexVisibilityJsonNotVisible.formDefinition.fields[2].fields[2][0].visibilityCondition); complexVisibilityJsonNotVisibleModel,
complexVisibilityJsonNotVisible.formDefinition.fields[2].fields[2][0].visibilityCondition
);
expect(isVisible).toBe(false); expect(isVisible).toBe(false);
}); });
@@ -16,25 +16,21 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { import { ContainerModel, FormFieldModel, FormFieldTypes, FormModel, TabModel } from '../components/widgets/core';
ContainerModel,
FormFieldModel,
FormFieldTypes,
FormModel,
TabModel
} from '../components/widgets/core';
import { WidgetVisibilityModel } from '../models/widget-visibility.model'; import { WidgetVisibilityModel } from '../models/widget-visibility.model';
import { WidgetVisibilityService } from './widget-visibility.service'; import { WidgetVisibilityService } from './widget-visibility.service';
import { import {
fakeFormJson, formTest, fakeFormJson,
formValues, complexVisibilityJsonVisible, formTest,
complexVisibilityJsonNotVisible, tabVisibilityJsonMock, formValues,
complexVisibilityJsonVisible,
complexVisibilityJsonNotVisible,
tabVisibilityJsonMock,
tabInvalidFormVisibility, tabInvalidFormVisibility,
fakeFormChainedVisibilityJson, fakeFormChainedVisibilityJson,
fakeFormCheckBoxVisibilityJson fakeFormCheckBoxVisibilityJson
} from '../../mock/form/widget-visibility.service.mock'; } from '../../mock/form/widget-visibility.service.mock';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('WidgetVisibilityService', () => { describe('WidgetVisibilityService', () => {
let service: WidgetVisibilityService; let service: WidgetVisibilityService;
@@ -53,18 +49,15 @@ describe('WidgetVisibilityService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
service = TestBed.inject(WidgetVisibilityService); service = TestBed.inject(WidgetVisibilityService);
}); });
describe('should be able to evaluate next condition operations', () => { describe('should be able to evaluate next condition operations', () => {
it('using == and return true', () => { it('using == and return true', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
[true, true], [true, true],
[false, false], [false, false],
['true', true], ['true', true],
@@ -73,7 +66,9 @@ describe('WidgetVisibilityService', () => {
['test', 'test'], ['test', 'test'],
['4', 4], ['4', 4],
[0, 0] [0, 0]
], '=='); ],
'=='
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(true); expect(result).toBe(true);
@@ -81,7 +76,8 @@ describe('WidgetVisibilityService', () => {
}); });
it('using == and return false', () => { it('using == and return false', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
[true, false], [true, false],
[false, true], [false, true],
['false', true], ['false', true],
@@ -90,7 +86,9 @@ describe('WidgetVisibilityService', () => {
['test', 'testt'], ['test', 'testt'],
['2', 3], ['2', 3],
[0, 1] [0, 1]
], '=='); ],
'=='
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(false); expect(result).toBe(false);
@@ -98,7 +96,8 @@ describe('WidgetVisibilityService', () => {
}); });
it('using != and return true', () => { it('using != and return true', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
['test', 'te'], ['test', 'te'],
['4', 123], ['4', 123],
[0, 1], [0, 1],
@@ -107,7 +106,9 @@ describe('WidgetVisibilityService', () => {
['false', true], ['false', true],
[false, 'true'], [false, 'true'],
['false', 'true'] ['false', 'true']
], '!='); ],
'!='
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(true); expect(result).toBe(true);
@@ -115,7 +116,8 @@ describe('WidgetVisibilityService', () => {
}); });
it('using != and return false', () => { it('using != and return false', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
['testtest', 'testtest'], ['testtest', 'testtest'],
['7', 7], ['7', 7],
[0, 0], [0, 0],
@@ -124,7 +126,9 @@ describe('WidgetVisibilityService', () => {
['true', true], ['true', true],
[true, 'true'], [true, 'true'],
['true', 'true'] ['true', 'true']
], '!='); ],
'!='
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(false); expect(result).toBe(false);
@@ -132,11 +136,14 @@ describe('WidgetVisibilityService', () => {
}); });
it('using < and return false', () => { it('using < and return false', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
[2, 1], [2, 1],
[1, 0], [1, 0],
[0, -1] [0, -1]
], '<'); ],
'<'
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(false); expect(result).toBe(false);
@@ -144,12 +151,15 @@ describe('WidgetVisibilityService', () => {
}); });
it('using <= and return true', () => { it('using <= and return true', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
[3, 4], [3, 4],
[0, 1], [0, 1],
[0, 0], [0, 0],
[1, 1] [1, 1]
], '<='); ],
'<='
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(true); expect(result).toBe(true);
@@ -157,12 +167,15 @@ describe('WidgetVisibilityService', () => {
}); });
it('using > and return false', () => { it('using > and return false', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
[0, 1], [0, 1],
[0, 141], [0, 141],
[-144, 0], [-144, 0],
[32, 44] [32, 44]
], '>'); ],
'>'
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(false); expect(result).toBe(false);
@@ -170,13 +183,16 @@ describe('WidgetVisibilityService', () => {
}); });
it('using >= and return true', () => { it('using >= and return true', () => {
const resultsArray = evaluateConditions([ const resultsArray = evaluateConditions(
[
[12, 2], [12, 2],
[2, 2], [2, 2],
[1, 0], [1, 0],
[0, 0], [0, 0],
[0, -10] [0, -10]
], '>='); ],
'>='
);
resultsArray.forEach((result) => { resultsArray.forEach((result) => {
expect(result).toBe(true); expect(result).toBe(true);
@@ -249,7 +265,8 @@ describe('WidgetVisibilityService', () => {
name: 'FORM_VARIABLE_TEST', name: 'FORM_VARIABLE_TEST',
type: 'string', type: 'string',
value: 'form_value_test' value: 'form_value_test'
}] }
]
}); });
beforeEach(() => { beforeEach(() => {
@@ -415,7 +432,6 @@ describe('WidgetVisibilityService', () => {
expect(isVisible).toBeTruthy(); expect(isVisible).toBeTruthy();
}); });
it('should return true when left field value is equal to true and rigth value is equal to "true"', () => { it('should return true when left field value is equal to true and rigth value is equal to "true"', () => {
spyOn(service, 'getFieldValue').and.returnValue(true); spyOn(service, 'getFieldValue').and.returnValue(true);
spyOn(service, 'isFormFieldValid').and.returnValue(true); spyOn(service, 'isFormFieldValid').and.returnValue(true);
@@ -670,13 +686,15 @@ describe('WidgetVisibilityService', () => {
visibilityObjTest.leftFormFieldId = 'FIELD_TEST'; visibilityObjTest.leftFormFieldId = 'FIELD_TEST';
visibilityObjTest.operator = '=='; visibilityObjTest.operator = '==';
visibilityObjTest.rightFormFieldId = 'LEFT_FORM_FIELD_ID'; visibilityObjTest.rightFormFieldId = 'LEFT_FORM_FIELD_ID';
const contModel = new ContainerModel(new FormFieldModel(fakeFormWithField, { const contModel = new ContainerModel(
new FormFieldModel(fakeFormWithField, {
id: 'fake-container-id', id: 'fake-container-id',
type: FormFieldTypes.GROUP, type: FormFieldTypes.GROUP,
name: 'fake-container-name', name: 'fake-container-name',
isVisible: true, isVisible: true,
visibilityCondition: visibilityObjTest visibilityCondition: visibilityObjTest
})); })
);
fakeFormWithField.fieldsCache.push(contModel.field); fakeFormWithField.fieldsCache.push(contModel.field);
service.refreshVisibility(fakeFormWithField); service.refreshVisibility(fakeFormWithField);
@@ -687,13 +705,15 @@ describe('WidgetVisibilityService', () => {
visibilityObjTest.leftFormFieldId = 'FIELD_TEST'; visibilityObjTest.leftFormFieldId = 'FIELD_TEST';
visibilityObjTest.operator = '!='; visibilityObjTest.operator = '!=';
visibilityObjTest.rightFormFieldId = 'RIGHT_FORM_FIELD_ID'; visibilityObjTest.rightFormFieldId = 'RIGHT_FORM_FIELD_ID';
const contModel = new ContainerModel(new FormFieldModel(fakeFormWithField, { const contModel = new ContainerModel(
new FormFieldModel(fakeFormWithField, {
id: 'fake-container-id', id: 'fake-container-id',
type: FormFieldTypes.GROUP, type: FormFieldTypes.GROUP,
name: 'fake-container-name', name: 'fake-container-name',
isVisible: true, isVisible: true,
visibilityCondition: visibilityObjTest visibilityCondition: visibilityObjTest
})); })
);
service.refreshEntityVisibility(contModel.field); service.refreshEntityVisibility(contModel.field);
expect(contModel.isVisible).toBeFalsy(); expect(contModel.isVisible).toBeFalsy();
}); });
@@ -752,7 +772,8 @@ describe('WidgetVisibilityService', () => {
name: 'No' name: 'No'
} }
] ]
}, { },
{
id: 'textBoxTest', id: 'textBoxTest',
name: 'textbox test', name: 'textbox test',
type: 'people', type: 'people',
@@ -780,7 +801,6 @@ describe('WidgetVisibilityService', () => {
}); });
describe('Visibility based on form variables', () => { describe('Visibility based on form variables', () => {
let fakeFormWithVariables = new FormModel(fakeFormJson); let fakeFormWithVariables = new FormModel(fakeFormJson);
const fakeTabVisibilityModel = new FormModel(tabVisibilityJsonMock); const fakeTabVisibilityModel = new FormModel(tabVisibilityJsonMock);
const complexVisibilityModel = new FormModel(complexVisibilityJsonVisible); const complexVisibilityModel = new FormModel(complexVisibilityJsonVisible);
@@ -804,14 +824,19 @@ describe('WidgetVisibilityService', () => {
}); });
it('should be able to analyze a complex visibility JSON truthy', () => { it('should be able to analyze a complex visibility JSON truthy', () => {
const isVisible = service.isFieldVisible(complexVisibilityModel, const isVisible = service.isFieldVisible(
complexVisibilityJsonVisible.formDefinition.fields[2].fields[2][0].visibilityCondition); complexVisibilityModel,
complexVisibilityJsonVisible.formDefinition.fields[2].fields[2][0].visibilityCondition
);
expect(isVisible).toBe(true); expect(isVisible).toBe(true);
}); });
it('should be able to analyze a complex visibility JSON false', () => { it('should be able to analyze a complex visibility JSON false', () => {
const formField = new FormFieldModel(complexVisibilityJsonNotVisibleModel, complexVisibilityJsonNotVisible.formDefinition.fields[2].fields[2][0]); const formField = new FormFieldModel(
complexVisibilityJsonNotVisibleModel,
complexVisibilityJsonNotVisible.formDefinition.fields[2].fields[2][0]
);
const isVisible = service.isFieldVisible(complexVisibilityJsonNotVisibleModel, new WidgetVisibilityModel(formField.visibilityCondition)); const isVisible = service.isFieldVisible(complexVisibilityJsonNotVisibleModel, new WidgetVisibilityModel(formField.visibilityCondition));
expect(isVisible).toBe(false); expect(isVisible).toBe(false);
}); });
@@ -899,7 +924,6 @@ describe('WidgetVisibilityService', () => {
}); });
describe('Visibility calculation in complex forms', () => { describe('Visibility calculation in complex forms', () => {
const fakeFormWithVariables = new FormModel(fakeFormChainedVisibilityJson); const fakeFormWithVariables = new FormModel(fakeFormChainedVisibilityJson);
it('Should be able to validate correctly the visibility for the text field for complex expressions', () => { it('Should be able to validate correctly the visibility for the text field for complex expressions', () => {
@@ -927,7 +951,6 @@ describe('WidgetVisibilityService', () => {
}); });
describe('Visibility calculation in checkbox forms', () => { describe('Visibility calculation in checkbox forms', () => {
const fakeFormWithValues = new FormModel(fakeFormCheckBoxVisibilityJson); const fakeFormWithValues = new FormModel(fakeFormCheckBoxVisibilityJson);
it('Should be able to validate correctly the visibility for the checkbox expression', () => { it('Should be able to validate correctly the visibility for the checkbox expression', () => {
@@ -17,7 +17,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { IdentityUserInfoComponent } from './identity-user-info.component'; import { IdentityUserInfoComponent } from './identity-user-info.component';
import { TranslateModule } from '@ngx-translate/core';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { MatMenuModule } from '@angular/material/menu'; import { MatMenuModule } from '@angular/material/menu';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
@@ -28,9 +27,21 @@ describe('IdentityUserInfoComponent', () => {
let fixture: ComponentFixture<IdentityUserInfoComponent>; let fixture: ComponentFixture<IdentityUserInfoComponent>;
let element: HTMLElement; let element: HTMLElement;
const identityUserMock = { firstName: 'fake-identity-first-name', lastName: 'fake-identity-last-name', email: 'fakeIdentity@email.com' } as unknown as IdentityUserModel; const identityUserMock = {
const identityUserWithOutFirstNameMock = { firstName: null, lastName: 'fake-identity-last-name', email: 'fakeIdentity@email.com' } as unknown as IdentityUserModel; firstName: 'fake-identity-first-name',
const identityUserWithOutLastNameMock = { firstName: 'fake-identity-first-name', lastName: null, email: 'fakeIdentity@email.com' } as unknown as IdentityUserModel; lastName: 'fake-identity-last-name',
email: 'fakeIdentity@email.com'
} as unknown as IdentityUserModel;
const identityUserWithOutFirstNameMock = {
firstName: null,
lastName: 'fake-identity-last-name',
email: 'fakeIdentity@email.com'
} as unknown as IdentityUserModel;
const identityUserWithOutLastNameMock = {
firstName: 'fake-identity-first-name',
lastName: null,
email: 'fakeIdentity@email.com'
} as unknown as IdentityUserModel;
const whenFixtureReady = async () => { const whenFixtureReady = async () => {
fixture.detectChanges(); fixture.detectChanges();
@@ -40,11 +51,7 @@ describe('IdentityUserInfoComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, MatMenuModule]
TranslateModule.forRoot(),
CoreTestingModule,
MatMenuModule
]
}); });
fixture = TestBed.createComponent(IdentityUserInfoComponent); fixture = TestBed.createComponent(IdentityUserInfoComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -70,7 +77,6 @@ describe('IdentityUserInfoComponent', () => {
}); });
describe('when identity user is logged in', () => { describe('when identity user is logged in', () => {
beforeEach(() => { beforeEach(() => {
component.identityUser = identityUserMock; component.identityUser = identityUserMock;
component.isLoggedIn = true; component.isLoggedIn = true;
@@ -21,7 +21,7 @@ import { MatTabChangeEvent } from '@angular/material/tabs';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { InfoDrawerComponent } from './info-drawer.component'; import { InfoDrawerComponent } from './info-drawer.component';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { TranslateService, TranslateModule } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { ESCAPE } from '@angular/cdk/keycodes'; import { ESCAPE } from '@angular/cdk/keycodes';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
@@ -36,10 +36,7 @@ describe('InfoDrawerComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
translateService = TestBed.inject(TranslateService); translateService = TestBed.inject(TranslateService);
spyOn(translateService, 'get').and.callFake((key) => of(key)); spyOn(translateService, 'get').and.callFake((key) => of(key));
@@ -91,12 +88,9 @@ describe('InfoDrawerComponent', () => {
@Component({ @Component({
template: ` template: `
<adf-info-drawer [selectedIndex]="tabIndex" [icon]="icon" title="Fake Title Custom"> <adf-info-drawer [selectedIndex]="tabIndex" [icon]="icon" title="Fake Title Custom">
<adf-info-drawer-tab label="Tab1"> <adf-info-drawer-tab label="Tab1"></adf-info-drawer-tab>
</adf-info-drawer-tab> <adf-info-drawer-tab label="Tab2"></adf-info-drawer-tab>
<adf-info-drawer-tab label="Tab2"> <adf-info-drawer-tab label="Tab3" icon="tab-icon"></adf-info-drawer-tab>
</adf-info-drawer-tab>
<adf-info-drawer-tab label="Tab3" icon="tab-icon">
</adf-info-drawer-tab>
</adf-info-drawer> </adf-info-drawer>
` `
}) })
@@ -111,18 +105,12 @@ describe('Custom InfoDrawer', () => {
let translateService: TranslateService; let translateService: TranslateService;
let loader: HarnessLoader; let loader: HarnessLoader;
const getNodeIcon = () => const getNodeIcon = () => fixture.debugElement.queryAll(By.css('[info-drawer-node-icon]'));
fixture.debugElement.queryAll(By.css('[info-drawer-node-icon]'));
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [CustomInfoDrawerComponent]
CoreTestingModule
],
declarations: [
CustomInfoDrawerComponent
]
}); });
translateService = TestBed.inject(TranslateService); translateService = TestBed.inject(TranslateService);
spyOn(translateService, 'get').and.callFake((key) => of(key)); spyOn(translateService, 'get').and.callFake((key) => of(key));
@@ -182,10 +170,7 @@ describe('Custom InfoDrawer', () => {
}); });
@Component({ @Component({
template: ` template: ` <adf-info-drawer [showHeader]="showHeader" [icon]="icon" title="Fake Visibility Info Drawer Title"> </adf-info-drawer> `
<adf-info-drawer [showHeader]="showHeader" [icon]="icon" title="Fake Visibility Info Drawer Title">
</adf-info-drawer>
`
}) })
class VisibilityInfoDrawerComponent extends InfoDrawerComponent { class VisibilityInfoDrawerComponent extends InfoDrawerComponent {
showHeader: boolean; showHeader: boolean;
@@ -195,18 +180,12 @@ class VisibilityInfoDrawerComponent extends InfoDrawerComponent {
describe('Header visibility InfoDrawer', () => { describe('Header visibility InfoDrawer', () => {
let fixture: ComponentFixture<VisibilityInfoDrawerComponent>; let fixture: ComponentFixture<VisibilityInfoDrawerComponent>;
let component: VisibilityInfoDrawerComponent; let component: VisibilityInfoDrawerComponent;
const getNodeIcon = () => const getNodeIcon = () => fixture.debugElement.queryAll(By.css('[info-drawer-node-icon]'));
fixture.debugElement.queryAll(By.css('[info-drawer-node-icon]'));
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [VisibilityInfoDrawerComponent]
CoreTestingModule
],
declarations: [
VisibilityInfoDrawerComponent
]
}); });
fixture = TestBed.createComponent(VisibilityInfoDrawerComponent); fixture = TestBed.createComponent(VisibilityInfoDrawerComponent);
fixture.detectChanges(); fixture.detectChanges();
@@ -20,11 +20,9 @@ import { AppConfigService } from '../app-config/app-config.service';
import { LanguageMenuComponent } from './language-menu.component'; import { LanguageMenuComponent } from './language-menu.component';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { UserPreferencesService } from '../common/services/user-preferences.service'; import { UserPreferencesService } from '../common/services/user-preferences.service';
import { TranslateModule } from '@ngx-translate/core';
import { LanguageService } from './service/language.service'; import { LanguageService } from './service/language.service';
describe('LanguageMenuComponent', () => { describe('LanguageMenuComponent', () => {
let fixture: ComponentFixture<LanguageMenuComponent>; let fixture: ComponentFixture<LanguageMenuComponent>;
let component: LanguageMenuComponent; let component: LanguageMenuComponent;
let appConfig: AppConfigService; let appConfig: AppConfigService;
@@ -49,10 +47,7 @@ describe('LanguageMenuComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(LanguageMenuComponent); fixture = TestBed.createComponent(LanguageMenuComponent);
@@ -71,7 +66,7 @@ describe('LanguageMenuComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
component.languages$.subscribe(langs => { component.languages$.subscribe((langs) => {
expect(langs).toEqual(languages); expect(langs).toEqual(languages);
done(); done();
}); });
@@ -22,7 +22,6 @@ import { By } from '@angular/platform-browser';
import { SidenavLayoutModule } from '../../layout.module'; import { SidenavLayoutModule } from '../../layout.module';
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { MaterialModule } from '../../../material.module'; import { MaterialModule } from '../../../material.module';
import { TranslateModule } from '@ngx-translate/core';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatToolbarHarness } from '@angular/material/toolbar/testing'; import { MatToolbarHarness } from '@angular/material/toolbar/testing';
@@ -35,10 +34,7 @@ describe('HeaderLayoutComponent', () => {
describe('Input parameters', () => { describe('Input parameters', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(HeaderLayoutComponent); fixture = TestBed.createComponent(HeaderLayoutComponent);
loader = TestbedHarnessEnvironment.loader(fixture); loader = TestbedHarnessEnvironment.loader(fixture);
@@ -257,8 +253,7 @@ describe('HeaderLayoutComponent', () => {
describe('Template transclusion', () => { describe('Template transclusion', () => {
@Component({ @Component({
selector: 'adf-test-layout-header', selector: 'adf-test-layout-header',
template: ` template: ` <adf-layout-header title="test" color="primary">
<adf-layout-header title="test" color="primary">
<p>Test text</p> <p>Test text</p>
<p></p> <p></p>
</adf-layout-header>` </adf-layout-header>`
@@ -267,7 +262,7 @@ describe('HeaderLayoutComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, SidenavLayoutModule, MaterialModule], imports: [CoreTestingModule, SidenavLayoutModule, MaterialModule],
declarations: [HeaderLayoutTesterComponent] declarations: [HeaderLayoutTesterComponent]
}); });
}); });
@@ -21,7 +21,6 @@ import { MaterialModule } from '../../../material.module';
import { SidebarActionMenuComponent } from './sidebar-action-menu.component'; import { SidebarActionMenuComponent } from './sidebar-action-menu.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateModule } from '@ngx-translate/core';
describe('SidebarActionMenuComponent', () => { describe('SidebarActionMenuComponent', () => {
let element: HTMLElement; let element: HTMLElement;
@@ -30,10 +29,7 @@ describe('SidebarActionMenuComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(SidebarActionMenuComponent); fixture = TestBed.createComponent(SidebarActionMenuComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
@@ -86,14 +82,8 @@ describe('Custom SidebarActionMenuComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [ declarations: [SidebarActionMenuComponent, CustomSidebarActionMenuComponent],
SidebarActionMenuComponent, imports: [MaterialModule, NoopAnimationsModule]
CustomSidebarActionMenuComponent
],
imports: [
MaterialModule,
NoopAnimationsModule
]
}); });
fixture = TestBed.createComponent(CustomSidebarActionMenuComponent); fixture = TestBed.createComponent(CustomSidebarActionMenuComponent);
fixture.detectChanges(); fixture.detectChanges();
@@ -17,7 +17,6 @@
import { BasicAlfrescoAuthService, CoreTestingModule, LoginDialogPanelComponent } from '@alfresco/adf-core'; import { BasicAlfrescoAuthService, CoreTestingModule, LoginDialogPanelComponent } from '@alfresco/adf-core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { OidcAuthenticationService } from '../../../auth/services/oidc-authentication.service'; import { OidcAuthenticationService } from '../../../auth/services/oidc-authentication.service';
@@ -31,13 +30,8 @@ describe('LoginDialogPanelComponent', () => {
beforeEach(async () => { beforeEach(async () => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), providers: [{ provide: OidcAuthenticationService, useValue: {} }]
CoreTestingModule
],
providers: [
{ provide: OidcAuthenticationService, useValue: {} }
]
}); });
fixture = TestBed.createComponent(LoginDialogPanelComponent); fixture = TestBed.createComponent(LoginDialogPanelComponent);
basicAlfrescoAuthService = TestBed.inject(BasicAlfrescoAuthService); basicAlfrescoAuthService = TestBed.inject(BasicAlfrescoAuthService);
@@ -22,7 +22,6 @@ import {
CoreTestingModule, CoreTestingModule,
LoginErrorEvent, LoginErrorEvent,
LoginSuccessEvent, LoginSuccessEvent,
LogService,
UserPreferencesService UserPreferencesService
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';
@@ -61,14 +60,12 @@ describe('LoginComponent', () => {
beforeEach(fakeAsync(() => { beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
CoreTestingModule
],
providers: [ providers: [
{ {
provide: OidcAuthenticationService, useValue: { provide: OidcAuthenticationService,
ssoLogin: () => { useValue: {
}, ssoLogin: () => {},
isPublicUrl: () => false, isPublicUrl: () => false,
hasValidIdToken: () => false, hasValidIdToken: () => false,
isLoggedIn: () => false isLoggedIn: () => false
@@ -89,9 +86,6 @@ describe('LoginComponent', () => {
userPreferences = TestBed.inject(UserPreferencesService); userPreferences = TestBed.inject(UserPreferencesService);
appConfigService = TestBed.inject(AppConfigService); appConfigService = TestBed.inject(AppConfigService);
const logService = TestBed.inject(LogService);
spyOn(logService, 'error');
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
@@ -117,17 +111,11 @@ describe('LoginComponent', () => {
}; };
it('should be autocomplete off', () => { it('should be autocomplete off', () => {
expect( expect(element.querySelector('#adf-login-form').getAttribute('autocomplete')).toBe('off');
element
.querySelector('#adf-login-form')
.getAttribute('autocomplete')
).toBe('off');
}); });
it('should redirect to route on successful login', () => { it('should redirect to route on successful login', () => {
spyOn(basicAlfrescoAuthService, 'login').and.returnValue( spyOn(basicAlfrescoAuthService, 'login').and.returnValue(of({ type: 'type', ticket: 'ticket' }));
of({ type: 'type', ticket: 'ticket' })
);
const redirect = '/home'; const redirect = '/home';
component.successRoute = redirect; component.successRoute = redirect;
spyOn(router, 'navigate'); spyOn(router, 'navigate');
@@ -200,7 +188,6 @@ describe('LoginComponent', () => {
}); });
describe('Login button', () => { describe('Login button', () => {
const getLoginButton = () => element.querySelector('#login-button'); const getLoginButton = () => element.querySelector('#login-button');
const getLoginButtonText = () => element.querySelector('#login-button span.adf-login-button-label').innerText; const getLoginButtonText = () => element.querySelector('#login-button span.adf-login-button-label').innerText;
@@ -290,12 +277,11 @@ describe('LoginComponent', () => {
}); });
describe('Remember me', () => { describe('Remember me', () => {
it('should be checked by default', () => { it('should be checked by default', () => {
expect(element.querySelector('#adf-login-remember input[type="checkbox"]').checked).toBe(true); expect(element.querySelector('#adf-login-remember input[type="checkbox"]').checked).toBe(true);
}); });
it('should set the component\'s rememberMe property properly', () => { it('should set the component rememberMe property properly', () => {
element.querySelector('#adf-login-remember').dispatchEvent(new Event('change')); element.querySelector('#adf-login-remember').dispatchEvent(new Event('change'));
fixture.detectChanges(); fixture.detectChanges();
@@ -335,10 +321,11 @@ describe('LoginComponent', () => {
}); });
describe('Copyright text', () => { describe('Copyright text', () => {
it('should render the default copyright text', () => { it('should render the default copyright text', () => {
expect(element.querySelector('[data-automation-id="login-copyright"]')).toBeDefined(); expect(element.querySelector('[data-automation-id="login-copyright"]')).toBeDefined();
expect(element.querySelector('[data-automation-id="login-copyright"]').innerText).toEqual('\u00A9 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.'); expect(element.querySelector('[data-automation-id="login-copyright"]').innerText).toEqual(
'\u00A9 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.'
);
}); });
it('should render the customised copyright text', () => { it('should render the customised copyright text', () => {
@@ -376,7 +363,6 @@ describe('LoginComponent', () => {
}); });
describe('Error', () => { describe('Error', () => {
it('should render validation min-length error when the username is just 1 character with a custom validation Validators.minLength(3)', () => { it('should render validation min-length error when the username is just 1 character with a custom validation Validators.minLength(3)', () => {
component.fieldsValidation = { component.fieldsValidation = {
username: ['', Validators.compose([Validators.required, Validators.minLength(3)])], username: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
@@ -529,12 +515,14 @@ describe('LoginComponent', () => {
}); });
it('should return CORS error when server CORS error occurs', (done) => { it('should return CORS error when server CORS error occurs', (done) => {
spyOn(basicAlfrescoAuthService, 'login').and.returnValue(throwError({ spyOn(basicAlfrescoAuthService, 'login').and.returnValue(
throwError({
error: { error: {
crossDomain: true, crossDomain: true,
message: 'ERROR: the network is offline, Origin is not allowed by Access-Control-Allow-Origin' message: 'ERROR: the network is offline, Origin is not allowed by Access-Control-Allow-Origin'
} }
})); })
);
component.error.subscribe(() => { component.error.subscribe(() => {
fixture.detectChanges(); fixture.detectChanges();
@@ -550,8 +538,7 @@ describe('LoginComponent', () => {
}); });
it('should return CSRF error when server CSRF error occurs', fakeAsync(() => { it('should return CSRF error when server CSRF error occurs', fakeAsync(() => {
spyOn(basicAlfrescoAuthService, 'login') spyOn(basicAlfrescoAuthService, 'login').and.returnValue(throwError({ message: 'ERROR: Invalid CSRF-token', status: 403 }));
.and.returnValue(throwError({ message: 'ERROR: Invalid CSRF-token', status: 403 }));
component.error.subscribe(() => { component.error.subscribe(() => {
fixture.detectChanges(); fixture.detectChanges();
@@ -565,14 +552,12 @@ describe('LoginComponent', () => {
})); }));
it('should return ECM read-only error when error occurs', fakeAsync(() => { it('should return ECM read-only error when error occurs', fakeAsync(() => {
spyOn(basicAlfrescoAuthService, 'login') spyOn(basicAlfrescoAuthService, 'login').and.returnValue(
.and.returnValue( throwError({
throwError(
{
message: 'ERROR: 00170728 Access Denied. The system is currently in read-only mode', message: 'ERROR: 00170728 Access Denied. The system is currently in read-only mode',
status: 403 status: 403
} })
)); );
component.error.subscribe(() => { component.error.subscribe(() => {
fixture.detectChanges(); fixture.detectChanges();
@@ -635,9 +620,7 @@ describe('LoginComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(component.isError).toBe(false); expect(component.isError).toBe(false);
expect(event).toEqual( expect(event).toEqual(new LoginSuccessEvent({ type: 'type', ticket: 'ticket' }, 'fake-username', null));
new LoginSuccessEvent({ type: 'type', ticket: 'ticket' }, 'fake-username', null)
);
}); });
loginWithCredentials('fake-username', 'fake-password'); loginWithCredentials('fake-username', 'fake-password');
@@ -652,9 +635,7 @@ describe('LoginComponent', () => {
expect(component.isError).toBe(true); expect(component.isError).toBe(true);
expect(getLoginErrorElement()).toBeDefined(); expect(getLoginErrorElement()).toBeDefined();
expect(getLoginErrorMessage()).toEqual('LOGIN.MESSAGES.LOGIN-ERROR-CREDENTIALS'); expect(getLoginErrorMessage()).toEqual('LOGIN.MESSAGES.LOGIN-ERROR-CREDENTIALS');
expect(error).toEqual( expect(error).toEqual(new LoginErrorEvent('Fake server error'));
new LoginErrorEvent('Fake server error')
);
}); });
loginWithCredentials('fake-username', 'fake-wrong-password'); loginWithCredentials('fake-username', 'fake-wrong-password');
@@ -695,9 +676,7 @@ describe('LoginComponent', () => {
})); }));
describe('SSO ', () => { describe('SSO ', () => {
describe('implicitFlow ', () => { describe('implicitFlow ', () => {
beforeEach(() => { beforeEach(() => {
appConfigService.config.oauth2 = { implicitFlow: true, silentLogin: false }; appConfigService.config.oauth2 = { implicitFlow: true, silentLogin: false };
appConfigService.load(); appConfigService.load();
@@ -727,7 +706,6 @@ describe('LoginComponent', () => {
expect(component.ssoLogin).toBe(false); expect(component.ssoLogin).toBe(false);
expect(component.redirectToSSOLogin).toHaveBeenCalled(); expect(component.redirectToSSOLogin).toHaveBeenCalled();
}); });
})); }));
it('should render the implicitFlow button in case silentLogin is disabled', fakeAsync(() => { it('should render the implicitFlow button in case silentLogin is disabled', fakeAsync(() => {
@@ -739,7 +717,6 @@ describe('LoginComponent', () => {
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
expect(component.ssoLogin).toBe(true); expect(component.ssoLogin).toBe(true);
}); });
})); }));
it('should not show the login base auth button', fakeAsync(() => { it('should not show the login base auth button', fakeAsync(() => {
@@ -17,7 +17,6 @@
import { CoreTestingModule, LoginComponent, LoginFooterDirective } from '@alfresco/adf-core'; import { CoreTestingModule, LoginComponent, LoginFooterDirective } from '@alfresco/adf-core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { OidcAuthenticationService } from '../../auth/services/oidc-authentication.service'; import { OidcAuthenticationService } from '../../auth/services/oidc-authentication.service';
describe('LoginFooterDirective', () => { describe('LoginFooterDirective', () => {
@@ -27,13 +26,11 @@ describe('LoginFooterDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ {
provide: OidcAuthenticationService, useValue: {} provide: OidcAuthenticationService,
useValue: {}
} }
] ]
}); });
@@ -17,7 +17,6 @@
import { CoreTestingModule, LoginComponent, LoginHeaderDirective } from '@alfresco/adf-core'; import { CoreTestingModule, LoginComponent, LoginHeaderDirective } from '@alfresco/adf-core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { OidcAuthenticationService } from '../../auth/services/oidc-authentication.service'; import { OidcAuthenticationService } from '../../auth/services/oidc-authentication.service';
describe('LoginHeaderDirective', () => { describe('LoginHeaderDirective', () => {
@@ -27,13 +26,8 @@ describe('LoginHeaderDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), providers: [{ provide: OidcAuthenticationService, useValue: {} }]
CoreTestingModule
],
providers: [
{ provide: OidcAuthenticationService, useValue: {} }
]
}); });
fixture = TestBed.createComponent(LoginComponent); fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -21,11 +21,9 @@ import { NotificationHistoryComponent } from './notification-history.component';
import { OverlayContainer } from '@angular/cdk/overlay'; import { OverlayContainer } from '@angular/cdk/overlay';
import { NotificationService } from '../services/notification.service'; import { NotificationService } from '../services/notification.service';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
import { TranslateModule } from '@ngx-translate/core';
import { NotificationModel, NOTIFICATION_TYPE } from '../models/notification.model'; import { NotificationModel, NOTIFICATION_TYPE } from '../models/notification.model';
describe('Notification History Component', () => { describe('Notification History Component', () => {
let fixture: ComponentFixture<NotificationHistoryComponent>; let fixture: ComponentFixture<NotificationHistoryComponent>;
let component: NotificationHistoryComponent; let component: NotificationHistoryComponent;
let element: HTMLElement; let element: HTMLElement;
@@ -42,10 +40,7 @@ describe('Notification History Component', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(NotificationHistoryComponent); fixture = TestBed.createComponent(NotificationHistoryComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -66,7 +61,6 @@ describe('Notification History Component', () => {
}); });
describe('ui ', () => { describe('ui ', () => {
it('should empty message be present when there are no notifications in the history', (done) => { it('should empty message be present when there are no notifications in the history', (done) => {
openNotification(); openNotification();
fixture.detectChanges(); fixture.detectChanges();
@@ -109,15 +103,12 @@ describe('Notification History Component', () => {
it('should show message when pushed directly to Notification History', (done) => { it('should show message when pushed directly to Notification History', (done) => {
const callBackSpy = jasmine.createSpy('callBack'); const callBackSpy = jasmine.createSpy('callBack');
fixture.detectChanges(); fixture.detectChanges();
notificationService.pushToNotificationHistory( notificationService.pushToNotificationHistory({
{
clickCallBack: callBackSpy, clickCallBack: callBackSpy,
messages: ['My new message'], messages: ['My new message'],
datetime: new Date(), datetime: new Date(),
type: NOTIFICATION_TYPE.RECURSIVE type: NOTIFICATION_TYPE.RECURSIVE
} as NotificationModel);
} as NotificationModel
);
openNotification(); openNotification();
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
@@ -148,12 +139,16 @@ describe('Notification History Component', () => {
}); });
it('should read notifications from local storage', (done) => { it('should read notifications from local storage', (done) => {
storage.setItem(NotificationHistoryComponent.NOTIFICATION_STORAGE, JSON.stringify([{ storage.setItem(
NotificationHistoryComponent.NOTIFICATION_STORAGE,
JSON.stringify([
{
messages: ['My new message'], messages: ['My new message'],
datetime: new Date(), datetime: new Date(),
type: NOTIFICATION_TYPE.RECURSIVE type: NOTIFICATION_TYPE.RECURSIVE
} as NotificationModel
} as NotificationModel])); ])
);
fixture.detectChanges(); fixture.detectChanges();
openNotification(); openNotification();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
@@ -21,7 +21,6 @@ import { MatSnackBarConfig, MatSnackBarModule } from '@angular/material/snack-ba
import { NotificationService } from './notification.service'; import { NotificationService } from './notification.service';
import { TranslationService } from '../../translation/translation.service'; import { TranslationService } from '../../translation/translation.service';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatIconHarness } from '@angular/material/icon/testing'; import { MatIconHarness } from '@angular/material/icon/testing';
@@ -92,7 +91,7 @@ describe('NotificationService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule, MatSnackBarModule], imports: [CoreTestingModule, MatSnackBarModule],
declarations: [ProvidesNotificationServiceComponent] declarations: [ProvidesNotificationServiceComponent]
}); });
translationService = TestBed.inject(TranslationService); translationService = TestBed.inject(TranslationService);
@@ -24,13 +24,11 @@ import { BehaviorSubject } from 'rxjs';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { Component, ChangeDetectorRef } from '@angular/core'; import { Component, ChangeDetectorRef } from '@angular/core';
import { RequestPaginationModel } from '../models/request-pagination.model'; import { RequestPaginationModel } from '../models/request-pagination.model';
import { TranslateModule } from '@ngx-translate/core';
@Component({ @Component({
template: `` template: ``
}) })
class TestPaginatedComponent implements PaginatedComponent { class TestPaginatedComponent implements PaginatedComponent {
private _pagination: BehaviorSubject<PaginationModel>; private _pagination: BehaviorSubject<PaginationModel>;
get pagination(): BehaviorSubject<PaginationModel> { get pagination(): BehaviorSubject<PaginationModel> {
@@ -52,7 +50,6 @@ class TestPaginatedComponent implements PaginatedComponent {
} }
describe('InfinitePaginationComponent', () => { describe('InfinitePaginationComponent', () => {
let fixture: ComponentFixture<InfinitePaginationComponent>; let fixture: ComponentFixture<InfinitePaginationComponent>;
let component: InfinitePaginationComponent; let component: InfinitePaginationComponent;
let pagination: PaginationModel; let pagination: PaginationModel;
@@ -60,13 +57,8 @@ describe('InfinitePaginationComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestPaginatedComponent]
CoreTestingModule
],
declarations: [
TestPaginatedComponent
]
}); });
fixture = TestBed.createComponent(InfinitePaginationComponent); fixture = TestBed.createComponent(InfinitePaginationComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -84,7 +76,6 @@ describe('InfinitePaginationComponent', () => {
}); });
describe('View', () => { describe('View', () => {
it('should show the loading spinner if loading', () => { it('should show the loading spinner if loading', () => {
pagination.hasMoreItems = true; pagination.hasMoreItems = true;
component.isLoading = true; component.isLoading = true;
@@ -194,7 +185,6 @@ describe('InfinitePaginationComponent', () => {
}); });
describe('Target', () => { describe('Target', () => {
let spyTarget; let spyTarget;
beforeEach(() => { beforeEach(() => {
@@ -203,7 +193,7 @@ describe('InfinitePaginationComponent', () => {
spyTarget = spyOn(component.target, 'updatePagination').and.callThrough(); spyTarget = spyOn(component.target, 'updatePagination').and.callThrough();
}); });
it('should subscribe to target\'s pagination observable to update pagination and pagesize correctly', () => { it('should subscribe to target pagination observable to update pagination and pagesize correctly', () => {
component.target.updatePagination(pagination); component.target.updatePagination(pagination);
fixture.detectChanges(); fixture.detectChanges();
@@ -211,7 +201,7 @@ describe('InfinitePaginationComponent', () => {
expect(component.pageSize).toBe(25); expect(component.pageSize).toBe(25);
}); });
it('should call the target\'s updatePagination on invoking the onLoadMore', () => { it('should call the target updatePagination on invoking the onLoadMore', () => {
component.target.updatePagination(pagination); component.target.updatePagination(pagination);
fixture.detectChanges(); fixture.detectChanges();
@@ -226,7 +216,7 @@ describe('InfinitePaginationComponent', () => {
}); });
}); });
it('should call the target\'s updatePagination on invoking the onLoadMore with a specific pageSize', () => { it('should call the target updatePagination on invoking the onLoadMore with a specific pageSize', () => {
component.pageSize = 7; component.pageSize = 7;
component.target.updatePagination(pagination); component.target.updatePagination(pagination);
fixture.detectChanges(); fixture.detectChanges();
@@ -241,7 +231,7 @@ describe('InfinitePaginationComponent', () => {
}); });
}); });
it('should unsubscribe from the target\'s pagination on onDestroy', () => { it('should unsubscribe from the target pagination on onDestroy', () => {
fixture.detectChanges(); fixture.detectChanges();
fixture.destroy(); fixture.destroy();
@@ -21,7 +21,6 @@ import { PaginationComponent } from './pagination.component';
import { PaginatedComponent } from './paginated-component.interface'; import { PaginatedComponent } from './paginated-component.interface';
import { BehaviorSubject } from 'rxjs'; import { BehaviorSubject } from 'rxjs';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { PaginationModel } from '../models/pagination.model'; import { PaginationModel } from '../models/pagination.model';
import { setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
@@ -33,21 +32,17 @@ class FakePaginationInput implements PaginationModel {
maxItems = 25; maxItems = 25;
constructor(pagesCount: number, currentPage: number, lastPageItems: number) { constructor(pagesCount: number, currentPage: number, lastPageItems: number) {
this.totalItems = ((pagesCount - 1) * this.maxItems) + lastPageItems; this.totalItems = (pagesCount - 1) * this.maxItems + lastPageItems;
this.skipCount = (currentPage - 1) * this.maxItems; this.skipCount = (currentPage - 1) * this.maxItems;
} }
} }
describe('PaginationComponent', () => { describe('PaginationComponent', () => {
let fixture: ComponentFixture<PaginationComponent>; let fixture: ComponentFixture<PaginationComponent>;
let component: PaginationComponent; let component: PaginationComponent;
setupTestBed({ setupTestBed({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}); });
@@ -106,7 +101,6 @@ describe('PaginationComponent', () => {
}); });
describe('Middle page', () => { describe('Middle page', () => {
// This test describes 6 pages being on the third page // This test describes 6 pages being on the third page
// and last page has 5 items // and last page has 5 items
@@ -186,7 +180,6 @@ describe('PaginationComponent', () => {
}); });
describe('First page', () => { describe('First page', () => {
// This test describes 10 pages being on the first page // This test describes 10 pages being on the first page
beforeEach(() => { beforeEach(() => {
@@ -212,7 +205,6 @@ describe('PaginationComponent', () => {
}); });
describe('Last page', () => { describe('Last page', () => {
// This test describes 10 pages being on the last page // This test describes 10 pages being on the last page
beforeEach(() => { beforeEach(() => {
@@ -255,7 +247,6 @@ describe('PaginationComponent', () => {
}); });
describe('with paginated component', () => { describe('with paginated component', () => {
it('should take pagination from the external component', () => { it('should take pagination from the external component', () => {
const pagination: PaginationModel = {}; const pagination: PaginationModel = {};
@@ -347,7 +338,6 @@ describe('PaginationComponent', () => {
expect(fixture.debugElement.nativeElement.querySelector('.adf-pagination__block')).toBeNull(); expect(fixture.debugElement.nativeElement.querySelector('.adf-pagination__block')).toBeNull();
}); });
}); });
describe('without total items', () => { describe('without total items', () => {
@@ -384,8 +374,10 @@ describe('PaginationComponent', () => {
it('should only some pages be available if over 100', () => { it('should only some pages be available if over 100', () => {
component.pagination = new FakePaginationInput(101, 30, 5); component.pagination = new FakePaginationInput(101, 30, 5);
const expectedPages = [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, const expectedPages = [
31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 101]; 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 101
];
expect(component.limitedPages).toEqual(expectedPages); expect(component.limitedPages).toEqual(expectedPages);
expect(component.limitedPages).not.toEqual(component.pages); expect(component.limitedPages).not.toEqual(component.pages);
@@ -17,7 +17,6 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { DateTimePipe } from './date-time.pipe'; import { DateTimePipe } from './date-time.pipe';
import { addMinutes, isValid } from 'date-fns'; import { addMinutes, isValid } from 'date-fns';
@@ -26,7 +25,7 @@ describe('DateTimePipe', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule], imports: [CoreTestingModule],
providers: [DateTimePipe] providers: [DateTimePipe]
}); });
@@ -21,19 +21,14 @@ import { UserPreferencesService } from '../common/services/user-preferences.serv
import { of } from 'rxjs'; import { of } from 'rxjs';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { DecimalNumberPipe } from './decimal-number.pipe'; import { DecimalNumberPipe } from './decimal-number.pipe';
import { TranslateModule } from '@ngx-translate/core';
describe('DecimalNumberPipe', () => { describe('DecimalNumberPipe', () => {
let pipe: DecimalNumberPipe; let pipe: DecimalNumberPipe;
let userPreferences: UserPreferencesService; let userPreferences: UserPreferencesService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
userPreferences = TestBed.inject(UserPreferencesService); userPreferences = TestBed.inject(UserPreferencesService);
spyOn(userPreferences, 'select').and.returnValue(of('')); spyOn(userPreferences, 'select').and.returnValue(of(''));
@@ -23,20 +23,15 @@ import { of } from 'rxjs';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { registerLocaleData } from '@angular/common'; import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr'; import localeFr from '@angular/common/locales/fr';
import { TranslateModule } from '@ngx-translate/core';
registerLocaleData(localeFr); registerLocaleData(localeFr);
describe('LocalizedDatePipe', () => { describe('LocalizedDatePipe', () => {
let pipe: LocalizedDatePipe; let pipe: LocalizedDatePipe;
let userPreferences: UserPreferencesService; let userPreferences: UserPreferencesService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
userPreferences = TestBed.inject(UserPreferencesService); userPreferences = TestBed.inject(UserPreferencesService);
spyOn(userPreferences, 'select').and.returnValue(of('')); spyOn(userPreferences, 'select').and.returnValue(of(''));
+1 -7
View File
@@ -21,19 +21,14 @@ import { AppConfigService } from '../app-config/app-config.service';
import { UserPreferencesService } from '../common/services/user-preferences.service'; import { UserPreferencesService } from '../common/services/user-preferences.service';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
describe('TimeAgoPipe', () => { describe('TimeAgoPipe', () => {
let pipe: TimeAgoPipe; let pipe: TimeAgoPipe;
let userPreferences: UserPreferencesService; let userPreferences: UserPreferencesService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
userPreferences = TestBed.inject(UserPreferencesService); userPreferences = TestBed.inject(UserPreferencesService);
spyOn(userPreferences, 'select').and.returnValue(of('')); spyOn(userPreferences, 'select').and.returnValue(of(''));
@@ -56,7 +51,6 @@ describe('TimeAgoPipe', () => {
}); });
describe('When a locale is given', () => { describe('When a locale is given', () => {
it('should return a localised message', () => { it('should return a localised message', () => {
const date = new Date(); const date = new Date();
const transformedDate = pipe.transform(date, 'de'); const transformedDate = pipe.transform(date, 'de');
@@ -21,11 +21,9 @@ import { SearchTextInputComponent } from './search-text-input.component';
import { DebugElement } from '@angular/core'; import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
import { UserPreferencesService } from '../common/services/user-preferences.service'; import { UserPreferencesService } from '../common/services/user-preferences.service';
describe('SearchTextInputComponent', () => { describe('SearchTextInputComponent', () => {
let fixture: ComponentFixture<SearchTextInputComponent>; let fixture: ComponentFixture<SearchTextInputComponent>;
let component: SearchTextInputComponent; let component: SearchTextInputComponent;
let debugElement: DebugElement; let debugElement: DebugElement;
@@ -34,10 +32,7 @@ describe('SearchTextInputComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(SearchTextInputComponent); fixture = TestBed.createComponent(SearchTextInputComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -52,7 +47,6 @@ describe('SearchTextInputComponent', () => {
}); });
describe('component rendering', () => { describe('component rendering', () => {
it('should display a search input field when specified', async () => { it('should display a search input field when specified', async () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
@@ -67,7 +61,6 @@ describe('SearchTextInputComponent', () => {
}); });
describe('expandable option false', () => { describe('expandable option false', () => {
beforeEach(() => { beforeEach(() => {
component.expandable = false; component.expandable = false;
}); });
@@ -86,7 +79,6 @@ describe('SearchTextInputComponent', () => {
}); });
describe('search button', () => { describe('search button', () => {
it('should NOT display a autocomplete list control when configured not to', fakeAsync(() => { it('should NOT display a autocomplete list control when configured not to', fakeAsync(() => {
fixture.detectChanges(); fixture.detectChanges();
@@ -345,7 +337,6 @@ describe('SearchTextInputComponent', () => {
expect(component.subscriptAnimationState.value).toEqual('inactive'); expect(component.subscriptAnimationState.value).toEqual('inactive');
expect(component.searchTerm).toEqual(''); expect(component.searchTerm).toEqual('');
}); });
}); });
describe('Collapse on blur', () => { describe('Collapse on blur', () => {
@@ -20,8 +20,8 @@ import { MatIcon, MatIconModule } from '@angular/material/icon';
import { MAT_SNACK_BAR_DATA, MatSnackBarModule, MatSnackBarRef } from '@angular/material/snack-bar'; import { MAT_SNACK_BAR_DATA, MatSnackBarModule, MatSnackBarRef } from '@angular/material/snack-bar';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
import { SnackbarContentComponent } from './snackbar-content.component'; import { SnackbarContentComponent } from './snackbar-content.component';
import { CoreTestingModule } from '@alfresco/adf-core';
describe('SnackbarContentComponent', () => { describe('SnackbarContentComponent', () => {
let component: SnackbarContentComponent; let component: SnackbarContentComponent;
@@ -30,24 +30,20 @@ describe('SnackbarContentComponent', () => {
beforeEach(async () => { beforeEach(async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
declarations: [SnackbarContentComponent], declarations: [SnackbarContentComponent],
imports: [ imports: [CoreTestingModule, MatIconModule, MatSnackBarModule, MatButtonModule],
MatIconModule, providers: [
MatSnackBarModule, {
MatButtonModule,
TranslateModule.forRoot()
],
providers: [{
provide: MatSnackBarRef, provide: MatSnackBarRef,
useValue: { useValue: {
dismissWithAction() { dismissWithAction() {}
} }
} },
}, { {
provide: MAT_SNACK_BAR_DATA, provide: MAT_SNACK_BAR_DATA,
useValue: {} useValue: {}
}] }
}) ]
.compileComponents(); }).compileComponents();
fixture = TestBed.createComponent(SnackbarContentComponent); fixture = TestBed.createComponent(SnackbarContentComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@@ -18,17 +18,14 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { TranslateService, TranslateModule } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
template: ` template: `
<adf-empty-content <adf-empty-content icon="delete" [title]="'CUSTOM_TITLE'" [subtitle]="'CUSTOM_SUBTITLE'">
icon="delete"
[title]="'CUSTOM_TITLE'"
[subtitle]="'CUSTOM_SUBTITLE'">
<div class="adf-empty-content__text">SUBTITLE-1</div> <div class="adf-empty-content__text">SUBTITLE-1</div>
<div class="adf-empty-content__text">SUBTITLE-2</div> <div class="adf-empty-content__text">SUBTITLE-2</div>
<div class="adf-empty-content__text">SUBTITLE-3</div> <div class="adf-empty-content__text">SUBTITLE-3</div>
@@ -38,19 +35,13 @@ import { CoreTestingModule } from '../../testing/core.testing.module';
class TestComponent {} class TestComponent {}
describe('EmptyContentComponent', () => { describe('EmptyContentComponent', () => {
let fixture: ComponentFixture<TestComponent>; let fixture: ComponentFixture<TestComponent>;
let translateService: TranslateService; let translateService: TranslateService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), declarations: [TestComponent]
CoreTestingModule
],
declarations: [
TestComponent
]
}); });
fixture = TestBed.createComponent(TestComponent); fixture = TestBed.createComponent(TestComponent);
translateService = TestBed.inject(TranslateService); translateService = TestBed.inject(TranslateService);
@@ -21,10 +21,8 @@ import { ErrorContentComponent } from './error-content.component';
import { TranslationService } from '../../translation/translation.service'; import { TranslationService } from '../../translation/translation.service';
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
describe('ErrorContentComponent', () => { describe('ErrorContentComponent', () => {
let fixture: ComponentFixture<ErrorContentComponent>; let fixture: ComponentFixture<ErrorContentComponent>;
let errorContentComponent: ErrorContentComponent; let errorContentComponent: ErrorContentComponent;
let element: HTMLElement; let element: HTMLElement;
@@ -32,13 +30,8 @@ describe('ErrorContentComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), providers: [{ provide: ActivatedRoute, useValue: { params: of() } }]
CoreTestingModule
],
providers: [
{ provide: ActivatedRoute, useValue: { params: of() } }
]
}); });
fixture = TestBed.createComponent(ErrorContentComponent); fixture = TestBed.createComponent(ErrorContentComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
@@ -16,7 +16,6 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { CoreTestingModule } from '../testing/core.testing.module'; import { CoreTestingModule } from '../testing/core.testing.module';
import { ToolbarComponent } from './toolbar.component'; import { ToolbarComponent } from './toolbar.component';
import { ToolbarModule } from './toolbar.module'; import { ToolbarModule } from './toolbar.module';
@@ -26,11 +25,7 @@ describe('ToolbarComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule, ToolbarModule]
TranslateModule.forRoot(),
CoreTestingModule,
ToolbarModule
]
}); });
fixture = TestBed.createComponent(ToolbarComponent); fixture = TestBed.createComponent(ToolbarComponent);
@@ -19,7 +19,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { MatDialogRef } from '@angular/material/dialog'; import { MatDialogRef } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { DownloadPromptDialogComponent } from './download-prompt-dialog.component'; import { DownloadPromptDialogComponent } from './download-prompt-dialog.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../testing/core.testing.module';
import { DownloadPromptActions } from '../../models/download-prompt.actions'; import { DownloadPromptActions } from '../../models/download-prompt.actions';
@@ -37,13 +36,8 @@ describe('DownloadPromptDialogComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [DownloadPromptDialogComponent], declarations: [DownloadPromptDialogComponent],
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(), providers: [{ provide: MatDialogRef, useValue: mockDialog }]
CoreTestingModule
],
providers: [
{ provide: MatDialogRef, useValue: mockDialog }
]
}); });
matDialogRef = TestBed.inject(MatDialogRef); matDialogRef = TestBed.inject(MatDialogRef);
@@ -21,11 +21,9 @@ import { UrlService } from '../../common/services/url.service';
import { ImgViewerComponent } from './img-viewer.component'; import { ImgViewerComponent } from './img-viewer.component';
import { CoreTestingModule } from '../../testing'; import { CoreTestingModule } from '../../testing';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.service';
import { TranslateModule } from '@ngx-translate/core';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
describe('Test Img viewer component ', () => { describe('Test Img viewer component ', () => {
let component: ImgViewerComponent; let component: ImgViewerComponent;
let urlService: UrlService; let urlService: UrlService;
let fixture: ComponentFixture<ImgViewerComponent>; let fixture: ComponentFixture<ImgViewerComponent>;
@@ -38,15 +36,11 @@ describe('Test Img viewer component ', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
}); });
describe('Zoom customization', () => { describe('Zoom customization', () => {
beforeEach(() => { beforeEach(() => {
urlService = TestBed.inject(UrlService); urlService = TestBed.inject(UrlService);
fixture = TestBed.createComponent(ImgViewerComponent); fixture = TestBed.createComponent(ImgViewerComponent);
@@ -58,16 +52,13 @@ describe('Test Img viewer component ', () => {
}); });
describe('default value', () => { describe('default value', () => {
it('should use default zoom if is not present a custom zoom in the app.config', () => { it('should use default zoom if is not present a custom zoom in the app.config', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(component.scale).toBe(1.0); expect(component.scale).toBe(1.0);
}); });
}); });
describe('custom value', () => { describe('custom value', () => {
beforeEach(() => { beforeEach(() => {
const appConfig: AppConfigService = TestBed.inject(AppConfigService); const appConfig: AppConfigService = TestBed.inject(AppConfigService);
appConfig.config['adf-viewer-render.image-viewer-scaling'] = 70; appConfig.config['adf-viewer-render.image-viewer-scaling'] = 70;
@@ -78,7 +69,7 @@ describe('Test Img viewer component ', () => {
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
expect(component.scale).toBe(0.70); expect(component.scale).toBe(0.7);
done(); done();
}); });
}); });
@@ -86,14 +77,14 @@ describe('Test Img viewer component ', () => {
}); });
describe('Url', () => { describe('Url', () => {
beforeEach(() => { beforeEach(() => {
urlService = TestBed.inject(UrlService); urlService = TestBed.inject(UrlService);
fixture = TestBed.createComponent(ImgViewerComponent); fixture = TestBed.createComponent(ImgViewerComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
component = fixture.componentInstance; component = fixture.componentInstance;
component.urlFile = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; component.urlFile =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
fixture.detectChanges(); fixture.detectChanges();
fixture.componentInstance.ngAfterViewInit(); fixture.componentInstance.ngAfterViewInit();
component.ngAfterViewInit(); component.ngAfterViewInit();
@@ -115,7 +106,6 @@ describe('Test Img viewer component ', () => {
}); });
describe('Blob', () => { describe('Blob', () => {
beforeEach(() => { beforeEach(() => {
urlService = TestBed.inject(UrlService); urlService = TestBed.inject(UrlService);
fixture = TestBed.createComponent(ImgViewerComponent); fixture = TestBed.createComponent(ImgViewerComponent);
@@ -169,7 +159,6 @@ describe('Test Img viewer component ', () => {
}); });
describe('toolbar actions', () => { describe('toolbar actions', () => {
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(ImgViewerComponent); fixture = TestBed.createComponent(ImgViewerComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
@@ -381,5 +370,4 @@ describe('Test Img viewer component ', () => {
expect(component.reset).toHaveBeenCalled(); expect(component.reset).toHaveBeenCalled();
}); });
}); });
}); });
@@ -19,7 +19,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { PdfPasswordDialogComponent } from './pdf-viewer-password-dialog'; import { PdfPasswordDialogComponent } from './pdf-viewer-password-dialog';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
declare const pdfjsLib: any; declare const pdfjsLib: any;
@@ -30,10 +29,7 @@ describe('PdfPasswordDialogComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [CoreTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ {
provide: MAT_DIALOG_DATA, provide: MAT_DIALOG_DATA,

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