ACS-8761 Noop Auth Module for unit testing ergonomics (#10195)

This commit is contained in:
Denys Vuika 2024-09-18 08:05:26 -04:00 committed by GitHub
parent 075c6891fe
commit 4d4a1dd6b1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
69 changed files with 630 additions and 836 deletions

View File

@ -27,7 +27,6 @@ import { AspectEntry, Node } from '@alfresco/js-api';
import { NodesApiService } from '../common/services/nodes-api.service'; import { NodesApiService } from '../common/services/nodes-api.service';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { AspectListComponent } from './aspect-list.component'; import { AspectListComponent } from './aspect-list.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
const aspectListMock: AspectEntry[] = [ const aspectListMock: AspectEntry[] = [
{ {
@ -114,7 +113,7 @@ describe('AspectListDialogComponent', () => {
excludedAspects: [] excludedAspects: []
}; };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [HttpClientTestingModule, ContentTestingModule, MatDialogModule], imports: [ContentTestingModule, MatDialogModule],
providers: [ providers: [
{ provide: MAT_DIALOG_DATA, useValue: data }, { provide: MAT_DIALOG_DATA, useValue: data },
{ {

View File

@ -28,7 +28,6 @@ import { CategoryService } from '../../category';
providedIn: 'root' providedIn: 'root'
}) })
export class DialogAspectListService { export class DialogAspectListService {
constructor( constructor(
private dialog: MatDialog, private dialog: MatDialog,
private overlayContainer: OverlayContainer, private overlayContainer: OverlayContainer,
@ -49,8 +48,8 @@ export class DialogAspectListService {
select, select,
nodeId, nodeId,
excludedAspects: [ excludedAspects: [
...this.tagService.areTagsEnabled() ? [] : ['cm:taggable'], ...(this.tagService.areTagsEnabled() ? [] : ['cm:taggable']),
...this.categoryService.areCategoriesEnabled() ? [] : ['cm:generalclassifiable'] ...(this.categoryService.areCategoriesEnabled() ? [] : ['cm:generalclassifiable'])
] ]
}; };
@ -58,15 +57,17 @@ export class DialogAspectListService {
return select; return select;
} }
private openDialog(data: AspectListDialogComponentData, panelClass: string, width: string, private openDialog(data: AspectListDialogComponentData, panelClass: string, width: string, selectorAutoFocusedOnClose?: string) {
selectorAutoFocusedOnClose?: string) { this.dialog
this.dialog.open(AspectListDialogComponent, { .open(AspectListDialogComponent, {
data, data,
panelClass, panelClass,
width, width,
role: 'dialog', role: 'dialog',
disableClose: true disableClose: true
}).afterClosed().subscribe(() => this.focusOnClose(selectorAutoFocusedOnClose)); })
.afterClosed()
.subscribe(() => this.focusOnClose(selectorAutoFocusedOnClose));
this.overlayContainer.getContainerElement().setAttribute('role', 'main'); this.overlayContainer.getContainerElement().setAttribute('role', 'main');
} }
@ -77,7 +78,7 @@ export class DialogAspectListService {
private focusOnClose(selectorAutoFocusedOnClose: string): void { private focusOnClose(selectorAutoFocusedOnClose: string): void {
if (selectorAutoFocusedOnClose) { if (selectorAutoFocusedOnClose) {
document.querySelector<HTMLElement>(selectorAutoFocusedOnClose).focus(); document.querySelector<HTMLElement>(selectorAutoFocusedOnClose)?.focus();
} }
} }
} }

View File

@ -20,22 +20,17 @@ import { By } from '@angular/platform-browser';
import { Node } from '@alfresco/js-api'; import { Node } from '@alfresco/js-api';
import { ContentMetadataCardComponent } from './content-metadata-card.component'; import { ContentMetadataCardComponent } from './content-metadata-card.component';
import { ContentMetadataComponent } from '../content-metadata/content-metadata.component'; import { ContentMetadataComponent } from '../content-metadata/content-metadata.component';
import { APP_INITIALIZER, SimpleChange } from '@angular/core'; import { SimpleChange } from '@angular/core';
import { NodeAspectService } from '../../../aspect-list/services/node-aspect.service'; import { NodeAspectService } from '../../../aspect-list/services/node-aspect.service';
import { ContentMetadataService } from '../../services/content-metadata.service'; import { ContentMetadataService } from '../../services/content-metadata.service';
import { AllowableOperationsEnum } from '../../../common/models/allowable-operations.enum'; import { AllowableOperationsEnum } from '../../../common/models/allowable-operations.enum';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { AuthModule, NoopTranslateModule } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { versionCompatibilityFactory } from '../../../version-compatibility/version-compatibility-factory';
import { VersionCompatibilityService } from '../../../version-compatibility';
import { MatDialogModule } from '@angular/material/dialog'; import { MatDialogModule } from '@angular/material/dialog';
import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBarModule } from '@angular/material/snack-bar';
import { CategoryService } from '../../../category'; import { CategoryService } from '../../../category';
import { TagService } from '../../../tag'; import { TagService } from '../../../tag';
import { PropertyDescriptorsService } from '../../public-api'; import { PropertyDescriptorsService } from '../../public-api';
import { AlfrescoApiService } from '../../../services/alfresco-api.service'; import { ContentTestingModule } from '../../../testing/content.testing.module';
import { AlfrescoApiServiceMock } from '../../../mock/alfresco-api.service.mock';
describe('ContentMetadataCardComponent', () => { describe('ContentMetadataCardComponent', () => {
let component: ContentMetadataCardComponent; let component: ContentMetadataCardComponent;
@ -52,23 +47,7 @@ describe('ContentMetadataCardComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [ContentTestingModule, MatDialogModule, MatSnackBarModule, ContentMetadataCardComponent]
NoopAnimationsModule,
NoopTranslateModule,
AuthModule.forRoot({ useHash: true }),
MatDialogModule,
MatSnackBarModule,
ContentMetadataCardComponent
],
providers: [
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock },
{
provide: APP_INITIALIZER,
useFactory: versionCompatibilityFactory,
deps: [VersionCompatibilityService],
multi: true
}
]
}); });
fixture = TestBed.createComponent(ContentMetadataCardComponent); fixture = TestBed.createComponent(ContentMetadataCardComponent);
contentMetadataService = TestBed.inject(ContentMetadataService); contentMetadataService = TestBed.inject(ContentMetadataService);

View File

@ -21,22 +21,13 @@ import { By } from '@angular/platform-browser';
import { Category, CategoryPaging, ClassesApi, Node, Tag, TagBody, TagEntry, TagPaging, TagPagingList } from '@alfresco/js-api'; import { Category, CategoryPaging, ClassesApi, Node, Tag, TagBody, TagEntry, TagPaging, TagPagingList } from '@alfresco/js-api';
import { ContentMetadataComponent } from './content-metadata.component'; import { ContentMetadataComponent } from './content-metadata.component';
import { ContentMetadataService } from '../../services/content-metadata.service'; import { ContentMetadataService } from '../../services/content-metadata.service';
import { import { AppConfigService, CardViewBaseItemModel, CardViewComponent, NotificationService, UpdateNotification } from '@alfresco/adf-core';
AppConfigService,
AuthModule,
CardViewBaseItemModel,
CardViewComponent,
NoopTranslateModule,
NotificationService,
UpdateNotification
} from '@alfresco/adf-core';
import { NodesApiService } from '../../../common/services/nodes-api.service'; import { NodesApiService } from '../../../common/services/nodes-api.service';
import { EMPTY, of, throwError } from 'rxjs'; import { EMPTY, of, throwError } from 'rxjs';
import { CardViewContentUpdateService } from '../../../common/services/card-view-content-update.service'; import { CardViewContentUpdateService } from '../../../common/services/card-view-content-update.service';
import { PropertyGroup } from '../../interfaces/property-group.interface'; import { PropertyGroup } from '../../interfaces/property-group.interface';
import { PropertyDescriptorsService } from '../../services/property-descriptors.service'; import { PropertyDescriptorsService } from '../../services/property-descriptors.service';
import { MatExpansionPanel } from '@angular/material/expansion'; import { MatExpansionPanel } from '@angular/material/expansion';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { MatDialogModule } from '@angular/material/dialog'; import { MatDialogModule } from '@angular/material/dialog';
import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBarModule } from '@angular/material/snack-bar';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
@ -45,6 +36,7 @@ import { TagService } from '../../../tag/services/tag.service';
import { CategoryService } from '../../../category/services/category.service'; import { CategoryService } from '../../../category/services/category.service';
import { TagsCreatorComponent, TagsCreatorMode } from '../../../tag'; import { TagsCreatorComponent, TagsCreatorMode } from '../../../tag';
import { CategoriesManagementComponent, CategoriesManagementMode } from '../../../category'; import { CategoriesManagementComponent, CategoriesManagementMode } from '../../../category';
import { ContentTestingModule } from '../../../testing/content.testing.module';
describe('ContentMetadataComponent', () => { describe('ContentMetadataComponent', () => {
let component: ContentMetadataComponent; let component: ContentMetadataComponent;
@ -176,14 +168,7 @@ describe('ContentMetadataComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [ContentTestingModule, MatDialogModule, MatSnackBarModule, ContentMetadataComponent],
NoopAnimationsModule,
NoopTranslateModule,
AuthModule.forRoot({ useHash: true }),
MatDialogModule,
MatSnackBarModule,
ContentMetadataComponent
],
providers: [ providers: [
{ {
provide: TagService, provide: TagService,

View File

@ -17,16 +17,7 @@
import { NgModule, APP_INITIALIZER } from '@angular/core'; import { NgModule, APP_INITIALIZER } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing'; import { CoreModule, NoopTranslateModule, NoopAuthModule } from '@alfresco/adf-core';
import {
CoreModule,
AppConfigService,
CookieService,
AppConfigServiceMock,
CookieServiceMock,
AuthModule,
NoopTranslateModule
} from '@alfresco/adf-core';
import { ContentModule } from '../content.module'; import { ContentModule } from '../content.module';
import { versionCompatibilityFactory } from '../version-compatibility/version-compatibility-factory'; import { versionCompatibilityFactory } from '../version-compatibility/version-compatibility-factory';
import { AlfrescoApiService } from '../services/alfresco-api.service'; import { AlfrescoApiService } from '../services/alfresco-api.service';
@ -35,19 +26,9 @@ import { MatIconTestingModule } from '@angular/material/icon/testing';
import { AlfrescoApiServiceMock } from '../mock'; import { AlfrescoApiServiceMock } from '../mock';
@NgModule({ @NgModule({
imports: [ imports: [NoopAnimationsModule, CoreModule, NoopAuthModule, NoopTranslateModule, ContentModule, MatIconTestingModule],
AuthModule.forRoot({ useHash: true }),
NoopAnimationsModule,
RouterTestingModule,
CoreModule,
NoopTranslateModule,
ContentModule,
MatIconTestingModule
],
providers: [ providers: [
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }, { provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock },
{ provide: AppConfigService, useClass: AppConfigServiceMock },
{ provide: CookieService, useClass: CookieServiceMock },
{ {
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
useFactory: versionCompatibilityFactory, useFactory: versionCompatibilityFactory,

View File

@ -21,29 +21,40 @@ import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testin
import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { AppExtensionService, ViewerExtensionRef } from '@alfresco/adf-extensions'; import { AppExtensionService, ViewerExtensionRef } from '@alfresco/adf-extensions';
import { ContentInfo, Node, NodeEntry, VersionEntry } from '@alfresco/js-api'; import { ContentInfo, Node, NodeEntry, VersionEntry } from '@alfresco/js-api';
import { AlfrescoViewerComponent, ContentService, NodeActionsService, RenditionService } from '@alfresco/adf-content-services';
import { import {
AuthModule,
CloseButtonPosition, CloseButtonPosition,
EventMock, EventMock,
ViewUtilService, ViewUtilService,
ViewerComponent, ViewerComponent,
VIEWER_DIRECTIVES, VIEWER_DIRECTIVES,
ViewerSidebarComponent, ViewerSidebarComponent,
NoopTranslateModule NoopTranslateModule,
ViewerToolbarComponent,
ViewerOpenWithComponent,
ViewerMoreActionsComponent,
ViewerToolbarActionsComponent,
NoopAuthModule
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { NodesApiService } from '../../common/services/nodes-api.service'; import { NodesApiService } from '../../common/services/nodes-api.service';
import { UploadService } from '../../common/services/upload.service'; import { UploadService } from '../../common/services/upload.service';
import { FileModel } from '../../common/models/file.model'; import { FileModel } from '../../common/models/file.model';
import { throwError } from 'rxjs'; import { throwError } from 'rxjs';
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { Component } from '@angular/core';
import { ESCAPE } from '@angular/cdk/keycodes'; import { ESCAPE } from '@angular/cdk/keycodes';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { AlfrescoApiService } from '../../services'; import { MatIconModule } from '@angular/material/icon';
import { AlfrescoApiServiceMock } from '../../mock'; import { MatMenuModule } from '@angular/material/menu';
import { MatButtonModule } from '@angular/material/button';
import { AlfrescoViewerComponent } from './alfresco-viewer.component';
import { RenditionService } from '../../common/services/rendition.service';
import { NodeActionsService } from '../../document-list/services/node-actions.service';
import { ContentTestingModule } from '../../testing/content.testing.module';
import { ContentService } from '../../common/services/content.service';
@Component({ @Component({
selector: 'adf-viewer-container-toolbar', selector: 'adf-viewer-container-toolbar',
standalone: true,
imports: [ViewerToolbarComponent, AlfrescoViewerComponent],
template: ` template: `
<adf-alfresco-viewer> <adf-alfresco-viewer>
<adf-viewer-toolbar> <adf-viewer-toolbar>
@ -56,22 +67,24 @@ class ViewerWithCustomToolbarComponent {}
@Component({ @Component({
selector: 'adf-viewer-container-toolbar-actions', selector: 'adf-viewer-container-toolbar-actions',
template: ` standalone: true,
<adf-alfresco-viewer> imports: [MatIconModule, MatButtonModule, ViewerToolbarActionsComponent, AlfrescoViewerComponent],
<adf-viewer-toolbar-actions> template: `<adf-alfresco-viewer>
<button mat-icon-button id="custom-button"> <adf-viewer-toolbar-actions>
<mat-icon>alarm</mat-icon> <button mat-icon-button id="custom-button">
</button> <mat-icon>alarm</mat-icon>
</adf-viewer-toolbar-actions> </button>
</adf-alfresco-viewer> </adf-viewer-toolbar-actions>
` </adf-alfresco-viewer>`
}) })
class ViewerWithCustomToolbarActionsComponent {} class ViewerWithCustomToolbarActionsComponent {}
@Component({ @Component({
selector: 'adf-viewer-container-sidebar', selector: 'adf-viewer-container-sidebar',
standalone: true,
imports: [ViewerSidebarComponent, AlfrescoViewerComponent],
template: ` template: `
<adf-alfresco-viewer> <adf-alfresco-viewer [allowRightSidebar]="true" [showRightSidebar]="true" [nodeId]="'1'">
<adf-viewer-sidebar> <adf-viewer-sidebar>
<div class="custom-sidebar"></div> <div class="custom-sidebar"></div>
</adf-viewer-sidebar> </adf-viewer-sidebar>
@ -88,6 +101,8 @@ class DummyDialogComponent {}
@Component({ @Component({
selector: 'adf-viewer-container-open-with', selector: 'adf-viewer-container-open-with',
standalone: true,
imports: [MatIconModule, MatMenuModule, ViewerOpenWithComponent, AlfrescoViewerComponent],
template: ` template: `
<adf-alfresco-viewer> <adf-alfresco-viewer>
<adf-viewer-open-with> <adf-viewer-open-with>
@ -111,24 +126,24 @@ class ViewerWithCustomOpenWithComponent {}
@Component({ @Component({
selector: 'adf-viewer-container-more-actions', selector: 'adf-viewer-container-more-actions',
template: ` standalone: true,
<adf-alfresco-viewer> imports: [MatIconModule, MatMenuModule, ViewerMoreActionsComponent, AlfrescoViewerComponent],
<adf-viewer-more-actions> template: ` <adf-alfresco-viewer>
<button mat-menu-item> <adf-viewer-more-actions>
<mat-icon>dialpad</mat-icon> <button mat-menu-item>
<span>Action One</span> <mat-icon>dialpad</mat-icon>
</button> <span>Action One</span>
<button mat-menu-item [disabled]="true"> </button>
<mat-icon>voicemail</mat-icon> <button mat-menu-item [disabled]="true">
<span>Action Two</span> <mat-icon>voicemail</mat-icon>
</button> <span>Action Two</span>
<button mat-menu-item> </button>
<mat-icon>notifications_off</mat-icon> <button mat-menu-item>
<span>Action Three</span> <mat-icon>notifications_off</mat-icon>
</button> <span>Action Three</span>
</adf-viewer-more-actions> </button>
</adf-alfresco-viewer> </adf-viewer-more-actions>
` </adf-alfresco-viewer>`
}) })
class ViewerWithCustomMoreActionsComponent {} class ViewerWithCustomMoreActionsComponent {}
@ -147,8 +162,12 @@ describe('AlfrescoViewerComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [AuthModule.forRoot({ useHash: true }), MatDialogModule, NoopTranslateModule, ...VIEWER_DIRECTIVES], imports: [
declarations: [ ContentTestingModule,
NoopAuthModule,
MatDialogModule,
NoopTranslateModule,
...VIEWER_DIRECTIVES,
ViewerWithCustomToolbarComponent, ViewerWithCustomToolbarComponent,
ViewerWithCustomSidebarComponent, ViewerWithCustomSidebarComponent,
ViewerWithCustomOpenWithComponent, ViewerWithCustomOpenWithComponent,
@ -157,19 +176,16 @@ describe('AlfrescoViewerComponent', () => {
], ],
providers: [ providers: [
ContentService, ContentService,
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock },
{ {
provide: RenditionService, provide: RenditionService,
useValue: { useValue: {
getNodeRendition: () => throwError('thrown'), getNodeRendition: () => throwError(() => new Error('thrown')),
generateMediaTracksRendition: () => {} generateMediaTracksRendition: () => {}
} }
}, },
{ provide: Location, useClass: SpyLocation }, { provide: Location, useClass: SpyLocation },
MatDialog, MatDialog
ViewerSidebarComponent ]
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}); });
fixture = TestBed.createComponent(AlfrescoViewerComponent); fixture = TestBed.createComponent(AlfrescoViewerComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
@ -380,33 +396,39 @@ describe('AlfrescoViewerComponent', () => {
}); });
}); });
it('should stop propagation on sidebar keydown event [keydown]', fakeAsync(() => { it('should stop propagation on sidebar keydown event [keydown]', async () => {
const customFixture = TestBed.createComponent(ViewerWithCustomSidebarComponent); const customFixture = TestBed.createComponent(ViewerWithCustomSidebarComponent);
const customElement: HTMLElement = customFixture.nativeElement; const customElement: HTMLElement = customFixture.nativeElement;
const escapeKeyboardEvent = new KeyboardEvent('keydown', { key: ESCAPE.toString() }); const escapeKeyboardEvent = new KeyboardEvent('keydown', { key: ESCAPE.toString() });
const stopPropagationSpy = spyOn(escapeKeyboardEvent, 'stopPropagation'); const stopPropagationSpy = spyOn(escapeKeyboardEvent, 'stopPropagation');
customFixture.detectChanges(); customFixture.detectChanges();
const viewerSidebarElement = customElement.querySelector('adf-viewer-sidebar'); await customFixture.whenStable();
const viewerSidebarElement = customElement.querySelector('.adf-viewer-sidebar');
viewerSidebarElement.dispatchEvent(escapeKeyboardEvent); viewerSidebarElement.dispatchEvent(escapeKeyboardEvent);
customFixture.detectChanges();
expect(stopPropagationSpy).toHaveBeenCalled(); expect(stopPropagationSpy).toHaveBeenCalled();
})); });
it('should stop propagation on sidebar keyup event [keyup]', fakeAsync(() => { it('should stop propagation on sidebar keyup event [keyup]', async () => {
const customFixture = TestBed.createComponent(ViewerWithCustomSidebarComponent); const customFixture = TestBed.createComponent(ViewerWithCustomSidebarComponent);
const customElement: HTMLElement = customFixture.nativeElement; const customElement: HTMLElement = customFixture.nativeElement;
const escapeKeyboardEvent = new KeyboardEvent('keyup', { key: ESCAPE.toString() }); const escapeKeyboardEvent = new KeyboardEvent('keyup', { key: ESCAPE.toString() });
const stopPropagationSpy = spyOn(escapeKeyboardEvent, 'stopPropagation'); const stopPropagationSpy = spyOn(escapeKeyboardEvent, 'stopPropagation');
customFixture.detectChanges(); customFixture.detectChanges();
const viewerSidebarElement = customElement.querySelector('adf-viewer-sidebar'); await customFixture.whenStable();
const viewerSidebarElement = customElement.querySelector('.adf-viewer-sidebar');
viewerSidebarElement.dispatchEvent(escapeKeyboardEvent); viewerSidebarElement.dispatchEvent(escapeKeyboardEvent);
await customFixture.whenStable();
expect(stopPropagationSpy).toHaveBeenCalled(); expect(stopPropagationSpy).toHaveBeenCalled();
})); });
}); });
describe('error handling', () => { describe('error handling', () => {

View File

@ -22,7 +22,7 @@ import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@ang
// First, initialize the Angular testing environment. // First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), {
teardown: { destroyAfterEach: false } teardown: { destroyAfterEach: true }
}); });
declare const pdfjsLib: any; declare const pdfjsLib: any;

View File

@ -17,7 +17,7 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { StorageFeaturesService } from './storage-features.service'; import { StorageFeaturesService } from './storage-features.service';
import { CoreTestingModule, StorageService } from '../../../../src/public-api'; import { StorageService } from '../../../../src/public-api';
import { FlagSet, WritableFeaturesServiceConfigToken } from '../interfaces/features.interface'; import { FlagSet, WritableFeaturesServiceConfigToken } from '../interfaces/features.interface';
import { skip, take } from 'rxjs/operators'; import { skip, take } from 'rxjs/operators';
@ -41,7 +41,6 @@ describe('StorageFeaturesService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule],
providers: [ providers: [
{ provide: StorageService, useValue: mockStorage }, { provide: StorageService, useValue: mockStorage },
{ {
@ -49,8 +48,7 @@ describe('StorageFeaturesService', () => {
useValue: { useValue: {
storageKey: 'storage-key-test' storageKey: 'storage-key-test'
} }
}, }
StorageFeaturesService
] ]
}); });
@ -170,11 +168,6 @@ describe('StorageFeaturesService', () => {
describe('if flags are not present in LocalStorage and no configuration is provided', () => { describe('if flags are not present in LocalStorage and no configuration is provided', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({
imports: [CoreTestingModule],
providers: [StorageFeaturesService]
});
storageFeaturesService = TestBed.inject(StorageFeaturesService); storageFeaturesService = TestBed.inject(StorageFeaturesService);
}); });

View File

@ -30,7 +30,7 @@ import {
import { FlagSetParser } from './flagset.parser'; import { FlagSetParser } from './flagset.parser';
import { StorageService } from '@alfresco/adf-core'; import { StorageService } from '@alfresco/adf-core';
@Injectable() @Injectable({ providedIn: 'root' })
export class StorageFeaturesService implements IFeaturesService, IWritableFeaturesService { export class StorageFeaturesService implements IFeaturesService, IWritableFeaturesService {
private currentFlagState: WritableFlagChangeset = {}; private currentFlagState: WritableFlagChangeset = {};
private flags = new BehaviorSubject<WritableFlagChangeset>({}); private flags = new BehaviorSubject<WritableFlagChangeset>({});

View File

@ -16,7 +16,7 @@
*/ */
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { ObjectUtils } from '../common/utils/object-utils'; import { ObjectUtils } from '../common/utils/object-utils';
import { Observable, ReplaySubject } from 'rxjs'; import { Observable, ReplaySubject } from 'rxjs';
import { map, distinctUntilChanged, take } from 'rxjs/operators'; import { map, distinctUntilChanged, take } from 'rxjs/operators';
@ -63,6 +63,9 @@ export enum Status {
providedIn: 'root' providedIn: 'root'
}) })
export class AppConfigService { export class AppConfigService {
protected http = inject(HttpClient);
protected extensionService = inject(ExtensionService);
config: any = { config: any = {
application: { application: {
name: 'Alfresco ADF Application' name: 'Alfresco ADF Application'
@ -80,11 +83,11 @@ export class AppConfigService {
return this.status === Status.LOADED; return this.status === Status.LOADED;
} }
constructor(protected http: HttpClient, protected extensionService: ExtensionService) { constructor() {
this.onLoadSubject = new ReplaySubject(); this.onLoadSubject = new ReplaySubject();
this.onLoad = this.onLoadSubject.asObservable(); this.onLoad = this.onLoadSubject.asObservable();
extensionService.setup$.subscribe((config) => { this.extensionService.setup$.subscribe((config) => {
this.onExtensionsLoaded(config); this.onExtensionsLoaded(config);
}); });
} }

View File

@ -16,25 +16,23 @@
*/ */
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { StorageService } from '../common/services/storage.service'; import { StorageService } from '../common/services/storage.service';
import { AppConfigService, AppConfigValues } from './app-config.service'; import { AppConfigService, AppConfigValues } from './app-config.service';
import { ExtensionService } from '@alfresco/adf-extensions';
@Injectable() @Injectable()
export class DebugAppConfigService extends AppConfigService { export class DebugAppConfigService extends AppConfigService {
constructor(private storage: StorageService, http: HttpClient, extensionService: ExtensionService) { constructor(private storage: StorageService) {
super(http, extensionService); super();
} }
/** @override */ /** @override */
get<T>(key: string, defaultValue?: T): T { get<T>(key: string, defaultValue?: T): T {
if (key === AppConfigValues.OAUTHCONFIG) { if (key === AppConfigValues.OAUTHCONFIG) {
return (JSON.parse(this.storage.getItem(key)) || super.get<T>(key, defaultValue)); return JSON.parse(this.storage.getItem(key)) || super.get<T>(key, defaultValue);
} else if (key === AppConfigValues.APPLICATION) { } else if (key === AppConfigValues.APPLICATION) {
return undefined; return undefined;
} else { } else {
return (this.storage.getItem(key) as any || super.get<T>(key, defaultValue)); return (this.storage.getItem(key) as any) || super.get<T>(key, defaultValue);
} }
} }
} }

View File

@ -26,7 +26,7 @@ import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatChipHarness, MatChipListboxHarness } from '@angular/material/chips/testing'; import { MatChipHarness, MatChipListboxHarness } from '@angular/material/chips/testing';
import { MatButtonHarness } from '@angular/material/button/testing'; import { MatButtonHarness } from '@angular/material/button/testing';
import { MatIconHarness } from '@angular/material/icon/testing'; import { MatIconHarness } from '@angular/material/icon/testing';
import { CoreTestingModule } from '@alfresco/adf-core'; import { NoopTranslateModule } from '@alfresco/adf-core';
describe('CardViewArrayItemComponent', () => { describe('CardViewArrayItemComponent', () => {
let loader: HarnessLoader; let loader: HarnessLoader;
@ -51,7 +51,7 @@ describe('CardViewArrayItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, CardViewArrayItemComponent] imports: [NoopTranslateModule, CardViewArrayItemComponent]
}); });
fixture = TestBed.createComponent(CardViewArrayItemComponent); fixture = TestBed.createComponent(CardViewArrayItemComponent);
service = TestBed.inject(CardViewUpdateService); service = TestBed.inject(CardViewUpdateService);

View File

@ -28,8 +28,7 @@ import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatChipHarness } from '@angular/material/chips/testing'; import { MatChipHarness } from '@angular/material/chips/testing';
import { addMinutes } from 'date-fns'; import { addMinutes } from 'date-fns';
import { MatSnackBarModule } from '@angular/material/snack-bar'; import { NoopTranslateModule } from '@alfresco/adf-core';
import { CoreTestingModule } from '@alfresco/adf-core';
describe('CardViewDateItemComponent', () => { describe('CardViewDateItemComponent', () => {
let loader: HarnessLoader; let loader: HarnessLoader;
@ -39,7 +38,7 @@ describe('CardViewDateItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, MatSnackBarModule, CardViewDateItemComponent] imports: [NoopTranslateModule, CardViewDateItemComponent]
}); });
appConfigService = TestBed.inject(AppConfigService); appConfigService = TestBed.inject(AppConfigService);
appConfigService.config.dateValues = { appConfigService.config.dateValues = {

View File

@ -39,6 +39,8 @@ import { TranslateModule } from '@ngx-translate/core';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips'; import { MatChipsModule } from '@angular/material/chips';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatSnackBarModule } from '@angular/material/snack-bar';
@Component({ @Component({
providers: [ providers: [
@ -49,7 +51,16 @@ import { MatFormFieldModule } from '@angular/material/form-field';
], ],
selector: 'adf-card-view-dateitem', selector: 'adf-card-view-dateitem',
standalone: true, standalone: true,
imports: [CommonModule, TranslateModule, MatIconModule, MatDatetimepickerModule, MatChipsModule, MatFormFieldModule], imports: [
CommonModule,
TranslateModule,
MatIconModule,
MatDatetimepickerModule,
MatChipsModule,
MatFormFieldModule,
MatDatepickerModule,
MatSnackBarModule
],
templateUrl: './card-view-dateitem.component.html', templateUrl: './card-view-dateitem.component.html',
styleUrls: ['./card-view-dateitem.component.scss'], styleUrls: ['./card-view-dateitem.component.scss'],
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,

View File

@ -20,7 +20,7 @@ import { By } from '@angular/platform-browser';
import { CardViewKeyValuePairsItemModel } from '../../models/card-view-keyvaluepairs.model'; import { CardViewKeyValuePairsItemModel } from '../../models/card-view-keyvaluepairs.model';
import { CardViewKeyValuePairsItemComponent } from './card-view-keyvaluepairsitem.component'; import { CardViewKeyValuePairsItemComponent } from './card-view-keyvaluepairsitem.component';
import { CardViewUpdateService } from '../../services/card-view-update.service'; import { CardViewUpdateService } from '../../services/card-view-update.service';
import { CoreTestingModule } from '@alfresco/adf-core'; import { NoopTranslateModule } from '@alfresco/adf-core';
describe('CardViewKeyValuePairsItemComponent', () => { describe('CardViewKeyValuePairsItemComponent', () => {
let fixture: ComponentFixture<CardViewKeyValuePairsItemComponent>; let fixture: ComponentFixture<CardViewKeyValuePairsItemComponent>;
@ -31,7 +31,7 @@ describe('CardViewKeyValuePairsItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, CardViewKeyValuePairsItemComponent] imports: [NoopTranslateModule, CardViewKeyValuePairsItemComponent]
}); });
fixture = TestBed.createComponent(CardViewKeyValuePairsItemComponent); fixture = TestBed.createComponent(CardViewKeyValuePairsItemComponent);
cardViewUpdateService = TestBed.inject(CardViewUpdateService); cardViewUpdateService = TestBed.inject(CardViewUpdateService);

View File

@ -21,7 +21,7 @@ import { By } from '@angular/platform-browser';
import { CardViewMapItemModel } from '../../models/card-view-mapitem.model'; 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 '@alfresco/adf-core'; import { NoopTranslateModule } from '@alfresco/adf-core';
describe('CardViewMapItemComponent', () => { describe('CardViewMapItemComponent', () => {
let service: CardViewUpdateService; let service: CardViewUpdateService;
@ -33,7 +33,7 @@ describe('CardViewMapItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, CardViewMapItemComponent] imports: [NoopTranslateModule, CardViewMapItemComponent]
}); });
fixture = TestBed.createComponent(CardViewMapItemComponent); fixture = TestBed.createComponent(CardViewMapItemComponent);
service = TestBed.inject(CardViewUpdateService); service = TestBed.inject(CardViewUpdateService);

View File

@ -25,7 +25,8 @@ import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatSelectHarness } from '@angular/material/select/testing'; import { MatSelectHarness } from '@angular/material/select/testing';
import { MatFormFieldHarness } from '@angular/material/form-field/testing'; import { MatFormFieldHarness } from '@angular/material/form-field/testing';
import { CoreTestingModule } from '@alfresco/adf-core'; import { NoopTranslateModule } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
describe('CardViewSelectItemComponent', () => { describe('CardViewSelectItemComponent', () => {
let loader: HarnessLoader; let loader: HarnessLoader;
@ -59,7 +60,7 @@ describe('CardViewSelectItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, CardViewSelectItemComponent] imports: [NoopTranslateModule, NoopAnimationsModule, CardViewSelectItemComponent]
}); });
fixture = TestBed.createComponent(CardViewSelectItemComponent); fixture = TestBed.createComponent(CardViewSelectItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;

View File

@ -20,7 +20,6 @@ import { By } from '@angular/platform-browser';
import { CardViewTextItemModel } from '../../models/card-view-textitem.model'; import { CardViewTextItemModel } from '../../models/card-view-textitem.model';
import { CardViewUpdateService } from '../../services/card-view-update.service'; import { CardViewUpdateService } from '../../services/card-view-update.service';
import { CardViewTextItemComponent } from './card-view-textitem.component'; import { CardViewTextItemComponent } from './card-view-textitem.component';
import { CoreTestingModule } from '../../../testing/core.testing.module';
import { CardViewItemFloatValidator } from '../../validators/card-view-item-float.validator'; import { CardViewItemFloatValidator } from '../../validators/card-view-item-float.validator';
import { CardViewItemIntValidator } from '../../validators/card-view-item-int.validator'; import { CardViewItemIntValidator } from '../../validators/card-view-item-int.validator';
import { CardViewIntItemModel } from '../../models/card-view-intitem.model'; import { CardViewIntItemModel } from '../../models/card-view-intitem.model';
@ -33,6 +32,8 @@ import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatChipHarness, MatChipGridHarness } from '@angular/material/chips/testing'; import { MatChipHarness, MatChipGridHarness } from '@angular/material/chips/testing';
import { MatInputHarness } from '@angular/material/input/testing'; import { MatInputHarness } from '@angular/material/input/testing';
import { NoopTranslateModule } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
describe('CardViewTextItemComponent', () => { describe('CardViewTextItemComponent', () => {
let loader: HarnessLoader; let loader: HarnessLoader;
@ -111,7 +112,7 @@ describe('CardViewTextItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, CardViewTextItemComponent] imports: [NoopTranslateModule, NoopAnimationsModule, CardViewTextItemComponent]
}); });
fixture = TestBed.createComponent(CardViewTextItemComponent); fixture = TestBed.createComponent(CardViewTextItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;

View File

@ -30,6 +30,7 @@ import { TranslateModule } from '@ngx-translate/core';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatSnackBarModule } from '@angular/material/snack-bar';
export const DEFAULT_SEPARATOR = ', '; export const DEFAULT_SEPARATOR = ', ';
const templateTypes = { const templateTypes = {
@ -52,7 +53,8 @@ const templateTypes = {
MatChipsModule, MatChipsModule,
MatIconModule, MatIconModule,
FormsModule, FormsModule,
MatButtonModule MatButtonModule,
MatSnackBarModule
], ],
templateUrl: './card-view-textitem.component.html', templateUrl: './card-view-textitem.component.html',
styleUrls: ['./card-view-textitem.component.scss'], styleUrls: ['./card-view-textitem.component.scss'],

View File

@ -28,9 +28,10 @@ import { CardViewItemDispatcherComponent } from '../card-view-item-dispatcher/ca
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 { MatSelectHarness } from '@angular/material/select/testing'; import { MatSelectHarness } from '@angular/material/select/testing';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatDialogModule } from '@angular/material/dialog'; import { MatDialogModule } from '@angular/material/dialog';
import { CoreTestingModule } from '@alfresco/adf-core'; import { NoopTranslateModule } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { MatSnackBarModule } from '@angular/material/snack-bar';
describe('CardViewComponent', () => { describe('CardViewComponent', () => {
let loader: HarnessLoader; let loader: HarnessLoader;
@ -39,7 +40,7 @@ describe('CardViewComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, MatSnackBarModule, MatDialogModule, CardViewComponent] imports: [NoopTranslateModule, NoopAnimationsModule, MatSnackBarModule, MatDialogModule, CardViewComponent]
}); });
fixture = TestBed.createComponent(CardViewComponent); fixture = TestBed.createComponent(CardViewComponent);

View File

@ -73,8 +73,8 @@ export class CommentsComponent implements OnChanges {
return; return;
} }
this.commentsService.get(this.id).subscribe( this.commentsService.get(this.id).subscribe({
(comments: CommentModel[]) => { next: (comments) => {
if (!this.isArrayInstance(comments)) { if (!this.isArrayInstance(comments)) {
return; return;
} }
@ -82,10 +82,10 @@ export class CommentsComponent implements OnChanges {
comments = this.sortedComments(comments); comments = this.sortedComments(comments);
this.comments.push(...comments); this.comments.push(...comments);
}, },
(err) => { error: (err) => {
this.error.emit(err); this.error.emit(err);
} }
); });
} }
addComment() { addComment() {
@ -95,18 +95,18 @@ export class CommentsComponent implements OnChanges {
this.beingAdded = true; this.beingAdded = true;
this.commentsService.add(this.id, this.message).subscribe( this.commentsService.add(this.id, this.message).subscribe({
(res: CommentModel) => { next: (res) => {
this.addToComments(res); this.addToComments(res);
this.resetMessage(); this.resetMessage();
}, },
(err) => { error: (err) => {
this.error.emit(err); this.error.emit(err);
}, },
() => { complete: () => {
this.beingAdded = false; this.beingAdded = false;
} }
); });
} }
clearMessage(event: Event): void { clearMessage(event: Event): void {
@ -135,7 +135,7 @@ export class CommentsComponent implements OnChanges {
} }
private sortedComments(comments: CommentModel[]): CommentModel[] { private sortedComments(comments: CommentModel[]): CommentModel[] {
return comments.sort((comment1: CommentModel, comment2: CommentModel) => { return comments.sort((comment1, comment2) => {
const date1 = new Date(comment1.created); const date1 = new Date(comment1.created);
const date2 = new Date(comment2.created); const date2 = new Date(comment2.created);

View File

@ -17,24 +17,21 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { AppConfigService, Status } from '../../app-config/app-config.service'; import { AppConfigService, Status } from '../../app-config/app-config.service';
import { HttpClient } from '@angular/common/http';
import { ExtensionService } from '@alfresco/adf-extensions';
@Injectable() @Injectable()
export class AppConfigServiceMock extends AppConfigService { export class AppConfigServiceMock extends AppConfigService {
constructor() {
super();
config: any = { this.config = {
application: { application: {
name: 'Alfresco ADF Application', name: 'Alfresco ADF Application',
storagePrefix: 'ADF_APP' storagePrefix: 'ADF_APP'
}, },
ecmHost: 'http://{hostname}{:port}/ecm', ecmHost: 'http://{hostname}{:port}/ecm',
bpmHost: 'http://{hostname}{:port}/bpm', bpmHost: 'http://{hostname}{:port}/bpm',
logLevel: 'silent' logLevel: 'silent'
}; };
constructor(http: HttpClient, extensionService: ExtensionService) {
super(http, extensionService);
} }
load(callback?: (...args: any[]) => any): Promise<any> { load(callback?: (...args: any[]) => any): Promise<any> {

View File

@ -1,29 +0,0 @@
/*!
* @license
* Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DirectionalityConfigService } from './directionality-config.service';
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
/**
* Creates a factory for Angular modules
*
* @param directionalityConfigService service dependency
* @returns a factory function
*/
export function directionalityConfigFactory(directionalityConfigService: DirectionalityConfigService) {
return () => directionalityConfigService;
}

View File

@ -1,53 +0,0 @@
/*!
* @license
* Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed } from '@angular/core/testing';
import { UserPreferencesService } from './user-preferences.service';
import { DirectionalityConfigService } from './directionality-config.service';
import { directionalityConfigFactory } from './directionality-config-factory';
import { APP_INITIALIZER } from '@angular/core';
import { NoopTranslateModule } from '@alfresco/adf-core';
describe('DirectionalityConfigService', () => {
let userPreferencesService: UserPreferencesService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NoopTranslateModule],
providers: [
UserPreferencesService,
{
provide: APP_INITIALIZER,
useFactory: directionalityConfigFactory,
deps: [DirectionalityConfigService],
multi: true
}
]
});
userPreferencesService = TestBed.inject(UserPreferencesService);
});
it('should set document direction on textOrientation event to `rtl`', () => {
userPreferencesService.set('textOrientation', 'rtl');
expect(document.body.getAttribute('dir')).toBe('rtl');
});
it('should set document direction on textOrientation event to `ltr`', () => {
userPreferencesService.set('textOrientation', 'ltr');
expect(document.body.getAttribute('dir')).toBe('ltr');
});
});

View File

@ -1,42 +0,0 @@
/*!
* @license
* Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable, Inject, Renderer2, RendererFactory2 } from '@angular/core';
import { Directionality, Direction } from '@angular/cdk/bidi';
import { UserPreferencesService } from './user-preferences.service';
import { DOCUMENT } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class DirectionalityConfigService {
constructor(
@Inject(DOCUMENT) private document: any,
private rendererFactory: RendererFactory2,
private userPreferencesService: UserPreferencesService,
private directionality: Directionality
) {
const renderer: Renderer2 = this.rendererFactory.createRenderer(null, null);
this.userPreferencesService
.select('textOrientation')
.subscribe((direction: Direction) => {
renderer.setAttribute(this.document.body, 'dir', direction);
(this.directionality as any).value = direction;
});
}
}

View File

@ -18,9 +18,7 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
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 { CoreTestingModule } from '../../testing'; import { NoopAuthModule, NoopTranslateModule } from '@alfresco/adf-core';
import { RedirectAuthService } from '../../auth';
import { EMPTY } from 'rxjs';
describe('StorageService', () => { describe('StorageService', () => {
let storage: StorageService; let storage: StorageService;
@ -31,48 +29,41 @@ describe('StorageService', () => {
describe('with prefix', () => { describe('with prefix', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopTranslateModule, NoopAuthModule]
providers: [{ provide: RedirectAuthService, useValue: { onLogin: EMPTY, init: () => [] } }]
}); });
appConfig = TestBed.inject(AppConfigService); appConfig = TestBed.inject(AppConfigService);
storage = TestBed.inject(StorageService); storage = TestBed.inject(StorageService);
}); });
it('should get the prefix for the storage from app config', (done) => { it('should get the prefix for the storage from app config', async () => {
appConfig.load().then(() => { await appConfig.load();
expect(storage.prefix).toBe('ADF_APP_'); expect(storage.prefix).toBe('ADF_APP_');
done();
});
}); });
it('should set a property with the prefix in the local storage', (done) => { it('should set a property with the prefix in the local storage', async () => {
appConfig.load().then(() => { await appConfig.load();
storage.clear();
storage.setItem(key, value); storage.clear();
const storageKey = localStorage.key(0); storage.setItem(key, value);
expect(storageKey).toBe('ADF_APP_' + key); const storageKey = localStorage.key(0);
expect(localStorage.getItem(storageKey)).toBe(value); expect(storageKey).toBe('ADF_APP_' + key);
done(); expect(localStorage.getItem(storageKey)).toBe(value);
});
}); });
it('should be able to get a property from the local storage', (done) => { it('should be able to get a property from the local storage', async () => {
storage.clear(); storage.clear();
appConfig.load().then(() => { await appConfig.load();
storage.setItem(key, value); storage.setItem(key, value);
expect(storage.getItem(key)).toBe(value); expect(storage.getItem(key)).toBe(value);
done();
});
}); });
}); });
describe('without prefix', () => { describe('without prefix', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopAuthModule]
providers: [{ provide: RedirectAuthService, useValue: { onLogin: EMPTY, init: () => [] } }]
}); });
appConfig = TestBed.inject(AppConfigService); appConfig = TestBed.inject(AppConfigService);
@ -84,20 +75,16 @@ describe('StorageService', () => {
storage = TestBed.inject(StorageService); storage = TestBed.inject(StorageService);
}); });
it('should set an empty prefix when the it is not defined in the app config', (done) => { it('should set an empty prefix when the it is not defined in the app config', async () => {
appConfig.load().then(() => { await appConfig.load();
expect(storage.prefix).toBe(''); expect(storage.prefix).toBe('');
done();
});
}); });
it('should set a property without a prefix in the local storage', (done) => { it('should set a property without a prefix in the local storage', async () => {
appConfig.load().then(() => { await appConfig.load();
storage.setItem(key, value); storage.setItem(key, value);
expect(localStorage.getItem(key)).toBe(value); expect(localStorage.getItem(key)).toBe(value);
done();
});
}); });
}); });
}); });

View File

@ -33,9 +33,7 @@ describe('UserPreferencesService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [NoopTranslateModule], imports: [NoopTranslateModule],
providers: [ providers: [{ provide: AppConfigService, useClass: AppConfigServiceMock }]
{ provide: AppConfigService, useClass: AppConfigServiceMock }
]
}); });
appConfig = TestBed.inject(AppConfigService); appConfig = TestBed.inject(AppConfigService);
appConfig.config = { appConfig.config = {
@ -56,6 +54,16 @@ describe('UserPreferencesService', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
it('should set document direction on textOrientation event to `rtl`', () => {
preferences.set('textOrientation', 'rtl');
expect(document.body.getAttribute('dir')).toBe('rtl');
});
it('should set document direction on textOrientation event to `ltr`', () => {
preferences.set('textOrientation', 'ltr');
expect(document.body.getAttribute('dir')).toBe('ltr');
});
describe(' with pagination config', () => { describe(' with pagination config', () => {
it('should get default pagination from app config', (done) => { it('should get default pagination from app config', (done) => {
appConfig.config.pagination.size = 0; appConfig.config.pagination.size = 0;

View File

@ -15,13 +15,15 @@
* limitations under the License. * limitations under the License.
*/ */
import { Injectable } from '@angular/core'; import { inject, Injectable, RendererFactory2 } from '@angular/core';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { Observable, BehaviorSubject } from 'rxjs'; import { Observable, BehaviorSubject } from 'rxjs';
import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service'; import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service';
import { StorageService } from './storage.service'; import { StorageService } from './storage.service';
import { distinctUntilChanged, map } from 'rxjs/operators'; import { distinctUntilChanged, map } from 'rxjs/operators';
import { LanguageItem } from './language-item.interface'; import { LanguageItem } from './language-item.interface';
import { DOCUMENT } from '@angular/common';
import { Directionality, Direction } from '@angular/cdk/bidi';
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
export enum UserPreferenceValues { export enum UserPreferenceValues {
@ -35,6 +37,9 @@ export enum UserPreferenceValues {
providedIn: 'root' providedIn: 'root'
}) })
export class UserPreferencesService { export class UserPreferencesService {
private document = inject(DOCUMENT);
private rendererFactory = inject(RendererFactory2);
private directionality = inject(Directionality);
defaults = { defaults = {
paginationSize: 25, paginationSize: 25,
@ -47,17 +52,20 @@ export class UserPreferencesService {
private onChangeSubject: BehaviorSubject<any>; private onChangeSubject: BehaviorSubject<any>;
onChange: Observable<any>; onChange: Observable<any>;
constructor( constructor(public translate: TranslateService, private appConfig: AppConfigService, private storage: StorageService) {
public translate: TranslateService,
private appConfig: AppConfigService,
private storage: StorageService
) {
this.onChangeSubject = new BehaviorSubject(this.userPreferenceStatus); this.onChangeSubject = new BehaviorSubject(this.userPreferenceStatus);
this.onChange = this.onChangeSubject.asObservable(); this.onChange = this.onChangeSubject.asObservable();
this.appConfig.onLoad.subscribe(() => { this.appConfig.onLoad.subscribe(() => {
this.initUserPreferenceStatus(); this.initUserPreferenceStatus();
}); });
const renderer = this.rendererFactory.createRenderer(null, null);
this.select('textOrientation').subscribe((direction: Direction) => {
renderer.setAttribute(this.document.body, 'dir', direction);
(this.directionality as any).value = direction;
});
} }
private initUserPreferenceStatus() { private initUserPreferenceStatus() {
@ -87,11 +95,10 @@ export class UserPreferencesService {
* @returns Notification callback * @returns Notification callback
*/ */
select<T = any>(property: string): Observable<T> { select<T = any>(property: string): Observable<T> {
return this.onChange return this.onChange.pipe(
.pipe( map((userPreferenceStatus) => userPreferenceStatus[property]),
map((userPreferenceStatus) => userPreferenceStatus[property]), distinctUntilChanged()
distinctUntilChanged() );
);
} }
/** /**
@ -120,10 +127,7 @@ export class UserPreferencesService {
if (!property) { if (!property) {
return; return;
} }
this.storage.setItem( this.storage.setItem(this.getPropertyKey(property), value);
this.getPropertyKey(property),
value
);
this.userPreferenceStatus[property] = value; this.userPreferenceStatus[property] = value;
this.onChangeSubject.next(this.userPreferenceStatus); this.onChangeSubject.next(this.userPreferenceStatus);
} }
@ -152,9 +156,7 @@ export class UserPreferencesService {
if (!property) { if (!property) {
return false; return false;
} }
return this.storage.hasItem( return this.storage.hasItem(this.getPropertyKey(property));
this.getPropertyKey(property)
);
} }
/** /**
@ -243,10 +245,12 @@ export class UserPreferencesService {
} }
private getLanguageByKey(key: string): LanguageItem { private getLanguageByKey(key: string): LanguageItem {
return ( const defaultLanguage = { key: 'en' } as LanguageItem;
this.appConfig
.get<Array<LanguageItem>>(AppConfigValues.APP_CONFIG_LANGUAGES_KEY, [{ key: 'en' } as LanguageItem]) const registeredLanguages = this.appConfig.get<Array<LanguageItem>>(AppConfigValues.APP_CONFIG_LANGUAGES_KEY);
.find((language) => key.includes(language.key)) || { key: 'en' } as LanguageItem if (registeredLanguages && Array.isArray(registeredLanguages)) {
); return registeredLanguages.find((language) => key.includes(language.key)) || defaultLanguage;
}
return defaultLanguage;
} }
} }

View File

@ -16,7 +16,6 @@
*/ */
import { Overlay } from '@angular/cdk/overlay'; import { Overlay } from '@angular/cdk/overlay';
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';
@ -35,7 +34,6 @@ describe('ContextMenuOverlayService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule],
providers: [Overlay] providers: [Overlay]
}); });
overlay = TestBed.inject(Overlay); overlay = TestBed.inject(Overlay);

View File

@ -39,8 +39,6 @@ import { CORE_DIRECTIVES } from './directives/directive.module';
import { CORE_PIPES } from './pipes/pipe.module'; import { CORE_PIPES } from './pipes/pipe.module';
import { TranslationService } from './translation/translation.service'; import { TranslationService } from './translation/translation.service';
import { TranslateLoaderService } from './translation/translate-loader.service'; import { TranslateLoaderService } from './translation/translate-loader.service';
import { directionalityConfigFactory } from './common/services/directionality-config-factory';
import { DirectionalityConfigService } from './common/services/directionality-config.service';
import { SEARCH_TEXT_INPUT_DIRECTIVES } from './search-text/search-text-input.module'; import { SEARCH_TEXT_INPUT_DIRECTIVES } from './search-text/search-text-input.module';
import { AdfHttpClient } from '@alfresco/adf-core/api'; import { AdfHttpClient } from '@alfresco/adf-core/api';
import { AuthenticationInterceptor, Authentication } from '@alfresco/adf-core/auth'; import { AuthenticationInterceptor, Authentication } from '@alfresco/adf-core/auth';
@ -145,12 +143,6 @@ export class CoreModule {
deps: [AppConfigService, StorageService, AdfHttpClient, StoragePrefixFactory], deps: [AppConfigService, StorageService, AdfHttpClient, StoragePrefixFactory],
multi: true multi: true
}, },
{
provide: APP_INITIALIZER,
useFactory: directionalityConfigFactory,
deps: [DirectionalityConfigService],
multi: true
},
{ provide: HTTP_INTERCEPTORS, useClass: AuthenticationInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: AuthenticationInterceptor, multi: true },
{ provide: Authentication, useClass: AuthenticationService }, { provide: Authentication, useClass: AuthenticationService },
{ {

View File

@ -20,11 +20,11 @@ import { ColumnsSelectorComponent } from './columns-selector.component';
import { DataColumn } from '../../data/data-column.model'; 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 { 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';
import { MatCheckboxHarness } from '@angular/material/checkbox/testing'; import { MatCheckboxHarness } from '@angular/material/checkbox/testing';
import { NoopTranslateModule } from '@alfresco/adf-core';
describe('ColumnsSelectorComponent', () => { describe('ColumnsSelectorComponent', () => {
let fixture: ComponentFixture<ColumnsSelectorComponent>; let fixture: ComponentFixture<ColumnsSelectorComponent>;
@ -40,8 +40,8 @@ describe('ColumnsSelectorComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, ColumnsSelectorComponent] imports: [NoopTranslateModule, ColumnsSelectorComponent]
}).compileComponents(); });
fixture = TestBed.createComponent(ColumnsSelectorComponent); fixture = TestBed.createComponent(ColumnsSelectorComponent);
loader = TestbedHarnessEnvironment.loader(fixture); loader = TestbedHarnessEnvironment.loader(fixture);

View File

@ -17,14 +17,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';
describe('EmptyListComponentComponent', () => { describe('EmptyListComponentComponent', () => {
let fixture: ComponentFixture<EmptyListComponent>; let fixture: ComponentFixture<EmptyListComponent>;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule] imports: [EmptyListComponent]
}); });
fixture = TestBed.createComponent(EmptyListComponent); fixture = TestBed.createComponent(EmptyListComponent);
}); });

View File

@ -18,7 +18,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ObjectDataTableAdapter } from '../../data/object-datatable-adapter'; 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 { JsonCellComponent } from './json-cell.component'; import { JsonCellComponent } from './json-cell.component';
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';
@ -34,7 +33,7 @@ describe('JsonCellComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule] imports: [JsonCellComponent]
}); });
fixture = TestBed.createComponent(JsonCellComponent); fixture = TestBed.createComponent(JsonCellComponent);
component = fixture.componentInstance; component = fixture.componentInstance;

View File

@ -17,7 +17,7 @@
import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation, Input } from '@angular/core'; import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation, Input } from '@angular/core';
import { DataTableCellComponent } from '../datatable-cell/datatable-cell.component'; import { DataTableCellComponent } from '../datatable-cell/datatable-cell.component';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { EditJsonDialogComponent, EditJsonDialogSettings } from '../../../dialogs/edit-json/edit-json.dialog'; import { EditJsonDialogComponent, EditJsonDialogSettings } from '../../../dialogs/edit-json/edit-json.dialog';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
@ -25,7 +25,7 @@ import { MatButtonModule } from '@angular/material/button';
@Component({ @Component({
selector: 'adf-json-cell', selector: 'adf-json-cell',
standalone: true, standalone: true,
imports: [CommonModule, MatButtonModule], imports: [CommonModule, MatButtonModule, MatDialogModule],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
template: ` template: `
<ng-container *ngIf="value$ | async as value; else editEmpty"> <ng-container *ngIf="value$ | async as value; else editEmpty">

View File

@ -19,7 +19,7 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ObjectDataTableAdapter } from '../../data/object-datatable-adapter'; import { ObjectDataTableAdapter } from '../../data/object-datatable-adapter';
import { ObjectDataColumn } from '../../data/object-datacolumn.model'; import { ObjectDataColumn } from '../../data/object-datacolumn.model';
import { LocationCellComponent } from './location-cell.component'; import { LocationCellComponent } from './location-cell.component';
import { CoreTestingModule } from '../../../testing/core.testing.module'; import { RouterTestingModule } from '@angular/router/testing';
describe('LocationCellComponent', () => { describe('LocationCellComponent', () => {
let component: LocationCellComponent; let component: LocationCellComponent;
@ -30,10 +30,7 @@ describe('LocationCellComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [RouterTestingModule, LocationCellComponent]
LocationCellComponent,
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(LocationCellComponent); fixture = TestBed.createComponent(LocationCellComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@ -52,12 +49,9 @@ describe('LocationCellComponent', () => {
} }
}; };
columnData = { format: '/files', type: 'location', key: 'path'}; columnData = { format: '/files', type: 'location', key: 'path' };
dataTableAdapter = new ObjectDataTableAdapter( dataTableAdapter = new ObjectDataTableAdapter([rowData], [new ObjectDataColumn(columnData)]);
[rowData],
[ new ObjectDataColumn(columnData) ]
);
component.link = []; component.link = [];
component.column = dataTableAdapter.getColumns()[0]; component.column = dataTableAdapter.getColumns()[0];
@ -78,7 +72,7 @@ describe('LocationCellComponent', () => {
it('should set router link', () => { it('should set router link', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(component.link).toEqual([ columnData.format , rowData.path.elements[2].id ]); expect(component.link).toEqual([columnData.format, rowData.path.elements[2].id]);
}); });
it('should NOT set router link when format NOT provided', () => { it('should NOT set router link when format NOT provided', () => {
@ -99,7 +93,7 @@ describe('LocationCellComponent', () => {
expect(value).toBe(''); expect(value).toBe('');
done(); done();
}); });
}); });
it('should not setup cell when path is missing required properties', (done) => { it('should not setup cell when path is missing required properties', (done) => {
rowData.path = { someProp: '' }; rowData.path = { someProp: '' };

View File

@ -16,16 +16,8 @@
*/ */
import { DataColumnComponent } from './data-column.component'; import { DataColumnComponent } from './data-column.component';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { TestBed } from '@angular/core/testing';
describe('DataColumnListComponent', () => { describe('DataColumnListComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [CoreTestingModule]
});
});
it('should setup screen reader title for thumbnails', () => { it('should setup screen reader title for thumbnails', () => {
const component = new DataColumnComponent(); const component = new DataColumnComponent();
component.key = '$thumbnail'; component.key = '$thumbnail';

View File

@ -18,7 +18,6 @@
import { TestBed, ComponentFixture } from '@angular/core/testing'; 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';
describe('LoadingContentTemplateDirective', () => { describe('LoadingContentTemplateDirective', () => {
let fixture: ComponentFixture<DataTableComponent>; let fixture: ComponentFixture<DataTableComponent>;
@ -27,7 +26,7 @@ describe('LoadingContentTemplateDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule] imports: [DataTableComponent]
}); });
fixture = TestBed.createComponent(DataTableComponent); fixture = TestBed.createComponent(DataTableComponent);
dataTable = fixture.componentInstance; dataTable = fixture.componentInstance;

View File

@ -18,7 +18,6 @@
import { TestBed, ComponentFixture } from '@angular/core/testing'; 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';
describe('NoContentTemplateDirective', () => { describe('NoContentTemplateDirective', () => {
let fixture: ComponentFixture<DataTableComponent>; let fixture: ComponentFixture<DataTableComponent>;
@ -27,7 +26,7 @@ describe('NoContentTemplateDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule] imports: [DataTableComponent]
}); });
fixture = TestBed.createComponent(DataTableComponent); fixture = TestBed.createComponent(DataTableComponent);
dataTable = fixture.componentInstance; dataTable = fixture.componentInstance;

View File

@ -16,16 +16,17 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { CoreTestingModule, UnsavedChangesDialogComponent, UnsavedChangesGuard } from '@alfresco/adf-core'; import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Observable, Subject } from 'rxjs'; import { Observable, Subject } from 'rxjs';
import { UnsavedChangesDialogComponent } from './unsaved-changes-dialog.component';
import { UnsavedChangesGuard } from './unsaved-changes.guard';
describe('UnsavedChangesGuard', () => { describe('UnsavedChangesGuard', () => {
let guard: UnsavedChangesGuard; let guard: UnsavedChangesGuard;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule] imports: [MatDialogModule]
}); });
guard = TestBed.inject(UnsavedChangesGuard); guard = TestBed.inject(UnsavedChangesGuard);
}); });

View File

@ -20,21 +20,22 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; 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';
/* spellchecker: disable */ /* spellchecker: disable */
const template: string = ` @Component({
<div id="outerDiv1" adf-highlight adf-highlight-selector=".highlightable" adf-highlight-class="highlight-for-free-willy"> selector: 'adf-test-component',
<div id="innerDiv11" class="highlightable">Lorem ipsum salana-eyong-aysis dolor sit amet</div> standalone: true,
<div id="innerDiv12">Lorem ipsum salana-eyong-aysis dolor sit amet</div> imports: [HighlightDirective],
<div id="innerDiv13" class="highlightable">consectetur adipiscing elit</div> template: ` <div id="outerDiv1" adf-highlight adf-highlight-selector=".highlightable" adf-highlight-class="highlight-for-free-willy">
<div id="innerDiv14" class="highlightable">sed do eiusmod salana-eyong-aysis tempor incididunt</div> <div id="innerDiv11" class="highlightable">Lorem ipsum salana-eyong-aysis dolor sit amet</div>
</div> <div id="innerDiv12">Lorem ipsum salana-eyong-aysis dolor sit amet</div>
<div id="outerDiv2" adf-highlight adf-highlight-selector=".highlightable"> <div id="innerDiv13" class="highlightable">consectetur adipiscing elit</div>
<div id="innerDiv21" class="highlightable">Lorem ipsum salana-eyong-aysis dolor sit amet</div> <div id="innerDiv14" class="highlightable">sed do eiusmod salana-eyong-aysis tempor incididunt</div>
</div>`; </div>
<div id="outerDiv2" adf-highlight adf-highlight-selector=".highlightable">
@Component({ selector: 'adf-test-component', template }) <div id="innerDiv21" class="highlightable">Lorem ipsum salana-eyong-aysis dolor sit amet</div>
</div>`
})
class TestComponent { class TestComponent {
@ViewChildren(HighlightDirective) public highlightDirectives; @ViewChildren(HighlightDirective) public highlightDirectives;
} }
@ -45,8 +46,7 @@ describe('HighlightDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [TestComponent]
declarations: [TestComponent]
}); });
fixture = TestBed.createComponent(TestComponent); fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance; component = fixture.componentInstance;

View File

@ -22,12 +22,14 @@ import { of, throwError } from 'rxjs';
import { AuthenticationService } from '../auth/services/authentication.service'; 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 { NoopAuthModule } from '@alfresco/adf-core';
describe('LogoutDirective', () => { describe('LogoutDirective', () => {
describe('No input', () => { describe('No input', () => {
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
standalone: true,
imports: [LogoutDirective],
template: '<button adf-logout></button>' template: '<button adf-logout></button>'
}) })
class TestComponent { class TestComponent {
@ -42,8 +44,7 @@ describe('LogoutDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopAuthModule, TestComponent]
declarations: [TestComponent]
}); });
router = TestBed.inject(Router); router = TestBed.inject(Router);
authService = TestBed.inject(AuthenticationService); authService = TestBed.inject(AuthenticationService);
@ -104,6 +105,8 @@ describe('LogoutDirective', () => {
describe('redirectUri', () => { describe('redirectUri', () => {
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
standalone: true,
imports: [LogoutDirective],
template: '<button adf-logout redirectUri="/myCustomUri"></button>' template: '<button adf-logout redirectUri="/myCustomUri"></button>'
}) })
class TestComponent { class TestComponent {
@ -117,8 +120,7 @@ describe('LogoutDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopAuthModule, TestComponent]
declarations: [TestComponent]
}); });
router = TestBed.inject(Router); router = TestBed.inject(Router);
authService = TestBed.inject(AuthenticationService); authService = TestBed.inject(AuthenticationService);
@ -141,6 +143,8 @@ describe('LogoutDirective', () => {
describe('enableRedirect', () => { describe('enableRedirect', () => {
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
standalone: true,
imports: [LogoutDirective],
template: '<button adf-logout [enableRedirect]="false"></button>' template: '<button adf-logout [enableRedirect]="false"></button>'
}) })
class TestComponent { class TestComponent {
@ -154,8 +158,7 @@ describe('LogoutDirective', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopAuthModule, TestComponent]
declarations: [TestComponent]
}); });
router = TestBed.inject(Router); router = TestBed.inject(Router);
authService = TestBed.inject(AuthenticationService); authService = TestBed.inject(AuthenticationService);

View File

@ -19,27 +19,23 @@ import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatTabChangeEvent } from '@angular/material/tabs'; 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, InfoDrawerTabComponent } from './info-drawer.component';
import { of } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
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';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatTabGroupHarness } from '@angular/material/tabs/testing'; import { MatTabGroupHarness } from '@angular/material/tabs/testing';
import { NoopTranslateModule } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
describe('InfoDrawerComponent', () => { describe('InfoDrawerComponent', () => {
let element: HTMLElement; let element: HTMLElement;
let component: InfoDrawerComponent; let component: InfoDrawerComponent;
let translateService: TranslateService;
let fixture: ComponentFixture<InfoDrawerComponent>; let fixture: ComponentFixture<InfoDrawerComponent>;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule] imports: [NoopTranslateModule, InfoDrawerComponent]
}); });
translateService = TestBed.inject(TranslateService);
spyOn(translateService, 'get').and.callFake((key) => of(key));
fixture = TestBed.createComponent(InfoDrawerComponent); fixture = TestBed.createComponent(InfoDrawerComponent);
element = fixture.nativeElement; element = fixture.nativeElement;
@ -86,6 +82,8 @@ describe('InfoDrawerComponent', () => {
}); });
@Component({ @Component({
standalone: true,
imports: [InfoDrawerTabComponent, InfoDrawerComponent],
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> <adf-info-drawer-tab label="Tab1"></adf-info-drawer-tab>
@ -102,18 +100,14 @@ class CustomInfoDrawerComponent extends InfoDrawerComponent {
describe('Custom InfoDrawer', () => { describe('Custom InfoDrawer', () => {
let fixture: ComponentFixture<CustomInfoDrawerComponent>; let fixture: ComponentFixture<CustomInfoDrawerComponent>;
let component: CustomInfoDrawerComponent; let component: CustomInfoDrawerComponent;
let translateService: TranslateService;
let loader: HarnessLoader; let loader: HarnessLoader;
const getNodeIcon = () => fixture.debugElement.queryAll(By.css('[info-drawer-node-icon]')); const getNodeIcon = () => fixture.debugElement.queryAll(By.css('[info-drawer-node-icon]'));
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopAnimationsModule, NoopTranslateModule, CustomInfoDrawerComponent]
declarations: [CustomInfoDrawerComponent]
}); });
translateService = TestBed.inject(TranslateService);
spyOn(translateService, 'get').and.callFake((key) => of(key));
fixture = TestBed.createComponent(CustomInfoDrawerComponent); fixture = TestBed.createComponent(CustomInfoDrawerComponent);
fixture.detectChanges(); fixture.detectChanges();
@ -170,6 +164,8 @@ describe('Custom InfoDrawer', () => {
}); });
@Component({ @Component({
standalone: true,
imports: [InfoDrawerComponent],
template: ` <adf-info-drawer [showHeader]="showHeader" [icon]="icon" title="Fake Visibility Info Drawer Title"> </adf-info-drawer> ` template: ` <adf-info-drawer [showHeader]="showHeader" [icon]="icon" title="Fake Visibility Info Drawer Title"> </adf-info-drawer> `
}) })
class VisibilityInfoDrawerComponent extends InfoDrawerComponent { class VisibilityInfoDrawerComponent extends InfoDrawerComponent {
@ -184,8 +180,7 @@ describe('Header visibility InfoDrawer', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopTranslateModule, VisibilityInfoDrawerComponent]
declarations: [VisibilityInfoDrawerComponent]
}); });
fixture = TestBed.createComponent(VisibilityInfoDrawerComponent); fixture = TestBed.createComponent(VisibilityInfoDrawerComponent);
fixture.detectChanges(); fixture.detectChanges();

View File

@ -16,21 +16,20 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatIcon, MatIconModule } from '@angular/material/icon'; import { MatIcon } from '@angular/material/icon';
import { MAT_SNACK_BAR_DATA, MatSnackBarModule, MatSnackBarRef } from '@angular/material/snack-bar'; import { MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material/snack-bar';
import { MatButtonModule } from '@angular/material/button';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { SnackbarContentComponent } from './snackbar-content.component'; import { SnackbarContentComponent } from './snackbar-content.component';
import { CoreTestingModule } from '@alfresco/adf-core'; import { CoreTestingModule, NoopTranslateModule } from '@alfresco/adf-core';
describe('SnackbarContentComponent', () => { describe('SnackbarContentComponent', () => {
let component: SnackbarContentComponent; let component: SnackbarContentComponent;
let fixture: ComponentFixture<SnackbarContentComponent>; let fixture: ComponentFixture<SnackbarContentComponent>;
beforeEach(async () => { beforeEach(() => {
await TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [SnackbarContentComponent], declarations: [SnackbarContentComponent],
imports: [CoreTestingModule, MatIconModule, MatSnackBarModule, MatButtonModule], imports: [NoopTranslateModule, CoreTestingModule],
providers: [ providers: [
{ {
provide: MatSnackBarRef, provide: MatSnackBarRef,
@ -43,7 +42,7 @@ describe('SnackbarContentComponent', () => {
useValue: {} useValue: {}
} }
] ]
}).compileComponents(); });
fixture = TestBed.createComponent(SnackbarContentComponent); fixture = TestBed.createComponent(SnackbarContentComponent);
component = fixture.componentInstance; component = fixture.componentInstance;

View File

@ -20,10 +20,13 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { TranslateService } 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 { NoopTranslateModule } from '../../testing/noop-translate.module';
import { EmptyContentComponent } from './empty-content.component';
@Component({ @Component({
selector: 'adf-test-component', selector: 'adf-test-component',
standalone: true,
imports: [EmptyContentComponent],
template: ` template: `
<adf-empty-content icon="delete" [title]="'CUSTOM_TITLE'" [subtitle]="'CUSTOM_SUBTITLE'"> <adf-empty-content 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>
@ -40,8 +43,7 @@ describe('EmptyContentComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [NoopTranslateModule, TestComponent]
declarations: [TestComponent]
}); });
fixture = TestBed.createComponent(TestComponent); fixture = TestBed.createComponent(TestComponent);
translateService = TestBed.inject(TranslateService); translateService = TestBed.inject(TranslateService);
@ -52,8 +54,8 @@ describe('EmptyContentComponent', () => {
await fixture.whenStable(); await fixture.whenStable();
const title = fixture.debugElement.query(By.css('.adf-empty-content__title')); const title = fixture.debugElement.query(By.css('.adf-empty-content__title'));
expect(title).toBeDefined('title element not found'); expect(title).toBeDefined();
expect(title.nativeElement.textContent).toContain('CUSTOM_TITLE', 'incorrect title value'); expect(title.nativeElement.textContent).toContain('CUSTOM_TITLE');
}); });
it('should translate title and subtitle', async () => { it('should translate title and subtitle', async () => {
@ -74,19 +76,19 @@ describe('EmptyContentComponent', () => {
const title = fixture.debugElement.query(By.css('.adf-empty-content__title')); const title = fixture.debugElement.query(By.css('.adf-empty-content__title'));
const subtitle = fixture.debugElement.query(By.css('.adf-empty-content__subtitle')); const subtitle = fixture.debugElement.query(By.css('.adf-empty-content__subtitle'));
expect(title).toBeDefined('title element not found'); expect(title).toBeDefined();
expect(title.nativeElement.textContent).toContain('ENG_CUSTOM_TITLE', 'incorrect title value'); expect(title.nativeElement.textContent).toContain('ENG_CUSTOM_TITLE');
expect(subtitle).toBeDefined('subtitle element not found'); expect(subtitle).toBeDefined();
expect(subtitle.nativeElement.textContent).toContain('ENG_CUSTOM_SUBTITLE', 'incorrect subtitle value'); expect(subtitle.nativeElement.textContent).toContain('ENG_CUSTOM_SUBTITLE');
}); });
it('should render multiple subtitle elements', () => { it('should render multiple subtitle elements', () => {
const subTitles = fixture.debugElement.queryAll(By.css('.adf-empty-content__text')); const subTitles = fixture.debugElement.queryAll(By.css('.adf-empty-content__text'));
expect(subTitles.length).toBe(3); expect(subTitles.length).toBe(3);
expect(subTitles[0].nativeElement.textContent).toContain('SUBTITLE-1', 'missing SUBTITLE-1'); expect(subTitles[0].nativeElement.textContent).toContain('SUBTITLE-1');
expect(subTitles[1].nativeElement.textContent).toContain('SUBTITLE-2', 'missing SUBTITLE-2'); expect(subTitles[1].nativeElement.textContent).toContain('SUBTITLE-2');
expect(subTitles[2].nativeElement.textContent).toContain('SUBTITLE-3', 'missing SUBTITLE-3'); expect(subTitles[2].nativeElement.textContent).toContain('SUBTITLE-3');
}); });
}); });

View File

@ -15,45 +15,13 @@
* limitations under the License. * limitations under the License.
*/ */
import { NgModule, APP_INITIALIZER } from '@angular/core'; import { NgModule } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { CoreModule } from '../core.module'; import { CoreModule } from '../core.module';
import { AppConfigService } from '../app-config/app-config.service';
import { AppConfigServiceMock } from '../common/mock/app-config.service.mock';
import { DatePipe } from '@angular/common';
import { CookieService } from '../common/services/cookie.service';
import { CookieServiceMock } from '../mock/cookie.service.mock';
import { HttpClientModule } from '@angular/common/http';
import { directionalityConfigFactory } from '../common/services/directionality-config-factory';
import { DirectionalityConfigService } from '../common/services/directionality-config.service';
import { AuthModule, RedirectAuthService } from '../auth';
import { EMPTY, of } from 'rxjs';
import { NoopTranslateModule } from './noop-translate.module'; import { NoopTranslateModule } from './noop-translate.module';
import { UserPreferencesService } from '../common/services/user-preferences.service'; import { NoopAuthModule } from './noop-auth.module';
@NgModule({ @NgModule({
imports: [ imports: [NoopAnimationsModule, CoreModule.forRoot(), NoopTranslateModule, NoopAuthModule]
AuthModule.forRoot({ useHash: true }),
NoopAnimationsModule,
RouterTestingModule,
HttpClientModule,
CoreModule.forRoot(),
NoopTranslateModule
],
providers: [
DatePipe,
UserPreferencesService,
{ provide: AppConfigService, useClass: AppConfigServiceMock },
{ provide: CookieService, useClass: CookieServiceMock },
{
provide: APP_INITIALIZER,
useFactory: directionalityConfigFactory,
deps: [DirectionalityConfigService],
multi: true
},
{ provide: RedirectAuthService, useValue: { onLogin: EMPTY, init: () => {}, onTokenReceived: of() } }
],
exports: [NoopAnimationsModule, CoreModule, RouterTestingModule]
}) })
export class CoreTestingModule {} export class CoreTestingModule {}

View File

@ -18,3 +18,4 @@
export * from './core.testing.module'; export * from './core.testing.module';
export * from './core.story.module'; export * from './core.story.module';
export * from './noop-translate.module'; export * from './noop-translate.module';
export * from './noop-auth.module';

View File

@ -0,0 +1,53 @@
/*!
* @license
* Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { APP_INITIALIZER, Injectable, NgModule } from '@angular/core';
import { AuthModule, RedirectAuthService } from '../auth';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppConfigService, StoragePrefixFactory } from '../app-config';
import { AppConfigServiceMock, CookieService, StorageService } from '../common';
import { CookieServiceMock } from '../mock';
import { EMPTY, of } from 'rxjs';
import { loadAppConfig } from '../app-config/app-config.loader';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({ providedIn: 'root' })
export class NoopRedirectAuthService extends RedirectAuthService {
onLogin = EMPTY;
onTokenReceived = of();
init(): Promise<boolean> {
return Promise.resolve(true);
}
}
@NgModule({
imports: [AuthModule.forRoot({ useHash: true }), HttpClientTestingModule, RouterTestingModule],
providers: [
{ provide: AppConfigService, useClass: AppConfigServiceMock },
{ provide: CookieService, useClass: CookieServiceMock },
{ provide: RedirectAuthService, useClass: NoopRedirectAuthService },
{
provide: APP_INITIALIZER,
useFactory: loadAppConfig,
deps: [AppConfigService, StorageService, AdfHttpClient, StoragePrefixFactory],
multi: true
}
]
})
export class NoopAuthModule {}

View File

@ -15,13 +15,14 @@
* limitations under the License. * limitations under the License.
*/ */
import { EventEmitter, NgModule } from '@angular/core'; import { EventEmitter, Injectable, NgModule } from '@angular/core';
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { TranslationService } from '../translation/translation.service'; import { TranslationService } from '../translation/translation.service';
import { LangChangeEvent } from '../mock'; import { LangChangeEvent } from '../mock';
import { Observable, of } from 'rxjs'; import { Observable, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class NoopTranslationService implements TranslationService { export class NoopTranslationService implements TranslationService {
defaultLang: string = 'en'; defaultLang: string = 'en';
userLang: string; userLang: string;

View File

@ -16,16 +16,15 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CoreTestingModule } from '../testing/core.testing.module';
import { ToolbarComponent } from './toolbar.component'; import { ToolbarComponent } from './toolbar.component';
import { TOOLBAR_DIRECTIVES } from './toolbar.module'; import { NoopTranslateModule } from '@alfresco/adf-core';
describe('ToolbarComponent', () => { describe('ToolbarComponent', () => {
let fixture: ComponentFixture<ToolbarComponent>; let fixture: ComponentFixture<ToolbarComponent>;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, ...TOOLBAR_DIRECTIVES] imports: [NoopTranslateModule, ToolbarComponent]
}); });
fixture = TestBed.createComponent(ToolbarComponent); fixture = TestBed.createComponent(ToolbarComponent);

View File

@ -19,11 +19,12 @@ import { Component } from '@angular/core';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu'; import { MatMenuModule } from '@angular/material/menu';
import { ViewerComponent } from '../viewer.component'; import { ViewerComponent } from '../viewer.component';
import { ViewerMoreActionsComponent } from '../viewer-more-actions.component';
@Component({ @Component({
selector: 'adf-viewer-container-more-actions', selector: 'adf-viewer-container-more-actions',
standalone: true, standalone: true,
imports: [ViewerComponent, MatIconModule, MatMenuModule], imports: [ViewerComponent, MatIconModule, MatMenuModule, ViewerMoreActionsComponent],
template: ` template: `
<adf-viewer> <adf-viewer>
<adf-viewer-more-actions> <adf-viewer-more-actions>
@ -31,7 +32,7 @@ import { ViewerComponent } from '../viewer.component';
<mat-icon>dialpad</mat-icon> <mat-icon>dialpad</mat-icon>
<span>Action One</span> <span>Action One</span>
</button> </button>
<button mat-menu-item disabled> <button mat-menu-item [disabled]="true">
<mat-icon>voicemail</mat-icon> <mat-icon>voicemail</mat-icon>
<span>Action Two</span> <span>Action Two</span>
</button> </button>

View File

@ -19,11 +19,12 @@ import { Component } from '@angular/core';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu'; import { MatMenuModule } from '@angular/material/menu';
import { ViewerComponent } from '../viewer.component'; import { ViewerComponent } from '../viewer.component';
import { ViewerOpenWithComponent } from '../viewer-open-with.component';
@Component({ @Component({
selector: 'adf-viewer-container-open-with', selector: 'adf-viewer-container-open-with',
standalone: true, standalone: true,
imports: [ViewerComponent, MatIconModule, MatMenuModule], imports: [ViewerComponent, MatIconModule, MatMenuModule, ViewerOpenWithComponent],
template: ` template: `
<adf-viewer> <adf-viewer>
<adf-viewer-open-with> <adf-viewer-open-with>
@ -31,7 +32,7 @@ import { ViewerComponent } from '../viewer.component';
<mat-icon>dialpad</mat-icon> <mat-icon>dialpad</mat-icon>
<span>Option 1</span> <span>Option 1</span>
</button> </button>
<button mat-menu-item disabled> <button mat-menu-item [disabled]="true">
<mat-icon>voicemail</mat-icon> <mat-icon>voicemail</mat-icon>
<span>Option 2</span> <span>Option 2</span>
</button> </button>

View File

@ -17,11 +17,12 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { ViewerComponent } from '../viewer.component'; import { ViewerComponent } from '../viewer.component';
import { ViewerSidebarComponent } from '../viewer-sidebar.component';
@Component({ @Component({
selector: 'adf-viewer-container-sidebar', selector: 'adf-viewer-container-sidebar',
standalone: true, standalone: true,
imports: [ViewerComponent], imports: [ViewerComponent, ViewerSidebarComponent],
template: ` template: `
<adf-viewer> <adf-viewer>
<adf-viewer-sidebar> <adf-viewer-sidebar>

View File

@ -19,11 +19,12 @@ import { Component } from '@angular/core';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { ViewerComponent } from '../viewer.component'; import { ViewerComponent } from '../viewer.component';
import { ViewerToolbarActionsComponent } from '../viewer-toolbar-actions.component';
@Component({ @Component({
selector: 'adf-viewer-container-toolbar-actions', selector: 'adf-viewer-container-toolbar-actions',
standalone: true, standalone: true,
imports: [ViewerComponent, MatIconModule, MatButtonModule], imports: [ViewerComponent, MatIconModule, MatButtonModule, ViewerToolbarActionsComponent],
template: ` template: `
<adf-viewer> <adf-viewer>
<adf-viewer-toolbar-actions> <adf-viewer-toolbar-actions>

View File

@ -17,11 +17,12 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { ViewerComponent } from '../viewer.component'; import { ViewerComponent } from '../viewer.component';
import { ViewerToolbarComponent } from '../viewer-toolbar.component';
@Component({ @Component({
selector: 'adf-viewer-container-toolbar', selector: 'adf-viewer-container-toolbar',
standalone: true, standalone: true,
imports: [ViewerComponent], imports: [ViewerComponent, ViewerToolbarComponent],
template: ` template: `
<adf-viewer> <adf-viewer>
<adf-viewer-toolbar> <adf-viewer-toolbar>

View File

@ -33,11 +33,14 @@ declare const pdfjsLib: any;
@Component({ @Component({
selector: 'adf-test-dialog-component', selector: 'adf-test-dialog-component',
standalone: true,
template: '' template: ''
}) })
class TestDialogComponent {} class TestDialogComponent {}
@Component({ @Component({
standalone: true,
imports: [PdfViewerComponent],
template: ` <adf-pdf-viewer [allowThumbnails]="true" [showToolbar]="true" [urlFile]="urlFile"></adf-pdf-viewer> ` template: ` <adf-pdf-viewer [allowThumbnails]="true" [showToolbar]="true" [urlFile]="urlFile"></adf-pdf-viewer> `
}) })
class UrlTestComponent { class UrlTestComponent {
@ -52,6 +55,8 @@ class UrlTestComponent {
} }
@Component({ @Component({
standalone: true,
imports: [PdfViewerComponent],
template: ` <adf-pdf-viewer [allowThumbnails]="true" [showToolbar]="true" [urlFile]="urlFile"></adf-pdf-viewer> ` template: ` <adf-pdf-viewer [allowThumbnails]="true" [showToolbar]="true" [urlFile]="urlFile"></adf-pdf-viewer> `
}) })
class UrlTestPasswordComponent { class UrlTestPasswordComponent {
@ -66,6 +71,8 @@ class UrlTestPasswordComponent {
} }
@Component({ @Component({
standalone: true,
imports: [PdfViewerComponent],
template: ` <adf-pdf-viewer [allowThumbnails]="true" [showToolbar]="true" [blobFile]="blobFile"></adf-pdf-viewer> ` template: ` <adf-pdf-viewer [allowThumbnails]="true" [showToolbar]="true" [blobFile]="blobFile"></adf-pdf-viewer> `
}) })
class BlobTestComponent { class BlobTestComponent {
@ -105,10 +112,9 @@ describe('Test PdfViewer component', () => {
let change: any; let change: any;
let dialog: MatDialog; let dialog: MatDialog;
beforeEach((done) => { beforeEach(async () => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [CoreTestingModule, UrlTestComponent, TestDialogComponent, UrlTestPasswordComponent, BlobTestComponent],
declarations: [TestDialogComponent, UrlTestComponent, UrlTestPasswordComponent, BlobTestComponent],
providers: [ providers: [
{ {
provide: MatDialog, provide: MatDialog,
@ -129,9 +135,7 @@ describe('Test PdfViewer component', () => {
component.inputPage('1'); component.inputPage('1');
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { await fixture.whenStable();
done();
});
}); });
describe('User interaction', () => { describe('User interaction', () => {
@ -371,28 +375,6 @@ describe('Test PdfViewer component', () => {
}); });
}); });
}, 55000); }, 55000);
it('should check if page fits to documentContainer', (done) => {
spyOn(componentUrlTestComponent.pdfViewerComponent, 'checkPageFitInContainer');
componentUrlTestComponent.pdfViewerComponent.scalePage('auto');
fixtureUrlTestComponent.detectChanges();
fixtureUrlTestComponent.whenStable().then(() => {
expect(componentUrlTestComponent.pdfViewerComponent.checkPageFitInContainer).toHaveBeenCalled();
done();
});
});
it('should check if document has overflow', (done) => {
spyOn(componentUrlTestComponent.pdfViewerComponent, 'setScaleUpdatePages');
componentUrlTestComponent.pdfViewerComponent.scalePage('auto');
fixtureUrlTestComponent.detectChanges();
fixtureUrlTestComponent.whenStable().then(() => {
expect(componentUrlTestComponent.pdfViewerComponent.setScaleUpdatePages).toHaveBeenCalled();
done();
});
});
}); });
}); });
@ -425,14 +407,13 @@ describe('Test PdfViewer component', () => {
document.body.removeChild(elementUrlTestComponent); document.body.removeChild(elementUrlTestComponent);
}); });
it('should use the custom zoom if it is present in the app.config', (done) => { it('should use the custom zoom if it is present in the app.config', async () => {
spyOn(componentUrlTestComponent.pdfViewerComponent.pdfViewer, 'forceRendering').and.callFake(() => {}); spyOn(componentUrlTestComponent.pdfViewerComponent.pdfViewer, 'forceRendering').and.callFake(() => {});
fixtureUrlTestComponent.detectChanges(); fixtureUrlTestComponent.detectChanges();
fixtureUrlTestComponent.whenStable().then(() => { await fixtureUrlTestComponent.whenStable();
expect(componentUrlTestComponent.pdfViewerComponent.pdfViewer.currentScale).toBe(0.8);
done(); expect(componentUrlTestComponent.pdfViewerComponent.pdfViewer.currentScale).toBe(0.8);
});
}); });
}); });
@ -531,15 +512,12 @@ describe('Test PdfViewer component', () => {
let fixtureUrlTestComponent: ComponentFixture<UrlTestComponent>; let fixtureUrlTestComponent: ComponentFixture<UrlTestComponent>;
let elementUrlTestComponent: HTMLElement; let elementUrlTestComponent: HTMLElement;
beforeEach((done) => { beforeEach(async () => {
fixtureUrlTestComponent = TestBed.createComponent(UrlTestComponent); fixtureUrlTestComponent = TestBed.createComponent(UrlTestComponent);
elementUrlTestComponent = fixtureUrlTestComponent.nativeElement; elementUrlTestComponent = fixtureUrlTestComponent.nativeElement;
fixtureUrlTestComponent.detectChanges(); fixtureUrlTestComponent.detectChanges();
await fixtureUrlTestComponent.whenStable();
fixtureUrlTestComponent.whenStable().then(() => {
done();
});
}); });
afterEach(() => { afterEach(() => {
@ -586,15 +564,12 @@ describe('Test PdfViewer component', () => {
let fixtureBlobTestComponent: ComponentFixture<BlobTestComponent>; let fixtureBlobTestComponent: ComponentFixture<BlobTestComponent>;
let elementBlobTestComponent: HTMLElement; let elementBlobTestComponent: HTMLElement;
beforeEach((done) => { beforeEach(async () => {
fixtureBlobTestComponent = TestBed.createComponent(BlobTestComponent); fixtureBlobTestComponent = TestBed.createComponent(BlobTestComponent);
elementBlobTestComponent = fixtureBlobTestComponent.nativeElement; elementBlobTestComponent = fixtureBlobTestComponent.nativeElement;
fixtureBlobTestComponent.detectChanges(); fixtureBlobTestComponent.detectChanges();
await fixtureBlobTestComponent.whenStable();
fixtureBlobTestComponent.whenStable().then(() => {
done();
});
}); });
afterEach(() => { afterEach(() => {
@ -681,44 +656,38 @@ describe('Test PdfViewer component', () => {
document.body.removeChild(fixtureUrlTestPasswordComponent.nativeElement); document.body.removeChild(fixtureUrlTestPasswordComponent.nativeElement);
}); });
it('should try to access protected pdf', (done) => { it('should try to access protected pdf', async () => {
componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.NEED_PASSWORD);
fixture.detectChanges();
await fixture.whenStable();
expect(dialog.open).toHaveBeenCalledTimes(1);
});
it('should raise dialog asking for password', async () => {
componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.NEED_PASSWORD); componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.NEED_PASSWORD);
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { await fixture.whenStable();
fixture.detectChanges();
expect(dialog.open).toHaveBeenCalledTimes(1); fixture.detectChanges();
done(); expect(dialog.open['calls'].all()[0].args[1].data).toEqual({
reason: pdfjsLib.PasswordResponses.NEED_PASSWORD
}); });
}); });
it('should raise dialog asking for password', (done) => { it('it should raise dialog with incorrect password', async () => {
componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.NEED_PASSWORD);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(dialog.open['calls'].all()[0].args[1].data).toEqual({
reason: pdfjsLib.PasswordResponses.NEED_PASSWORD
});
done();
});
});
it('it should raise dialog with incorrect password', (done) => {
componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.INCORRECT_PASSWORD); componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.INCORRECT_PASSWORD);
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { await fixture.whenStable();
fixture.detectChanges(); expect(dialog.open['calls'].all()[0].args[1].data).toEqual({
expect(dialog.open['calls'].all()[0].args[1].data).toEqual({ reason: pdfjsLib.PasswordResponses.INCORRECT_PASSWORD
reason: pdfjsLib.PasswordResponses.INCORRECT_PASSWORD
});
done();
}); });
}); });
}); });
describe('Close password dialog ', () => { describe('Close password dialog ', () => {
beforeEach((done) => { beforeEach(async () => {
fixtureUrlTestPasswordComponent = TestBed.createComponent(UrlTestPasswordComponent); fixtureUrlTestPasswordComponent = TestBed.createComponent(UrlTestPasswordComponent);
componentUrlTestPasswordComponent = fixtureUrlTestPasswordComponent.componentInstance; componentUrlTestPasswordComponent = fixtureUrlTestPasswordComponent.componentInstance;
@ -732,25 +701,18 @@ describe('Test PdfViewer component', () => {
spyOn(componentUrlTestPasswordComponent.pdfViewerComponent.close, 'emit'); spyOn(componentUrlTestPasswordComponent.pdfViewerComponent.close, 'emit');
fixtureUrlTestPasswordComponent.detectChanges(); fixtureUrlTestPasswordComponent.detectChanges();
await fixtureUrlTestPasswordComponent.whenStable();
fixtureUrlTestPasswordComponent.whenStable().then(() => {
done();
});
}); });
afterEach(() => { afterEach(() => {
document.body.removeChild(fixtureUrlTestPasswordComponent.nativeElement); document.body.removeChild(fixtureUrlTestPasswordComponent.nativeElement);
}); });
it('should try to access protected pdf', (done) => { it('should try to access protected pdf', async () => {
componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.NEED_PASSWORD); componentUrlTestPasswordComponent.pdfViewerComponent.onPdfPassword(() => {}, pdfjsLib.PasswordResponses.NEED_PASSWORD);
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { await fixture.whenStable();
fixture.detectChanges(); expect(componentUrlTestPasswordComponent.pdfViewerComponent.close.emit).toHaveBeenCalledWith();
expect(componentUrlTestPasswordComponent.pdfViewerComponent.close.emit).toHaveBeenCalledWith();
done();
});
}); });
}); });
}); });

View File

@ -20,16 +20,18 @@ import { Location } from '@angular/common';
import { SpyLocation } from '@angular/common/testing'; import { SpyLocation } from '@angular/common/testing';
import { Component, TemplateRef, ViewChild } from '@angular/core'; import { Component, TemplateRef, ViewChild } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatButtonModule } from '@angular/material/button'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatDialog } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { CoreTestingModule } from '../../../testing'; import { NoopTranslateModule } from '../../../testing';
import { RenderingQueueServices } from '../../services/rendering-queue.services'; import { RenderingQueueServices } from '../../services/rendering-queue.services';
import { ViewerRenderComponent } from './viewer-render.component'; import { ViewerRenderComponent } from './viewer-render.component';
import { ViewerExtensionDirective } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
@Component({ @Component({
selector: 'adf-double-viewer', selector: 'adf-double-viewer',
standalone: true,
imports: [ViewerExtensionDirective, ViewerRenderComponent],
template: ` template: `
<adf-viewer-render [urlFile]="urlFileViewer1" [viewerTemplateExtensions]="viewerTemplateExtensions" #viewer1></adf-viewer-render> <adf-viewer-render [urlFile]="urlFileViewer1" [viewerTemplateExtensions]="viewerTemplateExtensions" #viewer1></adf-viewer-render>
<adf-viewer-render [urlFile]="urlFileViewer2" #viewer2></adf-viewer-render> <adf-viewer-render [urlFile]="urlFileViewer2" #viewer2></adf-viewer-render>
@ -70,8 +72,7 @@ describe('ViewerComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule, MatButtonModule, MatIconModule], imports: [NoopTranslateModule, NoopAnimationsModule, MatDialogModule, ViewerRenderComponent, DoubleViewerComponent],
declarations: [DoubleViewerComponent],
providers: [RenderingQueueServices, { provide: Location, useClass: SpyLocation }, MatDialog] providers: [RenderingQueueServices, { provide: Location, useClass: SpyLocation }, MatDialog]
}); });
fixture = TestBed.createComponent(ViewerRenderComponent); fixture = TestBed.createComponent(ViewerRenderComponent);

View File

@ -22,5 +22,5 @@ import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@ang
// First, initialize the Angular testing environment. // First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), {
teardown: { destroyAfterEach: false } teardown: { destroyAfterEach: true }
}); });

View File

@ -24,5 +24,5 @@ import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@ang
// First, initialize the Angular testing environment. // First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), {
teardown: { destroyAfterEach: false } teardown: { destroyAfterEach: true }
}); });

View File

@ -42,7 +42,7 @@ export class DialogSelectAppTestComponent {
}); });
this.dialogRef.afterClosed().subscribe((selectedProcess) => { this.dialogRef.afterClosed().subscribe((selectedProcess) => {
this.processId = selectedProcess.id; this.processId = selectedProcess?.id;
}); });
} }
} }

View File

@ -17,13 +17,13 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { AlfrescoApiService, ContentModule, ContentNodeSelectorPanelComponent, DocumentListService, SitesService, NodesApiService } from '@alfresco/adf-content-services'; import { ContentNodeSelectorPanelComponent, DocumentListService, SitesService, NodesApiService } from '@alfresco/adf-content-services';
import { EventEmitter, NO_ERRORS_SCHEMA } from '@angular/core'; import { EventEmitter, NO_ERRORS_SCHEMA } from '@angular/core';
import { ProcessTestingModule } from '../../../testing/process.testing.module'; import { ProcessTestingModule } from '../../../testing/process.testing.module';
import { AttachFileWidgetDialogComponent } from './attach-file-widget-dialog.component'; import { AttachFileWidgetDialogComponent } from './attach-file-widget-dialog.component';
import { BasicAlfrescoAuthService, OidcAuthenticationService } from '@alfresco/adf-core'; import { AuthenticationService } from '@alfresco/adf-core';
import { AttachFileWidgetDialogComponentData } from './attach-file-widget-dialog-component.interface'; import { AttachFileWidgetDialogComponentData } from './attach-file-widget-dialog-component.interface';
import { of, throwError } from 'rxjs'; import { of, Subject, throwError } from 'rxjs';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { Node, SiteEntry, NodeEntry, SitePaging, SitePagingList } from '@alfresco/js-api'; import { Node, SiteEntry, NodeEntry, SitePaging, SitePagingList } from '@alfresco/js-api';
@ -39,21 +39,19 @@ describe('AttachFileWidgetDialogComponent', () => {
isSelectionValid: (entry: Node) => entry.isFile isSelectionValid: (entry: Node) => entry.isFile
}; };
let element: HTMLInputElement; let element: HTMLInputElement;
let basicAlfrescoAuthService: BasicAlfrescoAuthService;
let siteService: SitesService; let siteService: SitesService;
let nodeService: NodesApiService; let nodeService: NodesApiService;
let documentListService: DocumentListService; let documentListService: DocumentListService;
let apiService: AlfrescoApiService; let isLoggedInSpy: jasmine.Spy;
let matDialogRef: MatDialogRef<AttachFileWidgetDialogComponent>; let authService: AuthenticationService;
let closeSpy: jasmine.Spy;
let isLogged = false;
const fakeSite = new SiteEntry({ entry: { id: 'fake-site', guid: 'fake-site', title: 'fake-site', visibility: 'visible' } }); const fakeSite = new SiteEntry({ entry: { id: 'fake-site', guid: 'fake-site', title: 'fake-site', visibility: 'visible' } });
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ContentModule.forRoot(), ProcessTestingModule, AttachFileWidgetDialogComponent], imports: [ProcessTestingModule, AttachFileWidgetDialogComponent],
providers: [ providers: [
{ provide: OidcAuthenticationService, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: data }, { provide: MAT_DIALOG_DATA, useValue: data },
{ provide: MatDialogRef, useValue: { close: () => of() } } { provide: MatDialogRef, useValue: { close: () => of() } }
], ],
@ -62,12 +60,16 @@ describe('AttachFileWidgetDialogComponent', () => {
fixture = TestBed.createComponent(AttachFileWidgetDialogComponent); fixture = TestBed.createComponent(AttachFileWidgetDialogComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;
element = fixture.nativeElement; element = fixture.nativeElement;
basicAlfrescoAuthService = fixture.debugElement.injector.get(BasicAlfrescoAuthService);
siteService = fixture.debugElement.injector.get(SitesService); siteService = fixture.debugElement.injector.get(SitesService);
nodeService = fixture.debugElement.injector.get(NodesApiService); nodeService = fixture.debugElement.injector.get(NodesApiService);
documentListService = fixture.debugElement.injector.get(DocumentListService); documentListService = fixture.debugElement.injector.get(DocumentListService);
matDialogRef = fixture.debugElement.injector.get(MatDialogRef);
apiService = fixture.debugElement.injector.get(AlfrescoApiService); const matDialogRef = fixture.debugElement.injector.get(MatDialogRef);
closeSpy = spyOn(matDialogRef, 'close');
authService = fixture.debugElement.injector.get(AuthenticationService);
spyOn(authService, 'login').and.returnValue(of({ type: 'type', ticket: 'ticket' }));
authService.onLogin = new Subject<any>();
spyOn(documentListService, 'getFolderNode').and.returnValue(of({ entry: { path: { elements: [] } } } as NodeEntry)); spyOn(documentListService, 'getFolderNode').and.returnValue(of({ entry: { path: { elements: [] } } } as NodeEntry));
spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test')); spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test'));
@ -77,22 +79,17 @@ describe('AttachFileWidgetDialogComponent', () => {
spyOn(siteService, 'getSite').and.returnValue(of(fakeSite)); spyOn(siteService, 'getSite').and.returnValue(of(fakeSite));
spyOn(siteService, 'getSites').and.returnValue(of(new SitePaging({ list: new SitePagingList({ entries: [] }) }))); spyOn(siteService, 'getSites').and.returnValue(of(new SitePaging({ list: new SitePagingList({ entries: [] }) })));
spyOn(widget, 'isLoggedIn').and.callFake(() => isLogged); isLoggedInSpy = spyOn(widget, 'isLoggedIn').and.returnValue(false);
}); });
afterEach(() => { afterEach(() => {
fixture.destroy(); fixture.destroy();
}); });
it('should be able to create the widget', () => {
fixture.detectChanges();
expect(widget).not.toBeNull();
});
describe('When is not logged in', () => { describe('When is not logged in', () => {
beforeEach(() => { beforeEach(() => {
isLoggedInSpy.and.returnValue(false);
fixture.detectChanges(); fixture.detectChanges();
isLogged = false;
}); });
it('should show the login form', () => { it('should show the login form', () => {
@ -103,8 +100,7 @@ describe('AttachFileWidgetDialogComponent', () => {
}); });
it('should be able to login', (done) => { it('should be able to login', (done) => {
spyOn(basicAlfrescoAuthService, 'login').and.returnValue(of({ type: 'type', ticket: 'ticket' })); isLoggedInSpy.and.returnValue(true);
isLogged = true;
let loginButton: HTMLButtonElement = element.querySelector('[data-automation-id="attach-file-dialog-actions-login"]'); let loginButton: HTMLButtonElement = element.querySelector('[data-automation-id="attach-file-dialog-actions-login"]');
const usernameInput: HTMLInputElement = element.querySelector('#username'); const usernameInput: HTMLInputElement = element.querySelector('#username');
const passwordInput: HTMLInputElement = element.querySelector('#password'); const passwordInput: HTMLInputElement = element.querySelector('#password');
@ -129,7 +125,7 @@ describe('AttachFileWidgetDialogComponent', () => {
let contentNodePanel; let contentNodePanel;
beforeEach(() => { beforeEach(() => {
isLogged = true; isLoggedInSpy.and.returnValue(true);
fixture.detectChanges(); fixture.detectChanges();
contentNodePanel = fixture.debugElement.query(By.directive(ContentNodeSelectorPanelComponent)); contentNodePanel = fixture.debugElement.query(By.directive(ContentNodeSelectorPanelComponent));
}); });
@ -181,43 +177,36 @@ describe('AttachFileWidgetDialogComponent', () => {
describe('login only', () => { describe('login only', () => {
beforeEach(() => { beforeEach(() => {
spyOn(basicAlfrescoAuthService, 'login').and.returnValue(of({ type: 'type', ticket: 'ticket' })); widget.data = {
spyOn(matDialogRef, 'close').and.callThrough(); ...widget.data,
fixture.detectChanges(); loginOnly: true,
widget.data.loginOnly = true; registerExternalHost: () => {}
widget.data.registerExternalHost = () => {}; };
isLogged = false;
}); });
it('should close the dialog once user loggedIn', () => { it('should close the dialog once user loggedIn', async () => {
isLoggedInSpy.and.returnValue(false);
fixture.detectChanges(); fixture.detectChanges();
isLogged = true;
const loginButton = element.querySelector<HTMLButtonElement>('[data-automation-id="attach-file-dialog-actions-login"]');
const usernameInput = element.querySelector<HTMLInputElement>('#username');
const passwordInput = element.querySelector<HTMLInputElement>('#password');
usernameInput.value = 'fake-user';
passwordInput.value = 'fake-user';
usernameInput.dispatchEvent(new Event('input'));
passwordInput.dispatchEvent(new Event('input'));
loginButton.click();
basicAlfrescoAuthService.onLogin.next('logged-in'); authService.onLogin.next('logged-in');
fixture.detectChanges(); fixture.detectChanges();
expect(matDialogRef.close).toHaveBeenCalled(); await fixture.whenStable();
expect(closeSpy).toHaveBeenCalled();
}); });
it('should close the dialog immediately if user already loggedIn', () => { it('should close the dialog immediately if user already loggedIn', () => {
isLogged = true; isLoggedInSpy.and.returnValue(true);
fixture.detectChanges(); fixture.detectChanges();
spyOn(apiService, 'getInstance').and.returnValue({ isLoggedIn: () => true } as any); fixture.componentInstance.ngOnInit();
widget.updateExternalHost(); expect(closeSpy).toHaveBeenCalled();
expect(matDialogRef.close).toHaveBeenCalled();
}); });
}); });
describe('Attach button', () => { describe('Attach button', () => {
beforeEach(() => { beforeEach(() => {
isLogged = true; isLoggedInSpy.and.returnValue(true);
}); });
it('should be disabled by default', () => { it('should be disabled by default', () => {

View File

@ -15,16 +15,24 @@
* limitations under the License. * limitations under the License.
*/ */
import { Component, Inject, ViewEncapsulation, ViewChild } from '@angular/core'; import { Component, Inject, ViewEncapsulation, ViewChild, OnDestroy, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { LoginDialogPanelComponent, TranslationService, AuthenticationService } from '@alfresco/adf-core'; import { LoginDialogPanelComponent, TranslationService, AuthenticationService } from '@alfresco/adf-core';
import { AttachFileWidgetDialogComponentData } from './attach-file-widget-dialog-component.interface'; import { AttachFileWidgetDialogComponentData } from './attach-file-widget-dialog-component.interface';
import { DocumentListService, SitesService, SearchService, ContentNodeSelectorPanelComponent, AlfrescoApiService } from '@alfresco/adf-content-services'; import {
DocumentListService,
SitesService,
SearchService,
ContentNodeSelectorPanelComponent,
AlfrescoApiService
} from '@alfresco/adf-content-services';
import { ExternalAlfrescoApiService } from '../../services/external-alfresco-api.service'; import { ExternalAlfrescoApiService } from '../../services/external-alfresco-api.service';
import { Node } from '@alfresco/js-api'; import { Node } from '@alfresco/js-api';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({ @Component({
selector: 'adf-attach-file-widget-dialog', selector: 'adf-attach-file-widget-dialog',
@ -41,7 +49,7 @@ import { TranslateModule } from '@ngx-translate/core';
{ provide: AlfrescoApiService, useClass: ExternalAlfrescoApiService } { provide: AlfrescoApiService, useClass: ExternalAlfrescoApiService }
] ]
}) })
export class AttachFileWidgetDialogComponent { export class AttachFileWidgetDialogComponent implements OnInit, OnDestroy {
@ViewChild('adfLoginPanel') @ViewChild('adfLoginPanel')
loginPanel: LoginDialogPanelComponent; loginPanel: LoginDialogPanelComponent;
@ -50,6 +58,8 @@ export class AttachFileWidgetDialogComponent {
buttonActionName: string; buttonActionName: string;
chosenNode: Node[]; chosenNode: Node[];
private onDestroy$ = new Subject<boolean>();
constructor( constructor(
private translation: TranslationService, private translation: TranslationService,
@Inject(MAT_DIALOG_DATA) public data: AttachFileWidgetDialogComponentData, @Inject(MAT_DIALOG_DATA) public data: AttachFileWidgetDialogComponentData,
@ -61,16 +71,21 @@ export class AttachFileWidgetDialogComponent {
this.action = data.actionName ? data.actionName.toUpperCase() : 'CHOOSE'; this.action = data.actionName ? data.actionName.toUpperCase() : 'CHOOSE';
this.buttonActionName = `ATTACH-FILE.ACTIONS.${this.action}`; this.buttonActionName = `ATTACH-FILE.ACTIONS.${this.action}`;
this.updateTitle('DROPDOWN.MY_FILES_OPTION'); this.updateTitle('DROPDOWN.MY_FILES_OPTION');
this.updateExternalHost();
} }
updateExternalHost() { ngOnInit() {
this.authenticationService.onLogin.subscribe(() => this.registerAndClose()); this.authenticationService.onLogin.pipe(takeUntil(this.onDestroy$)).subscribe(() => this.registerAndClose());
if (this.isLoggedIn()) { if (this.isLoggedIn()) {
this.registerAndClose(); this.registerAndClose();
} }
} }
ngOnDestroy() {
this.onDestroy$.next(true);
this.onDestroy$.complete();
}
isLoggedIn(): boolean { isLoggedIn(): boolean {
return !!this.externalApiService.getInstance()?.isLoggedIn(); return !!this.externalApiService.getInstance()?.isLoggedIn();
} }
@ -111,10 +126,13 @@ export class AttachFileWidgetDialogComponent {
} }
private registerAndClose() { private registerAndClose() {
this.data.registerExternalHost(this.data.accountIdentifier, this.externalApiService); if (this.data) {
if (this.data.loginOnly) { this.data.registerExternalHost?.(this.data.accountIdentifier, this.externalApiService);
this.data.selected.complete();
this.matDialogRef.close(); if (this.data.loginOnly) {
this.data.selected?.complete();
this.matDialogRef.close();
}
} }
} }
} }

View File

@ -28,7 +28,7 @@ import {
AppConfigService, AppConfigService,
AppConfigValues AppConfigValues
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { ContentNodeDialogService, ContentModule } from '@alfresco/adf-content-services'; import { ContentNodeDialogService } from '@alfresco/adf-content-services';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { Node } from '@alfresco/js-api'; import { Node } from '@alfresco/js-api';
import { ProcessTestingModule } from '../../../testing/process.testing.module'; import { ProcessTestingModule } from '../../../testing/process.testing.module';
@ -154,7 +154,7 @@ describe('AttachFileWidgetComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ProcessTestingModule, ContentModule.forRoot()] imports: [ProcessTestingModule, AttachFileWidgetComponent]
}); });
fixture = TestBed.createComponent(AttachFileWidgetComponent); fixture = TestBed.createComponent(AttachFileWidgetComponent);
widget = fixture.componentInstance; widget = fixture.componentInstance;

View File

@ -15,12 +15,12 @@
* limitations under the License. * limitations under the License.
*/ */
import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PeopleComponent } from './people.component'; import { PeopleComponent } from './people.component';
import { ProcessTestingModule } from '../../../testing/process.testing.module'; import { ProcessTestingModule } from '../../../testing/process.testing.module';
import { LightUserRepresentation } from '@alfresco/js-api'; import { LightUserRepresentation } from '@alfresco/js-api';
import { PeopleProcessService } from '@alfresco/adf-process-services';
declare let jasmine: any; import { of, throwError } from 'rxjs';
const fakeUser: LightUserRepresentation = { const fakeUser: LightUserRepresentation = {
id: 0, id: 0,
@ -40,19 +40,24 @@ describe('PeopleComponent', () => {
let peopleComponent: PeopleComponent; let peopleComponent: PeopleComponent;
let fixture: ComponentFixture<PeopleComponent>; let fixture: ComponentFixture<PeopleComponent>;
let element: HTMLElement; let element: HTMLElement;
const userArray = [fakeUser, fakeSecondUser]; let peopleProcessService: PeopleProcessService;
let userArray: LightUserRepresentation[];
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ProcessTestingModule, PeopleComponent] imports: [ProcessTestingModule, PeopleComponent]
}); });
fixture = TestBed.createComponent(PeopleComponent); fixture = TestBed.createComponent(PeopleComponent);
peopleProcessService = fixture.debugElement.injector.get(PeopleProcessService);
peopleComponent = fixture.componentInstance; peopleComponent = fixture.componentInstance;
element = fixture.nativeElement; element = fixture.nativeElement;
peopleComponent.people = []; peopleComponent.people = [];
peopleComponent.readOnly = true; peopleComponent.readOnly = true;
fixture.detectChanges(); fixture.detectChanges();
userArray = [fakeUser, fakeSecondUser];
}); });
afterEach(() => fixture.destroy()); afterEach(() => fixture.destroy());
@ -78,18 +83,10 @@ describe('PeopleComponent', () => {
describe('when there are involved people', () => { describe('when there are involved people', () => {
beforeEach(() => { beforeEach(() => {
peopleComponent.taskId = 'fake-task-id'; peopleComponent.taskId = 'fake-task-id';
peopleComponent.people.push(...userArray); peopleComponent.people = [...userArray];
fixture.detectChanges(); fixture.detectChanges();
}); });
beforeEach(() => {
jasmine.Ajax.install();
});
afterEach(() => {
jasmine.Ajax.uninstall();
});
it('should show people involved', async () => { it('should show people involved', async () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
@ -99,33 +96,73 @@ describe('PeopleComponent', () => {
expect(gatewayElement.children.length).toBe(2); expect(gatewayElement.children.length).toBe(2);
}); });
it('should remove people involved', fakeAsync(() => { it('should remove involved user successfully', () => {
peopleComponent.removeInvolvedUser(fakeUser); spyOn(peopleProcessService, 'removeInvolvedUser').and.returnValue(of(null));
jasmine.Ajax.requests.mostRecent().respondWith({ peopleComponent.people = [...userArray];
status: 200
}); peopleComponent.removeInvolvedUser(fakeUser);
fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
const gatewayElement: any = element.querySelector('#assignment-people-list .adf-datatable-body');
expect(gatewayElement).not.toBeNull(); expect(peopleComponent.people.length).toBe(1);
expect(gatewayElement.children.length).toBe(1); expect(peopleComponent.people.find((user) => user.id === fakeUser.id)).toBeUndefined();
}); });
}));
it('should emit error when removing involved user fails', () => {
spyOn(peopleProcessService, 'removeInvolvedUser').and.returnValue(throwError(() => new Error('error')));
spyOn(peopleComponent.error, 'emit');
peopleComponent.people = [...userArray];
peopleComponent.removeInvolvedUser(fakeUser);
fixture.detectChanges();
expect(peopleComponent.people.length).toBe(2);
expect(peopleComponent.error.emit).toHaveBeenCalledWith('Impossible to remove involved user from task');
});
it('should involve user successfully', () => {
spyOn(peopleProcessService, 'involveUserWithTask').and.returnValue(of(null));
peopleComponent.people = [...userArray];
it('should involve people', fakeAsync(() => {
peopleComponent.involveUser(fakeUser); peopleComponent.involveUser(fakeUser);
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200 fixture.detectChanges();
});
fixture.whenStable().then(() => { expect(peopleComponent.people.length).toBe(3);
fixture.detectChanges(); expect(peopleComponent.people.find((user) => user.id === fakeUser.id)).toBeDefined();
const gatewayElement: any = element.querySelector('#assignment-people-list .adf-datatable-body'); });
expect(gatewayElement).not.toBeNull();
expect(gatewayElement.children.length).toBe(3); it('should emit error when involving user fails', () => {
}); spyOn(peopleProcessService, 'involveUserWithTask').and.returnValue(throwError(() => new Error('error')));
})); spyOn(peopleComponent.error, 'emit');
peopleComponent.people = [...userArray];
peopleComponent.involveUser(fakeUser);
fixture.detectChanges();
expect(peopleComponent.people.length).toBe(2);
expect(peopleComponent.error.emit).toHaveBeenCalledWith('Impossible to involve user with task');
});
it('should return an observable with user search results', (done) => { it('should return an observable with user search results', (done) => {
spyOn(peopleProcessService, 'getWorkflowUsers').and.returnValue(
of([
{
id: 1,
firstName: 'fake-test-1',
lastName: 'fake-last-1',
email: 'fake-test-1@test.com'
},
{
id: 2,
firstName: 'fake-test-2',
lastName: 'fake-last-2',
email: 'fake-test-2@test.com'
}
])
);
peopleComponent.peopleSearch$.subscribe((users) => { peopleComponent.peopleSearch$.subscribe((users) => {
expect(users.length).toBe(2); expect(users.length).toBe(2);
expect(users[0].firstName).toBe('fake-test-1'); expect(users[0].firstName).toBe('fake-test-1');
@ -135,71 +172,44 @@ describe('PeopleComponent', () => {
done(); done();
}); });
peopleComponent.searchUser('fake-search-word'); peopleComponent.searchUser('fake-search-word');
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
contentType: 'json',
responseText: {
data: [
{
id: 1,
firstName: 'fake-test-1',
lastName: 'fake-last-1',
email: 'fake-test-1@test.com'
},
{
id: 2,
firstName: 'fake-test-2',
lastName: 'fake-last-2',
email: 'fake-test-2@test.com'
}
]
}
});
}); });
it('should return an empty list for not valid search', (done) => { it('should return an empty list for not valid search', (done) => {
spyOn(peopleProcessService, 'getWorkflowUsers').and.returnValue(of([]));
peopleComponent.peopleSearch$.subscribe((users) => { peopleComponent.peopleSearch$.subscribe((users) => {
expect(users.length).toBe(0); expect(users.length).toBe(0);
done(); done();
}); });
peopleComponent.searchUser('fake-search-word'); peopleComponent.searchUser('fake-search-word');
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
contentType: 'json',
responseText: {}
});
}); });
}); });
describe('when there are errors on service call', () => { describe('when there are errors on service call', () => {
beforeEach(() => { beforeEach(() => {
jasmine.Ajax.install();
peopleComponent.people.push(...userArray); peopleComponent.people.push(...userArray);
fixture.detectChanges(); fixture.detectChanges();
}); });
afterEach(() => {
jasmine.Ajax.uninstall();
});
it('should not remove user if remove involved user fail', async () => { it('should not remove user if remove involved user fail', async () => {
spyOn(peopleProcessService, 'removeInvolvedUser').and.returnValue(throwError(() => new Error('error')));
peopleComponent.removeInvolvedUser(fakeUser); peopleComponent.removeInvolvedUser(fakeUser);
jasmine.Ajax.requests.mostRecent().respondWith({
status: 403 fixture.detectChanges();
});
await fixture.whenStable(); await fixture.whenStable();
const gatewayElement: any = element.querySelector('#assignment-people-list .adf-datatable-body');
const gatewayElement = element.querySelector('#assignment-people-list .adf-datatable-body');
expect(gatewayElement).not.toBeNull(); expect(gatewayElement).not.toBeNull();
expect(gatewayElement.children.length).toBe(2); expect(gatewayElement.children.length).toBe(2);
}); });
it('should not involve user if involve user fail', async () => { it('should not involve user if involve user fail', async () => {
spyOn(peopleProcessService, 'involveUserWithTask').and.returnValue(throwError(() => new Error('error')));
peopleComponent.involveUser(fakeUser); peopleComponent.involveUser(fakeUser);
jasmine.Ajax.requests.mostRecent().respondWith({
status: 403 fixture.detectChanges();
});
await fixture.whenStable(); await fixture.whenStable();
const gatewayElement: any = element.querySelector('#assignment-people-list .adf-datatable-body');
const gatewayElement = element.querySelector('#assignment-people-list .adf-datatable-body');
expect(gatewayElement).not.toBeNull(); expect(gatewayElement).not.toBeNull();
expect(gatewayElement.children.length).toBe(2); expect(gatewayElement.children.length).toBe(2);
}); });

View File

@ -75,30 +75,30 @@ export class PeopleComponent {
} }
searchUser(searchedWord: string) { searchUser(searchedWord: string) {
this.peopleProcessService.getWorkflowUsers(this.taskId, searchedWord).subscribe( this.peopleProcessService.getWorkflowUsers(this.taskId, searchedWord).subscribe({
(users) => { next: (users) => {
this.peopleSearchObserver.next(users); this.peopleSearchObserver.next(users);
}, },
(error) => this.error.emit(error) error: (error) => this.error.emit(error)
); });
} }
involveUser(user: LightUserRepresentation) { involveUser(user: LightUserRepresentation) {
if (user?.id !== undefined) { if (user?.id !== undefined) {
this.peopleProcessService.involveUserWithTask(this.taskId, user.id.toString()).subscribe( this.peopleProcessService.involveUserWithTask(this.taskId, user.id.toString()).subscribe({
() => (this.people = [...this.people, user]), next: () => (this.people = [...this.people, user]),
() => this.error.emit('Impossible to involve user with task') error: () => this.error.emit('Impossible to involve user with task')
); });
} }
} }
removeInvolvedUser(user: LightUserRepresentation) { removeInvolvedUser(user: LightUserRepresentation) {
this.peopleProcessService.removeInvolvedUser(this.taskId, user.id.toString()).subscribe( this.peopleProcessService.removeInvolvedUser(this.taskId, user.id.toString()).subscribe({
() => { next: () => {
this.people = this.people.filter((involvedUser) => involvedUser.id !== user.id); this.people = this.people.filter((involvedUser) => involvedUser.id !== user.id);
}, },
() => this.error.emit('Impossible to remove involved user from task') error: () => this.error.emit('Impossible to remove involved user from task')
); });
} }
getDisplayUser(firstName: string, lastName: string, delimiter: string = '-'): string { getDisplayUser(firstName: string, lastName: string, delimiter: string = '-'): string {

View File

@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { CUSTOM_ELEMENTS_SCHEMA, SimpleChange } from '@angular/core'; import { SimpleChange } from '@angular/core';
import { from, of, throwError } from 'rxjs'; import { from, of, throwError } from 'rxjs';
import { AppsProcessService } from '../../../services/apps-process.service'; import { AppsProcessService } from '../../../services/apps-process.service';
import { ProcessFilterService } from '../../services/process-filter.service'; import { ProcessFilterService } from '../../services/process-filter.service';
@ -24,7 +24,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { ProcessTestingModule } from '../../../testing/process.testing.module'; import { ProcessTestingModule } from '../../../testing/process.testing.module';
import { NavigationStart, Router } from '@angular/router'; import { NavigationStart, Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { ProcessInstanceFilterRepresentation, UserProcessInstanceFilterRepresentation } from '@alfresco/js-api'; import { ProcessInstanceFilterRepresentation, UserProcessInstanceFilterRepresentation } from '@alfresco/js-api';
const fakeProcessFilters: UserProcessInstanceFilterRepresentation[] = [ const fakeProcessFilters: UserProcessInstanceFilterRepresentation[] = [
@ -54,17 +53,26 @@ describe('ProcessFiltersComponent', () => {
let processFilterService: ProcessFilterService; let processFilterService: ProcessFilterService;
let appsProcessService: AppsProcessService; let appsProcessService: AppsProcessService;
let router: Router; let router: Router;
let getProcessFiltersSpy: jasmine.Spy;
let getDeployedApplicationsByNameSpy: jasmine.Spy;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ProcessTestingModule, RouterTestingModule], imports: [ProcessTestingModule]
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}); });
processFilterService = TestBed.inject(ProcessFilterService);
getProcessFiltersSpy = spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
appsProcessService = TestBed.inject(AppsProcessService);
getDeployedApplicationsByNameSpy = spyOn(appsProcessService, 'getDeployedApplicationsByName').and.returnValue(
from(Promise.resolve({ id: 1 }))
);
router = TestBed.inject(Router);
fixture = TestBed.createComponent(ProcessFiltersComponent); fixture = TestBed.createComponent(ProcessFiltersComponent);
filterList = fixture.componentInstance; filterList = fixture.componentInstance;
processFilterService = TestBed.inject(ProcessFilterService);
appsProcessService = TestBed.inject(AppsProcessService);
router = TestBed.inject(Router);
}); });
afterEach(() => { afterEach(() => {
@ -72,7 +80,6 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should return the filter task list', async () => { it('should return the filter task list', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const appId = '1'; const appId = '1';
const change = new SimpleChange(null, appId, true); const change = new SimpleChange(null, appId, true);
@ -97,23 +104,7 @@ describe('ProcessFiltersComponent', () => {
expect(filterList.filters[2].name).toEqual('Running'); expect(filterList.filters[2].name).toEqual('Running');
}); });
it('should select the Running process filter', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const appId = '1';
const change = new SimpleChange(null, appId, true);
filterList.ngOnChanges({ appId: change });
fixture.detectChanges();
await fixture.whenStable();
filterList.selectRunningFilter();
expect(filterList.currentFilter.name).toEqual('Running');
});
it('should emit the selected filter based on the filterParam input', async () => { it('should emit the selected filter based on the filterParam input', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.filterParam = { id: 10 } as any; filterList.filterParam = { id: 10 } as any;
const appId = '1'; const appId = '1';
const change = new SimpleChange(null, appId, true); const change = new SimpleChange(null, appId, true);
@ -142,8 +133,6 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should reset selection when filterParam is a filter that does not exist', async () => { it('should reset selection when filterParam is a filter that does not exist', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const nonExistingFilterParam = { name: 'non-existing-filter' }; const nonExistingFilterParam = { name: 'non-existing-filter' };
const appId = '1'; const appId = '1';
const change = new SimpleChange(null, appId, true); const change = new SimpleChange(null, appId, true);
@ -159,18 +148,15 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should return the filter task list, filtered By Name', () => { it('should return the filter task list, filtered By Name', () => {
const deployApp = spyOn(appsProcessService, 'getDeployedApplicationsByName').and.returnValue(from(Promise.resolve({ id: 1 })));
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const change = new SimpleChange(null, 'test', true); const change = new SimpleChange(null, 'test', true);
filterList.ngOnChanges({ appName: change }); filterList.ngOnChanges({ appName: change });
fixture.detectChanges(); fixture.detectChanges();
expect(deployApp.calls.count()).toEqual(1); expect(getDeployedApplicationsByNameSpy.calls.count()).toEqual(1);
}); });
it('should emit an error with a bad response of getProcessFilters', () => { it('should emit an error with a bad response of getProcessFilters', () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(throwError('error')); getProcessFiltersSpy.and.returnValue(throwError(() => new Error('error')));
const appId = '1'; const appId = '1';
const change = new SimpleChange(null, appId, true); const change = new SimpleChange(null, appId, true);
@ -184,7 +170,7 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should emit an error with a bad response of getDeployedApplicationsByName', () => { it('should emit an error with a bad response of getDeployedApplicationsByName', () => {
spyOn(appsProcessService, 'getDeployedApplicationsByName').and.returnValue(throwError('wrong request')); getDeployedApplicationsByNameSpy.and.returnValue(throwError(() => new Error('wrong request')));
const appId = 'fake-app'; const appId = 'fake-app';
const change = new SimpleChange(null, appId, true); const change = new SimpleChange(null, appId, true);
@ -255,8 +241,6 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should select the filter passed as input by id', async () => { it('should select the filter passed as input by id', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.filterParam = { id: 20 } as any; filterList.filterParam = { id: 20 } as any;
const appId = 1; const appId = 1;
@ -272,8 +256,6 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should select the filter passed as input by name', async () => { it('should select the filter passed as input by name', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.filterParam = { name: 'FakeAll' } as any; filterList.filterParam = { name: 'FakeAll' } as any;
const appId = 1; const appId = 1;
@ -289,7 +271,6 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should attach specific icon for each filter if hasIcon is true', async () => { it('should attach specific icon for each filter if hasIcon is true', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.showIcon = true; filterList.showIcon = true;
const change = new SimpleChange(undefined, 1, true); const change = new SimpleChange(undefined, 1, true);
filterList.ngOnChanges({ appId: change }); filterList.ngOnChanges({ appId: change });
@ -304,7 +285,6 @@ describe('ProcessFiltersComponent', () => {
}); });
it('should not attach icons for each filter if hasIcon is false', async () => { it('should not attach icons for each filter if hasIcon is false', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.showIcon = false; filterList.showIcon = false;
const change = new SimpleChange(undefined, 1, true); const change = new SimpleChange(undefined, 1, true);
filterList.ngOnChanges({ appId: change }); filterList.ngOnChanges({ appId: change });

View File

@ -15,18 +15,17 @@
* limitations under the License. * limitations under the License.
*/ */
import { NO_ERRORS_SCHEMA, SimpleChange } from '@angular/core'; import { SimpleChange } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { FormModel, FormOutcomeEvent, FormOutcomeModel, CommentModel, User } from '@alfresco/adf-core'; import { FormModel, FormOutcomeEvent, FormOutcomeModel, CommentModel, User, ADF_COMMENTS_SERVICE, CommentsService } from '@alfresco/adf-core';
import { noDataMock, taskDetailsMock, taskFormMock, tasksMock, taskDetailsWithOutAssigneeMock } from '../../../testing/mock'; import { noDataMock, taskDetailsMock, taskFormMock, tasksMock, taskDetailsWithOutAssigneeMock } from '../../../testing/mock';
import { TaskListService } from '../../services/tasklist.service'; import { TaskListService } from '../../services/tasklist.service';
import { TaskDetailsComponent } from './task-details.component'; import { TaskDetailsComponent } from './task-details.component';
import { ProcessTestingModule } from '../../../testing/process.testing.module'; import { ProcessTestingModule } from '../../../testing/process.testing.module';
import { TaskService } from '../../../form/services/task.service'; import { TaskService } from '../../../form/services/task.service';
import { TaskFormService } from '../../../form/services/task-form.service'; import { TaskFormService } from '../../../form/services/task-form.service';
import { TaskCommentsService } from '../../../services/task-comments.service';
import { PeopleProcessService } from '../../../services/people-process.service'; import { PeopleProcessService } from '../../../services/people-process.service';
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';
@ -48,32 +47,27 @@ const fakeTaskAssignResponse: any = {
}; };
describe('TaskDetailsComponent', () => { describe('TaskDetailsComponent', () => {
let taskListService: TaskListService;
let taskService: TaskService;
let taskFormService: TaskFormService; let taskFormService: TaskFormService;
let component: TaskDetailsComponent; let component: TaskDetailsComponent;
let fixture: ComponentFixture<TaskDetailsComponent>; let fixture: ComponentFixture<TaskDetailsComponent>;
let loader: HarnessLoader; let loader: HarnessLoader;
let getTaskDetailsSpy: jasmine.Spy; let getTaskDetailsSpy: jasmine.Spy;
let getCommentsSpy: jasmine.Spy;
let getTasksSpy: jasmine.Spy; let getTasksSpy: jasmine.Spy;
let assignTaskSpy: jasmine.Spy; let assignTaskSpy: jasmine.Spy;
let taskCommentsService: TaskCommentsService; let taskCommentsService: CommentsService;
let peopleProcessService: PeopleProcessService; let peopleProcessService: PeopleProcessService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ProcessTestingModule, TaskDetailsComponent], imports: [ProcessTestingModule, TaskDetailsComponent]
schemas: [NO_ERRORS_SCHEMA]
}); });
peopleProcessService = TestBed.inject(PeopleProcessService); peopleProcessService = TestBed.inject(PeopleProcessService);
spyOn(peopleProcessService, 'getCurrentUserInfo').and.returnValue(of({ email: 'fake-email' } as any)); spyOn(peopleProcessService, 'getCurrentUserInfo').and.returnValue(of({ email: 'fake-email' } as any));
taskListService = TestBed.inject(TaskListService); const taskListService = TestBed.inject(TaskListService);
spyOn(taskListService, 'getTaskChecklist').and.returnValue(of(noDataMock)); spyOn(taskListService, 'getTaskChecklist').and.returnValue(of(noDataMock));
taskService = TestBed.inject(TaskService); const taskService = TestBed.inject(TaskService);
taskFormService = TestBed.inject(TaskFormService); taskFormService = TestBed.inject(TaskFormService);
getTaskDetailsSpy = spyOn(taskListService, 'getTaskDetails').and.returnValue(of(taskDetailsMock)); getTaskDetailsSpy = spyOn(taskListService, 'getTaskDetails').and.returnValue(of(taskDetailsMock));
@ -83,9 +77,11 @@ describe('TaskDetailsComponent', () => {
getTasksSpy = spyOn(taskListService, 'getTasks').and.returnValue(of(tasksMock)); getTasksSpy = spyOn(taskListService, 'getTasks').and.returnValue(of(tasksMock));
assignTaskSpy = spyOn(taskListService, 'assignTask').and.returnValue(of(fakeTaskAssignResponse)); assignTaskSpy = spyOn(taskListService, 'assignTask').and.returnValue(of(fakeTaskAssignResponse));
taskCommentsService = TestBed.inject(TaskCommentsService);
getCommentsSpy = spyOn(taskCommentsService, 'get').and.returnValue( fixture = TestBed.createComponent(TaskDetailsComponent);
taskCommentsService = fixture.debugElement.injector.get<CommentsService>(ADF_COMMENTS_SERVICE);
spyOn(taskCommentsService, 'get').and.returnValue(
of([ of([
new CommentModel({ message: 'Test1', created: new Date(), createdBy: new User({ firstName: 'Admin', lastName: 'User' }) }), new CommentModel({ message: 'Test1', created: new Date(), createdBy: new User({ firstName: 'Admin', lastName: 'User' }) }),
new CommentModel({ message: 'Test2', created: new Date(), createdBy: new User({ firstName: 'Admin', lastName: 'User' }) }), new CommentModel({ message: 'Test2', created: new Date(), createdBy: new User({ firstName: 'Admin', lastName: 'User' }) }),
@ -93,15 +89,12 @@ describe('TaskDetailsComponent', () => {
]) ])
); );
fixture = TestBed.createComponent(TaskDetailsComponent);
peopleProcessService = TestBed.inject(PeopleProcessService);
component = fixture.componentInstance; component = fixture.componentInstance;
component.showComments = false;
loader = TestbedHarnessEnvironment.documentRootLoader(fixture); loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
}); });
afterEach(() => { afterEach(() => {
getTaskDetailsSpy.calls.reset();
getCommentsSpy.calls.reset();
fixture.destroy(); fixture.destroy();
}); });
@ -418,8 +411,12 @@ describe('TaskDetailsComponent', () => {
expect(lastValue.length).toBe(0); expect(lastValue.length).toBe(0);
}); });
it('should assign task to user', () => { it('should assign task to user', async () => {
component.assignTaskToUser(fakeUser); component.assignTaskToUser(fakeUser);
fixture.detectChanges();
await fixture.whenStable();
expect(assignTaskSpy).toHaveBeenCalled(); expect(assignTaskSpy).toHaveBeenCalled();
}); });
}); });

View File

@ -16,6 +16,7 @@
*/ */
import { import {
ADF_COMMENTS_SERVICE,
CardViewUpdateService, CardViewUpdateService,
ClickNotification, ClickNotification,
ContentLinkModel, ContentLinkModel,
@ -51,7 +52,7 @@ import { TranslateModule } from '@ngx-translate/core';
import { AttachFormComponent } from '../attach-form/attach-form.component'; import { AttachFormComponent } from '../attach-form/attach-form.component';
import { PeopleComponent, PeopleSearchComponent } from '../../../people'; import { PeopleComponent, PeopleSearchComponent } from '../../../people';
import { TaskHeaderComponent } from '../task-header/task-header.component'; import { TaskHeaderComponent } from '../task-header/task-header.component';
import { TaskCommentsComponent } from '../../../task-comments'; import { TaskCommentsComponent, TaskCommentsService } from '../../../task-comments';
import { ChecklistComponent } from '../checklist/checklist.component'; import { ChecklistComponent } from '../checklist/checklist.component';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
@ -75,6 +76,12 @@ import { MatCardModule } from '@angular/material/card';
InfoDrawerComponent, InfoDrawerComponent,
MatCardModule MatCardModule
], ],
providers: [
{
provide: ADF_COMMENTS_SERVICE,
useClass: TaskCommentsService
}
],
templateUrl: './task-details.component.html', templateUrl: './task-details.component.html',
styleUrls: ['./task-details.component.scss'], styleUrls: ['./task-details.component.scss'],
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None

View File

@ -15,36 +15,19 @@
* limitations under the License. * limitations under the License.
*/ */
import { AlfrescoApiService, AlfrescoApiServiceMock } from '@alfresco/adf-content-services';
import { NgModule } from '@angular/core'; import { NgModule } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { ProcessModule } from '../process.module'; import { ProcessModule } from '../process.module';
import { import { CoreModule, FormRenderingService, NoopTranslateModule, NoopAuthModule } from '@alfresco/adf-core';
AppConfigService,
AppConfigServiceMock,
CoreModule,
FormRenderingService,
AuthModule,
NoopTranslateModule
} from '@alfresco/adf-core';
import { ProcessFormRenderingService } from '../form/process-form-rendering.service'; import { ProcessFormRenderingService } from '../form/process-form-rendering.service';
import { RouterTestingModule } from '@angular/router/testing'; import { AlfrescoApiService, AlfrescoApiServiceMock } from '@alfresco/adf-content-services';
@NgModule({ @NgModule({
imports: [ imports: [CoreModule.forRoot(), ProcessModule.forRoot(), NoopAuthModule, NoopAnimationsModule, NoopTranslateModule],
AuthModule.forRoot({ useHash: true }),
NoopAnimationsModule,
CoreModule.forRoot(),
ProcessModule.forRoot(),
RouterTestingModule,
NoopTranslateModule
],
providers: [ providers: [
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }, { provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock },
{ provide: AppConfigService, useClass: AppConfigServiceMock },
FormRenderingService,
{ provide: FormRenderingService, useClass: ProcessFormRenderingService } { provide: FormRenderingService, useClass: ProcessFormRenderingService }
], ],
exports: [NoopAnimationsModule, CoreModule, ProcessModule] exports: [CoreModule, ProcessModule]
}) })
export class ProcessTestingModule {} export class ProcessTestingModule {}

View File

@ -22,5 +22,5 @@ import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@ang
// First, initialize the Angular testing environment. // First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), {
teardown: { destroyAfterEach: false } teardown: { destroyAfterEach: true }
}); });