[ACS-6190] prefer-promise-reject-errors rule and fixes (#9021)

* fix promise rejections

* fix promise errors

* promise error fixes

* fix promise rejections

* [ci:force] fix formatting

* test fixes

* [ci:force] fix tests

* [ci:force] fix tests

* fix incorrect return types

* meaningful errors

* remove useless pipe

* fix accessing private members in the test
This commit is contained in:
Denys Vuika
2023-10-25 12:01:45 +01:00
committed by GitHub
parent 352e0e4933
commit 8bd24dbb7c
18 changed files with 155 additions and 189 deletions

View File

@@ -101,7 +101,7 @@ module.exports = {
],
'@typescript-eslint/member-ordering': 'off',
'prefer-arrow/prefer-arrow-functions': 'off',
'prefer-promise-reject-errors': 'error',
'brace-style': 'off',
'@typescript-eslint/brace-style': 'error',
'comma-dangle': 'error',

View File

@@ -26,17 +26,14 @@ import {
AlfrescoApiService,
AlfrescoApiServiceMock,
AuthenticationService,
CoreTestingModule,
LogService
CoreTestingModule
} from '@alfresco/adf-core';
import { PeopleContentQueryRequestModel, PeopleContentService } from './people-content.service';
import { TranslateModule } from '@ngx-translate/core';
import { TestBed } from '@angular/core/testing';
describe('PeopleContentService', () => {
let peopleContentService: PeopleContentService;
let logService: LogService;
let authenticationService: AuthenticationService;
beforeEach(() => {
@@ -52,7 +49,6 @@ describe('PeopleContentService', () => {
authenticationService = TestBed.inject(AuthenticationService);
peopleContentService = TestBed.inject(PeopleContentService);
logService = TestBed.inject(LogService);
});
it('should be able to fetch person details based on id', async () => {
@@ -110,14 +106,11 @@ describe('PeopleContentService', () => {
});
it('should be able to throw an error if createPerson api failed', (done) => {
spyOn(peopleContentService.peopleApi, 'createPerson').and.returnValue(Promise.reject('failed to create new person'));
const logErrorSpy = spyOn(logService, 'error');
spyOn(peopleContentService.peopleApi, 'createPerson').and.returnValue(Promise.reject(new Error('failed to create new person')));
peopleContentService.createPerson(createNewPersonMock).subscribe(
() => {
},
(error) => {
expect(logErrorSpy).toHaveBeenCalledWith('failed to create new person');
expect(error).toEqual('failed to create new person');
() => {},
(error: Error) => {
expect(error.message).toEqual('failed to create new person');
done();
}
);

View File

@@ -16,9 +16,9 @@
*/
import { Injectable } from '@angular/core';
import { from, Observable, of, throwError } from 'rxjs';
import { AlfrescoApiService, AuthenticationService, LogService } from '@alfresco/adf-core';
import { catchError, map, tap } from 'rxjs/operators';
import { from, Observable, of } from 'rxjs';
import { AlfrescoApiService, AuthenticationService } from '@alfresco/adf-core';
import { map, tap } from 'rxjs/operators';
import { Pagination, PeopleApi, PersonBodyCreate, PersonBodyUpdate } from '@alfresco/js-api';
import { EcmUserModel } from '../models/ecm-user.model';
import { ContentService } from './content.service';
@@ -59,7 +59,6 @@ export class PeopleContentService {
constructor(
private apiService: AlfrescoApiService,
authenticationService: AuthenticationService,
private logService: LogService,
private contentService: ContentService
) {
authenticationService.onLogout.subscribe(() => {
@@ -76,8 +75,8 @@ export class PeopleContentService {
getPerson(personId: string): Observable<EcmUserModel> {
return from(this.peopleApi.getPerson(personId))
.pipe(
map((personEntry) => new EcmUserModel(personEntry.entry)),
catchError((error) => this.handleError(error)));
map((personEntry) => new EcmUserModel(personEntry.entry))
);
}
getCurrentPerson(): Observable<EcmUserModel> {
@@ -130,8 +129,7 @@ export class PeopleContentService {
map(response => ({
pagination: response.list.pagination,
entries: response.list.entries.map((person) => person.entry as EcmUserModel)
})),
catchError((err) => this.handleError(err))
}))
);
}
@@ -144,8 +142,7 @@ export class PeopleContentService {
*/
createPerson(newPerson: PersonBodyCreate, opts?: any): Observable<EcmUserModel> {
return from(this.peopleApi.createPerson(newPerson, opts)).pipe(
map((res) => res?.entry as EcmUserModel),
catchError((error) => this.handleError(error))
map((res) => res?.entry as EcmUserModel)
);
}
@@ -159,8 +156,7 @@ export class PeopleContentService {
*/
updatePerson(personId: string, details: PersonBodyUpdate, opts?: any): Observable<EcmUserModel> {
return from(this.peopleApi.updatePerson(personId, details, opts)).pipe(
map((res) => res?.entry as EcmUserModel),
catchError((error) => this.handleError(error))
map((res) => res?.entry as EcmUserModel)
);
}
@@ -177,9 +173,4 @@ export class PeopleContentService {
private buildOrderArray(sorting: PeopleContentSortingModel): string[] {
return sorting?.orderBy && sorting?.direction ? [`${sorting.orderBy} ${sorting.direction.toUpperCase()}`] : [];
}
private handleError(error: any) {
this.logService.error(error);
return throwError(error || 'Server error');
}
}

View File

@@ -201,7 +201,7 @@ export class RenditionService {
clearInterval(intervalId);
return resolve(this.handleNodeRendition(nodeId, rendition.entry.content.mimeType, versionId));
}
}, () => reject());
}, () => reject(new Error('Error geting version rendition')));
} else {
this.renditionsApi.getRendition(nodeId, renditionId).then((rendition: RenditionEntry) => {
const status: string = rendition.entry.status.toString();
@@ -210,11 +210,11 @@ export class RenditionService {
clearInterval(intervalId);
return resolve(this.handleNodeRendition(nodeId, renditionId, versionId));
}
}, () => reject());
}, () => reject(new Error('Error getting rendition')));
}
} else {
clearInterval(intervalId);
return reject();
return reject(new Error('Error getting rendition'));
}
}, this.TRY_TIMEOUT);
});
@@ -287,6 +287,7 @@ export class RenditionService {
* These are: images, PDF files, or PDF rendition of files.
* We also force PDF rendition for TEXT type objects, otherwise the default URL is to download.
* TODO there are different TEXT type objects, (HTML, plaintext, xml, etc. we should determine how these are handled)
*
* @param objectId object it
* @param mimeType mime type
*/

View File

@@ -20,22 +20,20 @@ import { AlfrescoApiService, LogService, TranslationService, ViewUtilService } f
import { Rendition, RenditionEntry, RenditionPaging, RenditionsApi } from '@alfresco/js-api';
import { RenditionService } from '@alfresco/adf-content-services';
const getRenditionEntry = (status: Rendition.StatusEnum): RenditionEntry => {
return {
const getRenditionEntry = (status: Rendition.StatusEnum): RenditionEntry => ({
entry: {
id: 'pdf',
status: status,
status,
content: { mimeType: 'application/pdf', mimeTypeName: 'application/pdf', sizeInBytes: 10 }
}
};
};
const getRenditionPaging = (status: Rendition.StatusEnum): RenditionPaging => {
return {
});
const getRenditionPaging = (status: Rendition.StatusEnum): RenditionPaging => ({
list: {
entries: [getRenditionEntry(status)]
}
};
};
});
describe('RenditionService', () => {
let renditionService: RenditionService;
let renditionsApi: any;

View File

@@ -92,7 +92,7 @@ describe('NodeLockDialogComponent', () => {
}));
it('should call onError if submit fails', fakeAsync(() => {
spyOn(component.nodesApi, 'lockNode').and.returnValue(Promise.reject('error'));
spyOn(component.nodesApi, 'lockNode').and.returnValue(Promise.reject(new Error('error')));
spyOn(component.data, 'onError');
component.submit();

View File

@@ -53,39 +53,39 @@ describe('LibraryFavoriteDirective', () => {
});
it('should not check for favorite if no selection exists', () => {
spyOn(component.directive['favoritesApi'], 'getFavoriteSite');
spyOn(component.directive.favoritesApi, 'getFavoriteSite');
fixture.detectChanges();
expect(component.directive['favoritesApi'].getFavoriteSite).not.toHaveBeenCalled();
expect(component.directive.favoritesApi.getFavoriteSite).not.toHaveBeenCalled();
});
it('should mark selection as favorite', async () => {
spyOn(component.directive['favoritesApi'], 'getFavoriteSite').and.returnValue(Promise.resolve(null));
spyOn(component.directive.favoritesApi, 'getFavoriteSite').and.returnValue(Promise.resolve(null));
delete selection.isFavorite;
fixture.detectChanges();
await fixture.whenStable();
expect(component.directive['favoritesApi'].getFavoriteSite).toHaveBeenCalled();
expect(component.directive.favoritesApi.getFavoriteSite).toHaveBeenCalled();
expect(component.directive.isFavorite()).toBe(true);
});
it('should mark selection not favorite', async () => {
spyOn(component.directive['favoritesApi'], 'getFavoriteSite').and.returnValue(Promise.reject());
spyOn(component.directive.favoritesApi, 'getFavoriteSite').and.returnValue(Promise.reject(new Error('error')));
delete selection.isFavorite;
fixture.detectChanges();
await fixture.whenStable();
expect(component.directive['favoritesApi'].getFavoriteSite).toHaveBeenCalled();
expect(component.directive.favoritesApi.getFavoriteSite).toHaveBeenCalled();
expect(component.directive.isFavorite()).toBe(false);
});
it('should call addFavorite() on click event when selection is not a favorite', async () => {
spyOn(component.directive['favoritesApi'], 'getFavoriteSite').and.returnValue(Promise.reject());
spyOn(component.directive['favoritesApi'], 'createFavorite').and.returnValue(Promise.resolve(null));
spyOn(component.directive.favoritesApi, 'getFavoriteSite').and.returnValue(Promise.reject(new Error('error')));
spyOn(component.directive.favoritesApi, 'createFavorite').and.returnValue(Promise.resolve(null));
fixture.detectChanges();
await fixture.whenStable();
@@ -94,12 +94,12 @@ describe('LibraryFavoriteDirective', () => {
fixture.nativeElement.querySelector('button').dispatchEvent(new MouseEvent('click'));
fixture.detectChanges();
expect(component.directive['favoritesApi'].createFavorite).toHaveBeenCalled();
expect(component.directive.favoritesApi.createFavorite).toHaveBeenCalled();
});
it('should call removeFavoriteSite() on click event when selection is favorite', async () => {
spyOn(component.directive['favoritesApi'], 'getFavoriteSite').and.returnValue(Promise.resolve(null));
spyOn(component.directive['favoritesApi'], 'deleteFavorite').and.returnValue(Promise.resolve());
spyOn(component.directive.favoritesApi, 'getFavoriteSite').and.returnValue(Promise.resolve(null));
spyOn(component.directive.favoritesApi, 'deleteFavorite').and.returnValue(Promise.resolve());
selection.isFavorite = true;
@@ -113,6 +113,6 @@ describe('LibraryFavoriteDirective', () => {
fixture.detectChanges();
await fixture.whenStable();
expect(component.directive['favoritesApi'].deleteFavorite).toHaveBeenCalled();
expect(component.directive.favoritesApi.deleteFavorite).toHaveBeenCalled();
});
});

View File

@@ -70,7 +70,7 @@ describe('LibraryMembershipDirective', () => {
describe('markMembershipRequest', () => {
beforeEach(() => {
getMembershipSpy = spyOn(directive['sitesApi'], 'getSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
getMembershipSpy = spyOn(directive.sitesApi, 'getSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
});
it('should not check membership requests if no entry is selected', fakeAsync(() => {
@@ -98,7 +98,7 @@ describe('LibraryMembershipDirective', () => {
}));
it('should remember when a membership request is not found for selected library', fakeAsync(() => {
getMembershipSpy.and.returnValue(Promise.reject());
getMembershipSpy.and.returnValue(Promise.reject(new Error('error')));
const selection = { entry: testSiteEntry };
const change = new SimpleChange(null, selection, true);
@@ -111,9 +111,9 @@ describe('LibraryMembershipDirective', () => {
describe('toggleMembershipRequest', () => {
beforeEach(() => {
mockSupportedVersion = false;
getMembershipSpy = spyOn(directive['sitesApi'], 'getSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
addMembershipSpy = spyOn(directive['sitesApi'], 'createSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
deleteMembershipSpy = spyOn(directive['sitesApi'], 'deleteSiteMembershipRequestForPerson').and.returnValue(Promise.resolve());
getMembershipSpy = spyOn(directive.sitesApi, 'getSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
addMembershipSpy = spyOn(directive.sitesApi, 'createSiteMembershipRequestForPerson').and.returnValue(Promise.resolve({ entry: requestedMembershipResponse }));
deleteMembershipSpy = spyOn(directive.sitesApi, 'deleteSiteMembershipRequestForPerson').and.returnValue(Promise.resolve());
});
it('should do nothing if there is no selected library ', fakeAsync(() => {

View File

@@ -111,10 +111,10 @@ describe('NodeDeleteDirective', () => {
element = fixture.debugElement.query(By.directive(NodeDeleteDirective));
elementWithPermanentDelete = fixtureWithPermanentComponent.debugElement.query(By.directive(NodeDeleteDirective));
deleteNodeSpy = spyOn(component.deleteDirective['nodesApi'], 'deleteNode').and.returnValue(Promise.resolve());
deleteNodeSpy = spyOn(component.deleteDirective.nodesApi, 'deleteNode').and.returnValue(Promise.resolve());
deleteNodePermanentSpy = spyOn(componentWithPermanentDelete.deleteDirective['nodesApi'], 'deleteNode').and.returnValue(Promise.resolve());
purgeDeletedNodePermanentSpy = spyOn(componentWithPermanentDelete.deleteDirective['trashcanApi'], 'deleteDeletedNode').and.returnValue(Promise.resolve());
deleteNodePermanentSpy = spyOn(componentWithPermanentDelete.deleteDirective.nodesApi, 'deleteNode').and.returnValue(Promise.resolve());
purgeDeletedNodePermanentSpy = spyOn(componentWithPermanentDelete.deleteDirective.trashcanApi, 'deleteDeletedNode').and.returnValue(Promise.resolve());
});
@@ -152,7 +152,7 @@ describe('NodeDeleteDirective', () => {
});
it('should notify failed node deletion', async () => {
deleteNodeSpy.and.returnValue(Promise.reject('error'));
deleteNodeSpy.and.returnValue(Promise.reject(new Error('error')));
component.selection = [{ entry: { id: '1', name: 'name1' } }];
fixture.detectChanges();
@@ -187,7 +187,7 @@ describe('NodeDeleteDirective', () => {
});
it('should notify failed nodes deletion', async () => {
deleteNodeSpy.and.returnValue(Promise.reject('error'));
deleteNodeSpy.and.returnValue(Promise.reject(new Error('error')));
component.selection = [
{ entry: { id: '1', name: 'name1' } },
@@ -209,7 +209,7 @@ describe('NodeDeleteDirective', () => {
it('should notify partial deletion when only one node is successful', async () => {
deleteNodeSpy.and.callFake((id) => {
if (id === '1') {
return Promise.reject('error');
return Promise.reject(new Error('error'));
} else {
return Promise.resolve();
}
@@ -235,7 +235,7 @@ describe('NodeDeleteDirective', () => {
it('should notify partial deletion when some nodes are successful', async () => {
deleteNodeSpy.and.callFake((id) => {
if (id === '1') {
return Promise.reject(null);
return Promise.reject(new Error('error'));
}
return Promise.resolve();

View File

@@ -69,7 +69,7 @@ describe('NodeFavoriteDirective', () => {
});
it('should reset favorites if selection is empty', fakeAsync(() => {
spyOn(directive['favoritesApi'], 'getFavorite').and.returnValue(Promise.resolve(null));
spyOn(directive.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve(null));
const selection = [
{ entry: { id: '1', name: 'name1' } }
@@ -90,11 +90,10 @@ describe('NodeFavoriteDirective', () => {
});
describe('markFavoritesNodes()', () => {
let favoritesApiSpy;
let favoritesApiSpy: jasmine.Spy;
beforeEach(() => {
favoritesApiSpy = spyOn(directive['favoritesApi'], 'getFavorite')
.and.returnValue(Promise.resolve(null));
favoritesApiSpy = spyOn(directive.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve(null));
});
it('should check each selected node if it is a favorite', fakeAsync(() => {
@@ -108,7 +107,6 @@ describe('NodeFavoriteDirective', () => {
tick();
expect(favoritesApiSpy.calls.count()).toBe(2);
}));
it('should not check processed node when another is unselected', fakeAsync(() => {
@@ -170,12 +168,12 @@ describe('NodeFavoriteDirective', () => {
});
describe('toggleFavorite()', () => {
let removeFavoriteSpy;
let addFavoriteSpy;
let removeFavoriteSpy: jasmine.Spy;
let addFavoriteSpy: jasmine.Spy;
beforeEach(() => {
removeFavoriteSpy = spyOn(directive['favoritesApi'], 'deleteFavorite').and.callThrough();
addFavoriteSpy = spyOn(directive['favoritesApi'], 'createFavorite').and.callThrough();
removeFavoriteSpy = spyOn(directive.favoritesApi, 'deleteFavorite').and.callThrough();
addFavoriteSpy = spyOn(directive.favoritesApi, 'createFavorite').and.callThrough();
});
afterEach(() => {
@@ -266,7 +264,8 @@ describe('NodeFavoriteDirective', () => {
}));
it('should emit error event when removeFavoriteSite() fails', fakeAsync(() => {
removeFavoriteSpy.and.returnValue(Promise.reject('error'));
const error = new Error('error');
removeFavoriteSpy.and.returnValue(Promise.reject(error));
spyOn(directive.error, 'emit');
directive.favorites = [
@@ -276,11 +275,12 @@ describe('NodeFavoriteDirective', () => {
directive.toggleFavorite();
tick();
expect(directive.error.emit).toHaveBeenCalledWith('error');
expect(directive.error.emit).toHaveBeenCalledWith(error);
}));
it('should emit error event when addFavorite() fails', fakeAsync(() => {
addFavoriteSpy.and.returnValue(Promise.reject('error'));
const error = new Error('error');
addFavoriteSpy.and.returnValue(Promise.reject(error));
spyOn(directive.error, 'emit');
directive.favorites = [
@@ -290,7 +290,7 @@ describe('NodeFavoriteDirective', () => {
directive.toggleFavorite();
tick();
expect(directive.error.emit).toHaveBeenCalledWith('error');
expect(directive.error.emit).toHaveBeenCalledWith(error);
}));
it('should set isFavorites items to false', fakeAsync(() => {
@@ -323,7 +323,7 @@ describe('NodeFavoriteDirective', () => {
describe('getFavorite()', () => {
it('should not hit server when using 6.x api', fakeAsync(() => {
spyOn(directive['favoritesApi'], 'getFavorite').and.callThrough();
spyOn(directive.favoritesApi, 'getFavorite').and.callThrough();
const selection = [
{ entry: { id: '1', name: 'name1', isFavorite: true } }
@@ -334,11 +334,11 @@ describe('NodeFavoriteDirective', () => {
tick();
expect(directive.favorites[0].entry.isFavorite).toBe(true);
expect(directive['favoritesApi'].getFavorite).not.toHaveBeenCalled();
expect(directive.favoritesApi.getFavorite).not.toHaveBeenCalled();
}));
it('should process node as favorite', fakeAsync(() => {
spyOn(directive['favoritesApi'], 'getFavorite').and.returnValue(Promise.resolve(null));
spyOn(directive.favoritesApi, 'getFavorite').and.returnValue(Promise.resolve(null));
const selection = [
{ entry: { id: '1', name: 'name1' } }
@@ -352,7 +352,7 @@ describe('NodeFavoriteDirective', () => {
}));
it('should not process node as favorite', fakeAsync(() => {
spyOn(directive['favoritesApi'], 'getFavorite').and.returnValue(Promise.reject({}));
spyOn(directive.favoritesApi, 'getFavorite').and.returnValue(Promise.reject(new Error('error')));
const selection = [
{ entry: { id: '1', name: 'name1' } }

View File

@@ -1273,10 +1273,10 @@ describe('DocumentList', () => {
});
it('should emit error when fetch trashcan fails', (done) => {
spyOn(customResourcesService.trashcanApi, 'listDeletedNodes').and.returnValue(Promise.reject('error'));
spyOn(customResourcesService.trashcanApi, 'listDeletedNodes').and.returnValue(Promise.reject(new Error('error')));
const disposableError = documentList.error.subscribe((val) => {
expect(val).toBe('error');
const disposableError = documentList.error.subscribe((err) => {
expect(err.message).toBe('error');
disposableError.unsubscribe();
done();
});
@@ -1295,10 +1295,10 @@ describe('DocumentList', () => {
});
it('should emit error when fetch shared links fails', (done) => {
spyOn(customResourcesService.sharedLinksApi, 'listSharedLinks').and.returnValue(Promise.reject('error'));
spyOn(customResourcesService.sharedLinksApi, 'listSharedLinks').and.returnValue(Promise.reject(new Error('error')));
const disposableError = documentList.error.subscribe((val) => {
expect(val).toBe('error');
const disposableError = documentList.error.subscribe((err) => {
expect(err.message).toBe('error');
disposableError.unsubscribe();
done();
});
@@ -1316,10 +1316,10 @@ describe('DocumentList', () => {
});
it('should emit error when fetch sites fails', (done) => {
spyGetSites.and.returnValue(Promise.reject('error'));
spyGetSites.and.returnValue(Promise.reject(new Error('error')));
const disposableError = documentList.error.subscribe((val) => {
expect(val).toBe('error');
const disposableError = documentList.error.subscribe((err) => {
expect(err.message).toBe('error');
disposableError.unsubscribe();
done();
});
@@ -1338,10 +1338,10 @@ describe('DocumentList', () => {
});
it('should emit error when fetch membership sites fails', (done) => {
spyOn(customResourcesService.sitesApi, 'listSiteMembershipsForPerson').and.returnValue(Promise.reject('error'));
spyOn(customResourcesService.sitesApi, 'listSiteMembershipsForPerson').and.returnValue(Promise.reject(new Error('error')));
const disposableError = documentList.error.subscribe((val) => {
expect(val).toBe('error');
const disposableError = documentList.error.subscribe((err) => {
expect(err.message).toBe('error');
disposableError.unsubscribe();
done();
});
@@ -1359,10 +1359,10 @@ describe('DocumentList', () => {
});
it('should emit error when fetch favorites fails', (done) => {
spyFavorite.and.returnValue(Promise.reject('error'));
spyFavorite.and.returnValue(Promise.reject(new Error('error')));
const disposableError = documentList.error.subscribe((val) => {
expect(val).toBe('error');
const disposableError = documentList.error.subscribe((err) => {
expect(err.message).toBe('error');
disposableError.unsubscribe();
done();
});

View File

@@ -97,7 +97,7 @@ export class WebscriptComponent implements OnChanges {
resolve();
}, (error) => {
this.logService.log('Error' + error);
reject();
reject(error);
});
});
}

View File

@@ -469,7 +469,7 @@ describe('LoginComponent', () => {
});
it('should return error with a wrong username', (done) => {
spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject());
spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject(new Error('login error')));
component.error.subscribe(() => {
fixture.detectChanges();
@@ -484,7 +484,7 @@ describe('LoginComponent', () => {
});
it('should return error with a wrong password', (done) => {
spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject());
spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject(new Error('login error')));
component.error.subscribe(() => {
fixture.detectChanges();
@@ -500,7 +500,7 @@ describe('LoginComponent', () => {
});
it('should return error with a wrong username and password', (done) => {
spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject());
spyOn(alfrescoApiService.getInstance(), 'login').and.returnValue(Promise.reject(new Error('login error')));
component.error.subscribe(() => {
fixture.detectChanges();

View File

@@ -99,7 +99,7 @@ describe('ContentCloudNodeSelectorService', () => {
});
it('should return defined alias nodeId if the relative path does not exist', async () => {
getNodeSpy.and.returnValues(Promise.reject('Relative does not exists'), Promise.resolve(aliasNodeResponseBody));
getNodeSpy.and.returnValues(Promise.reject(new Error('Relative does not exists')), Promise.resolve(aliasNodeResponseBody));
const aliasNodeId = await service.getNodeIdFromPath({ alias: 'mock-alias', path: 'mock-relativePath' });
expect(getNodeSpy).toHaveBeenCalledTimes(2);
@@ -114,7 +114,7 @@ describe('ContentCloudNodeSelectorService', () => {
});
it('should return default nodeId if the given folder does not exist', async () => {
getNodeSpy.and.returnValues(Promise.reject('Folder does not exists'), Promise.resolve(aliasNodeResponseBody));
getNodeSpy.and.returnValues(Promise.reject(new Error('Folder does not exists')), Promise.resolve(aliasNodeResponseBody));
const aliasNodeId = await service.getNodeIdFromFolderVariableValue('mock-folder-id', '-my-');
expect(getNodeSpy).toHaveBeenCalledTimes(2);
@@ -136,7 +136,7 @@ describe('ContentCloudNodeSelectorService', () => {
});
it('should show a warning notification if the relative path is invalid/deleted', async () => {
getNodeSpy.and.returnValue(Promise.reject('Relative path does not exists'));
getNodeSpy.and.returnValue(Promise.reject(new Error('Relative path does not exists')));
try {
expect(service.sourceNodeNotFound).toBe(false);
@@ -144,7 +144,7 @@ describe('ContentCloudNodeSelectorService', () => {
await service.getNodeIdFromPath({ alias: 'mock-alias', path: 'mock-relativePath' });
fail('An error should have been thrown');
} catch (error) {
expect(error).toEqual('Relative path does not exists');
expect(error.message).toEqual('Relative path does not exists');
expect(service.sourceNodeNotFound).toBe(true);
}
@@ -155,7 +155,7 @@ describe('ContentCloudNodeSelectorService', () => {
});
it('should show a warning notification if the defined folderVariable value is invalid/deleted', async () => {
getNodeSpy.and.returnValue(Promise.reject('Folder does not exists'));
getNodeSpy.and.returnValue(Promise.reject(new Error('Folder does not exists')));
try {
expect(service.sourceNodeNotFound).toBe(false);
@@ -163,7 +163,7 @@ describe('ContentCloudNodeSelectorService', () => {
await service.getNodeIdFromFolderVariableValue('mock-folder-id', '-my-');
fail('An error should have been thrown');
} catch (error) {
expect(error).toEqual('Folder does not exists');
expect(error.message).toEqual('Folder does not exists');
expect(service.sourceNodeNotFound).toBe(true);
}

View File

@@ -160,9 +160,7 @@ describe('ProcessFiltersComponent', () => {
});
it('should emit an error with a bad response of getProcessFilters', async () => {
const mockErrorFilterPromise = Promise.reject({
error: 'wrong request'
});
const mockErrorFilterPromise = Promise.reject(new Error('wrong request'));
spyOn(processFilterService, 'getProcessFilters').and.returnValue(from(mockErrorFilterPromise));
const appId = '1';
@@ -177,9 +175,7 @@ describe('ProcessFiltersComponent', () => {
});
it('should emit an error with a bad response of getDeployedApplicationsByName', async () => {
const mockErrorFilterPromise = Promise.reject({
error: 'wrong request'
});
const mockErrorFilterPromise = Promise.reject(new Error('wrong request'));
spyOn(appsProcessService, 'getDeployedApplicationsByName').and.returnValue(from(mockErrorFilterPromise));
const appId = 'fake-app';

View File

@@ -47,7 +47,7 @@ describe('Process filter', () => {
let createFilter: jasmine.Spy;
beforeEach(() => {
getFilters = spyOn(service['userFiltersApi'], 'getUserProcessInstanceFilters').and.returnValue(
getFilters = spyOn(service.userFiltersApi, 'getUserProcessInstanceFilters').and.returnValue(
Promise.resolve(fakeProcessFiltersResponse)
);
@@ -70,7 +70,7 @@ describe('Process filter', () => {
});
it('should return the task filter by id', (done) => {
service.getProcessFilterById(333).subscribe((processFilter: FilterProcessRepresentationModel) => {
service.getProcessFilterById(333).subscribe((processFilter) => {
expect(processFilter).toBeDefined();
expect(processFilter.id).toEqual(333);
expect(processFilter.name).toEqual('Running');
@@ -81,7 +81,7 @@ describe('Process filter', () => {
});
it('should return the task filter by name', (done) => {
service.getProcessFilterByName('Running').subscribe((res: FilterProcessRepresentationModel) => {
service.getProcessFilterByName('Running').subscribe((res) => {
expect(res).toBeDefined();
expect(res.id).toEqual(333);
expect(res.name).toEqual('Running');
@@ -211,7 +211,7 @@ describe('Process filter', () => {
describe('add filter', () => {
beforeEach(() => {
createFilter = spyOn(service['userFiltersApi'], 'createUserProcessInstanceFilter').and.callFake(
createFilter = spyOn(service.userFiltersApi, 'createUserProcessInstanceFilter').and.callFake(
(processFilter) => Promise.resolve(processFilter)
);
});
@@ -243,11 +243,11 @@ describe('Process filter', () => {
});
it('should return a default error if no data is returned by the API', (done) => {
createFilter = createFilter.and.returnValue(Promise.reject(null));
createFilter = createFilter.and.returnValue(Promise.reject(new Error('Server error')));
service.addProcessFilter(filter).subscribe(
() => {},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);
@@ -307,8 +307,8 @@ describe('Process filter', () => {
const duplicateRunningObservable = of(duplicateRunningFilter);
spyOn(service, 'getRunningFilterInstance').and.returnValue(runningFilter);
spyOn<any>(service, 'getCompletedFilterInstance').and.returnValue(completedFilter);
spyOn<any>(service, 'getAllFilterInstance').and.returnValue(allFilter);
spyOn(service, 'getCompletedFilterInstance').and.returnValue(completedFilter);
spyOn(service, 'getAllFilterInstance').and.returnValue(allFilter);
spyOn(service, 'addProcessFilter').and.returnValues(
runningObservable,

View File

@@ -17,12 +17,13 @@
import { AlfrescoApiService } from '@alfresco/adf-core';
import { Injectable } from '@angular/core';
import { Observable, from, forkJoin, throwError } from 'rxjs';
import { Observable, from, forkJoin } from 'rxjs';
import { FilterProcessRepresentationModel } from '../models/filter-process.model';
import { map, catchError } from 'rxjs/operators';
import { map } from 'rxjs/operators';
import {
ResultListDataRepresentationUserProcessInstanceFilterRepresentation,
UserFiltersApi
UserFiltersApi,
UserProcessInstanceFilterRepresentation
} from '@alfresco/js-api';
@Injectable({
@@ -57,8 +58,7 @@ export class ProcessFilterService {
}
});
return filters;
}),
catchError((err) => this.handleProcessError(err))
})
);
}
@@ -69,11 +69,10 @@ export class ProcessFilterService {
* @param appId ID of the target app
* @returns Details of the filter
*/
getProcessFilterById(filterId: number, appId?: number): Observable<FilterProcessRepresentationModel> {
getProcessFilterById(filterId: number, appId?: number): Observable<UserProcessInstanceFilterRepresentation> {
return from(this.callApiProcessFilters(appId))
.pipe(
map((response: any) => response.data.find((filter) => filter.id === filterId)),
catchError((err) => this.handleProcessError(err))
map((response) => response.data.find((filter) => filter.id === filterId))
);
}
@@ -84,11 +83,10 @@ export class ProcessFilterService {
* @param appId ID of the target app
* @returns Details of the filter
*/
getProcessFilterByName(filterName: string, appId?: number): Observable<FilterProcessRepresentationModel> {
getProcessFilterByName(filterName: string, appId?: number): Observable<UserProcessInstanceFilterRepresentation> {
return from(this.callApiProcessFilters(appId))
.pipe(
map((response: any) => response.data.find((filter) => filter.name === filterName)),
catchError((err) => this.handleProcessError(err))
map((response) => response.data.find((filter) => filter.name === filterName))
);
}
@@ -130,9 +128,6 @@ export class ProcessFilterService {
});
observer.next(filters);
observer.complete();
},
(err: any) => {
this.handleProcessError(err);
});
});
}
@@ -172,12 +167,8 @@ export class ProcessFilterService {
* @param filter The filter to add
* @returns The filter just added
*/
addProcessFilter(filter: FilterProcessRepresentationModel): Observable<FilterProcessRepresentationModel> {
return from(this.userFiltersApi.createUserProcessInstanceFilter(filter))
.pipe(
map((response: FilterProcessRepresentationModel) => response),
catchError((err) => this.handleProcessError(err))
);
addProcessFilter(filter: FilterProcessRepresentationModel): Observable<UserProcessInstanceFilterRepresentation> {
return from(this.userFiltersApi.createUserProcessInstanceFilter(filter));
}
/**
@@ -194,7 +185,7 @@ export class ProcessFilterService {
}
}
private getCompletedFilterInstance(appId: number, index?: number): FilterProcessRepresentationModel {
getCompletedFilterInstance(appId: number, index?: number): FilterProcessRepresentationModel {
return new FilterProcessRepresentationModel({
name: 'Completed',
appId,
@@ -205,7 +196,7 @@ export class ProcessFilterService {
});
}
private getAllFilterInstance(appId: number, index?: number): FilterProcessRepresentationModel {
getAllFilterInstance(appId: number, index?: number): FilterProcessRepresentationModel {
return new FilterProcessRepresentationModel({
name: 'All',
appId,
@@ -215,8 +206,4 @@ export class ProcessFilterService {
index
});
}
private handleProcessError(error: any) {
return throwError(error || 'Server error');
}
}

View File

@@ -46,7 +46,7 @@ describe('ProcessService', () => {
});
beforeEach(() => {
spyOn(service['processInstancesApi'], 'getProcessInstances')
spyOn(service.processInstancesApi, 'getProcessInstances')
.and
.returnValue(Promise.resolve({ data: [exampleProcess] }));
});
@@ -74,7 +74,7 @@ describe('ProcessService', () => {
const processId = 'test';
beforeEach(() => {
spyOn(service['processInstancesApi'], 'getProcessInstance')
spyOn(service.processInstancesApi, 'getProcessInstance')
.and
.returnValue(Promise.resolve(exampleProcess));
});
@@ -95,7 +95,7 @@ describe('ProcessService', () => {
let startNewProcessInstance: jasmine.Spy;
beforeEach(() => {
startNewProcessInstance = spyOn(service['processInstancesApi'], 'startNewProcessInstance')
startNewProcessInstance = spyOn(service.processInstancesApi, 'startNewProcessInstance')
.and
.returnValue(Promise.resolve(exampleProcess));
});
@@ -145,12 +145,12 @@ describe('ProcessService', () => {
});
it('should return a default error if no data is returned by the API', (done) => {
startNewProcessInstance = startNewProcessInstance.and.returnValue(Promise.reject(null));
startNewProcessInstance = startNewProcessInstance.and.returnValue(Promise.reject(new Error('Server error')));
service.startProcess(processDefId, processName).subscribe(
() => {
},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);
@@ -163,7 +163,7 @@ describe('ProcessService', () => {
let deleteProcessInstance: jasmine.Spy;
beforeEach(() => {
deleteProcessInstance = spyOn(service['processInstancesApi'], 'deleteProcessInstance')
deleteProcessInstance = spyOn(service.processInstancesApi, 'deleteProcessInstance')
.and
.returnValue(Promise.resolve());
});
@@ -191,12 +191,12 @@ describe('ProcessService', () => {
});
it('should return a default error if no data is returned by the API', (done) => {
deleteProcessInstance = deleteProcessInstance.and.returnValue(Promise.reject(null));
deleteProcessInstance = deleteProcessInstance.and.returnValue(Promise.reject(new Error('Server error')));
service.cancelProcess(null).subscribe(
() => {
},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);
@@ -208,7 +208,7 @@ describe('ProcessService', () => {
let getProcessDefinitions: jasmine.Spy;
beforeEach(() => {
getProcessDefinitions = spyOn(service['processDefinitionsApi'], 'getProcessDefinitions')
getProcessDefinitions = spyOn(service.processDefinitionsApi, 'getProcessDefinitions')
.and
.returnValue(Promise.resolve({ data: [fakeProcessDef, fakeProcessDef] }));
});
@@ -251,12 +251,12 @@ describe('ProcessService', () => {
});
it('should return a default error if no data is returned by the API', (done) => {
getProcessDefinitions = getProcessDefinitions.and.returnValue(Promise.reject(null));
getProcessDefinitions = getProcessDefinitions.and.returnValue(Promise.reject(new Error('Server error')));
service.getProcessDefinitions().subscribe(
() => {
},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);
@@ -269,7 +269,7 @@ describe('ProcessService', () => {
let listTasks: jasmine.Spy;
beforeEach(() => {
listTasks = spyOn(service['tasksApi'], 'listTasks')
listTasks = spyOn(service.tasksApi, 'listTasks')
.and
.returnValue(Promise.resolve(fakeTasksList));
});
@@ -325,12 +325,12 @@ describe('ProcessService', () => {
});
it('should return a default error if no data is returned by the API', (done) => {
listTasks = listTasks.and.returnValue(Promise.reject(null));
listTasks = listTasks.and.returnValue(Promise.reject(new Error('Server error')));
service.getProcessTasks(processId).subscribe(
() => {
},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);
@@ -344,7 +344,7 @@ describe('ProcessService', () => {
let deleteProcessInstanceVariableSpy: jasmine.Spy;
beforeEach(() => {
getVariablesSpy = spyOn(service['processInstanceVariablesApi'], 'getProcessInstanceVariables').and.returnValue(Promise.resolve([{
getVariablesSpy = spyOn(service.processInstanceVariablesApi, 'getProcessInstanceVariables').and.returnValue(Promise.resolve([{
name: 'var1',
value: 'Test1'
}, {
@@ -352,10 +352,10 @@ describe('ProcessService', () => {
value: 'Test3'
}]));
createOrUpdateProcessInstanceVariablesSpy = spyOn(service['processInstanceVariablesApi'],
createOrUpdateProcessInstanceVariablesSpy = spyOn(service.processInstanceVariablesApi,
'createOrUpdateProcessInstanceVariables').and.returnValue(Promise.resolve({} as any));
deleteProcessInstanceVariableSpy = spyOn(service['processInstanceVariablesApi'],
deleteProcessInstanceVariableSpy = spyOn(service.processInstanceVariablesApi,
'deleteProcessInstanceVariable').and.returnValue(Promise.resolve());
});
@@ -379,12 +379,12 @@ describe('ProcessService', () => {
});
it('should return a default error if no data is returned by the API', (done) => {
getVariablesSpy = getVariablesSpy.and.returnValue(Promise.reject(null));
getVariablesSpy = getVariablesSpy.and.returnValue(Promise.reject(new Error('Server error')));
service.getProcessInstanceVariables(null).subscribe(
() => {
},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);
@@ -410,20 +410,20 @@ describe('ProcessService', () => {
service.createOrUpdateProcessInstanceVariables('123', updatedVariables).subscribe(
() => {
},
(res) => {
expect(res).toBe(mockError);
(err) => {
expect(err).toBe(mockError);
done();
}
);
});
it('should return a default error if no data is returned by the API', (done) => {
createOrUpdateProcessInstanceVariablesSpy = createOrUpdateProcessInstanceVariablesSpy.and.returnValue(Promise.reject(null));
createOrUpdateProcessInstanceVariablesSpy = createOrUpdateProcessInstanceVariablesSpy.and.returnValue(Promise.reject(new Error('Server error')));
service.createOrUpdateProcessInstanceVariables('123', updatedVariables).subscribe(
() => {
},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);
@@ -444,12 +444,12 @@ describe('ProcessService', () => {
});
it('should return a default error if no data is returned by the API', (done) => {
deleteProcessInstanceVariableSpy = deleteProcessInstanceVariableSpy.and.returnValue(Promise.reject(null));
deleteProcessInstanceVariableSpy = deleteProcessInstanceVariableSpy.and.returnValue(Promise.reject(new Error('Server error')));
service.deleteProcessInstanceVariable('123', 'myVar').subscribe(
() => {
},
(res) => {
expect(res).toBe('Server error');
(err) => {
expect(err.message).toBe('Server error');
done();
}
);