[affected:*][ci:force] - REBASED

This commit is contained in:
Vito Albano 2024-04-02 15:48:51 +01:00
parent 89698db681
commit 882f1476c7
14 changed files with 636 additions and 715 deletions

View File

@ -42,7 +42,7 @@ const emitters: Emitters = {
apiClientEmitter: emitter apiClientEmitter: emitter
}; };
const mockResponse = { const mockResponse = {
data: [ data: [
{ {
id: 14, id: 14,
@ -58,23 +58,19 @@ describe('AdfHttpClient', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [HttpClientTestingModule],
HttpClientTestingModule providers: [AdfHttpClient]
]
}); });
angularHttpClient = TestBed.inject(AdfHttpClient); angularHttpClient = TestBed.inject(AdfHttpClient);
controller = TestBed.inject(HttpTestingController); controller = TestBed.inject(HttpTestingController);
}); });
describe('deserialize', () => { describe('deserialize', () => {
afterEach(() => { afterEach(() => {
controller.verify(); controller.verify();
}); });
it('should deserialize incoming request based on return type', (done) => { it('should deserialize incoming request based on return type', (done) => {
const options: RequestOptions = { const options: RequestOptions = {
path: '', path: '',
httpMethod: 'POST', httpMethod: 'POST',
@ -85,38 +81,41 @@ describe('AdfHttpClient', () => {
accepts: ['application/json'] accepts: ['application/json']
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res: ResultListDataRepresentationTaskRepresentation) => { angularHttpClient
expect(res instanceof ResultListDataRepresentationTaskRepresentation).toBeTruthy(); .request('http://example.com', options, securityOptions, emitters)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion .then((res: ResultListDataRepresentationTaskRepresentation) => {
expect(res.data![0].created instanceof Date).toBeTruthy(); expect(res instanceof ResultListDataRepresentationTaskRepresentation).toBeTruthy();
done(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
}).catch(error=> fail(error)); expect(res.data![0].created instanceof Date).toBeTruthy();
done();
})
.catch((error) => fail(error));
const req = controller.expectOne('http://example.com'); const req = controller.expectOne('http://example.com');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
req.flush(mockResponse); req.flush(mockResponse);
}); });
it('should return parsed json object when responseType is json', (done) => { it('should return parsed json object when responseType is json', (done) => {
const options: RequestOptions = { const options: RequestOptions = {
path: '', path: '',
httpMethod: 'POST', httpMethod: 'POST',
responseType: 'json' responseType: 'json'
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => { angularHttpClient
expect(res).toEqual(mockResponse); .request('http://example.com', options, securityOptions, emitters)
done(); .then((res) => {
}).catch(error=> fail(error)); expect(res).toEqual(mockResponse);
done();
})
.catch((error) => fail(error));
const req = controller.expectOne('http://example.com'); const req = controller.expectOne('http://example.com');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
req.flush(mockResponse); req.flush(mockResponse);
}); });
it('should emit unauthorized message for 401 request', (done) => { it('should emit unauthorized message for 401 request', (done) => {
@ -135,13 +134,11 @@ describe('AdfHttpClient', () => {
const req = controller.expectOne('http://example.com'); const req = controller.expectOne('http://example.com');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
req.flush('<div></div>', { status: 401, statusText: 'unauthorized'}); req.flush('<div></div>', { status: 401, statusText: 'unauthorized' });
}); });
}); });
describe('upload', () => { describe('upload', () => {
afterEach(() => { afterEach(() => {
controller.verify(); controller.verify();
}); });
@ -177,9 +174,7 @@ describe('AdfHttpClient', () => {
returnType: null returnType: null
}; };
angularHttpClient.request('http://example.com', requestOptions, securityOptions, emitters).catch(error => angularHttpClient.request('http://example.com', requestOptions, securityOptions, emitters).catch((error) => fail(error));
fail(error)
);
const req = controller.expectOne('http://example.com?autoRename=true&include=allowableOperations'); const req = controller.expectOne('http://example.com?autoRename=true&include=allowableOperations');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
@ -251,19 +246,18 @@ describe('AdfHttpClient', () => {
httpMethod: 'POST', httpMethod: 'POST',
queryParams: { queryParams: {
skipCount: 0, skipCount: 0,
status: [ status: ['RUNNING', 'SUSPENDED'],
'RUNNING',
'SUSPENDED'
],
sort: 'startDate,DESC' sort: 'startDate,DESC'
} }
}; };
angularHttpClient.request('http://example.com/candidatebaseapp/query/v1/process-instances', options, securityOptions, emitters).catch(error => angularHttpClient
fail(error) .request('http://example.com/candidatebaseapp/query/v1/process-instances', options, securityOptions, emitters)
); .catch((error) => fail(error));
const req = controller.expectOne('http://example.com/candidatebaseapp/query/v1/process-instances?skipCount=0&status=RUNNING&status=SUSPENDED&sort=startDate%2CDESC'); const req = controller.expectOne(
'http://example.com/candidatebaseapp/query/v1/process-instances?skipCount=0&status=RUNNING&status=SUSPENDED&sort=startDate%2CDESC'
);
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
req.flush(null, { status: 200, statusText: 'Ok' }); req.flush(null, { status: 200, statusText: 'Ok' });
@ -275,10 +269,13 @@ describe('AdfHttpClient', () => {
httpMethod: 'GET' httpMethod: 'GET'
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => { angularHttpClient
expect(res).toEqual(''); .request('http://example.com', options, securityOptions, emitters)
done(); .then((res) => {
}).catch(error=> fail(error)); expect(res).toEqual('');
done();
})
.catch((error) => fail(error));
const req = controller.expectOne('http://example.com'); const req = controller.expectOne('http://example.com');
@ -294,9 +291,7 @@ describe('AdfHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error => angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((error) => fail(error));
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000%2B02%3A00'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000%2B02%3A00');
@ -312,9 +307,7 @@ describe('AdfHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error => angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((error) => fail(error));
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z');
@ -331,9 +324,7 @@ describe('AdfHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error => angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((error) => fail(error));
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z');
@ -352,9 +343,7 @@ describe('AdfHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error => angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((error) => fail(error));
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z');
@ -372,9 +361,7 @@ describe('AdfHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error => angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((error) => fail(error));
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z');
@ -392,9 +379,7 @@ describe('AdfHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error => angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((error) => fail(error));
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z');
@ -402,5 +387,4 @@ describe('AdfHttpClient', () => {
req.flush(null, { status: 200, statusText: 'Ok' }); req.flush(null, { status: 200, statusText: 'Ok' });
}); });
}); });

View File

@ -16,10 +16,10 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { AboutGithubLinkComponent } from './about-github-link.component'; import { AboutGithubLinkComponent } from './about-github-link.component';
import { aboutGithubDetails } from '../about.mock'; import { aboutGithubDetails } from '../about.mock';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { MatCardModule } from '@angular/material/card';
describe('AboutGithubLinkComponent', () => { describe('AboutGithubLinkComponent', () => {
let fixture: ComponentFixture<AboutGithubLinkComponent>; let fixture: ComponentFixture<AboutGithubLinkComponent>;
@ -27,7 +27,7 @@ describe('AboutGithubLinkComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [TranslateModule.forRoot(), MatCardModule]
}); });
fixture = TestBed.createComponent(AboutGithubLinkComponent); fixture = TestBed.createComponent(AboutGithubLinkComponent);
component = fixture.componentInstance; component = fixture.componentInstance;

View File

@ -16,11 +16,12 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { AboutServerSettingsComponent } from './about-server-settings.component'; import { AboutServerSettingsComponent } from './about-server-settings.component';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.service';
import { aboutGithubDetails } from '../about.mock'; import { aboutGithubDetails } from '../about.mock';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { AppConfigServiceMock } from '../../common';
describe('AboutServerSettingsComponent', () => { describe('AboutServerSettingsComponent', () => {
let fixture: ComponentFixture<AboutServerSettingsComponent>; let fixture: ComponentFixture<AboutServerSettingsComponent>;
@ -29,10 +30,8 @@ describe('AboutServerSettingsComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule],
TranslateModule.forRoot(), providers: [{ provide: AppConfigService, useClass: AppConfigServiceMock }]
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(AboutServerSettingsComponent); fixture = TestBed.createComponent(AboutServerSettingsComponent);
component = fixture.componentInstance; component = fixture.componentInstance;

View File

@ -20,14 +20,15 @@ import { AppConfigService } from '../../app-config/app-config.service';
import { AuthGuardBpm } from './auth-guard-bpm.service'; import { AuthGuardBpm } from './auth-guard-bpm.service';
import { AuthenticationService } from '../services/authentication.service'; import { AuthenticationService } from '../services/authentication.service';
import { RouterStateSnapshot, Router } from '@angular/router'; import { RouterStateSnapshot, Router } from '@angular/router';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatDialog } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
import { OidcAuthenticationService } from '../services/oidc-authentication.service'; import { OidcAuthenticationService } from '../services/oidc-authentication.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RedirectAuthService } from '../oidc/redirect-auth.service';
import { EMPTY } from 'rxjs';
describe('AuthGuardService BPM', () => { describe('AuthGuardService BPM', () => {
let authGuard: AuthGuardBpm; let authGuard: AuthGuardBpm;
let authService: AuthenticationService; let authService: AuthenticationService;
let basicAlfrescoAuthService: BasicAlfrescoAuthService; let basicAlfrescoAuthService: BasicAlfrescoAuthService;
@ -38,14 +39,13 @@ describe('AuthGuardService BPM', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule, MatDialogModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
{ provide: RedirectAuthService, useValue: { onLogin: EMPTY } },
{ {
provide: OidcAuthenticationService, useValue: { provide: OidcAuthenticationService,
ssoLogin: () => { }, useValue: {
ssoLogin: () => {},
isPublicUrl: () => false, isPublicUrl: () => false,
hasValidIdToken: () => false, hasValidIdToken: () => false,
isLoggedIn: () => false isLoggedIn: () => false
@ -154,7 +154,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url' provider: 'BPM',
url: 'some-url'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url');
}); });
@ -167,7 +168,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url;q=123' provider: 'BPM',
url: 'some-url;q=123'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123');
}); });
@ -180,7 +182,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: '/' provider: 'BPM',
url: '/'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('/'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('/');
}); });
@ -194,7 +197,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url' provider: 'BPM',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url'));
}); });
@ -211,7 +215,8 @@ describe('AuthGuardService BPM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'BPM', url: 'some-url' provider: 'BPM',
url: 'some-url'
}); });
expect(materialDialog.closeAll).toHaveBeenCalled(); expect(materialDialog.closeAll).toHaveBeenCalled();

View File

@ -20,14 +20,16 @@ import { AppConfigService } from '../../app-config/app-config.service';
import { AuthGuardEcm } from './auth-guard-ecm.service'; import { AuthGuardEcm } from './auth-guard-ecm.service';
import { AuthenticationService } from '../services/authentication.service'; import { AuthenticationService } from '../services/authentication.service';
import { RouterStateSnapshot, Router } from '@angular/router'; import { RouterStateSnapshot, Router } from '@angular/router';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatDialog } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { OidcAuthenticationService } from '../services/oidc-authentication.service'; import { OidcAuthenticationService } from '../services/oidc-authentication.service';
import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { RedirectAuthService } from '../oidc/redirect-auth.service';
import { EMPTY } from 'rxjs';
describe('AuthGuardService ECM', () => { describe('AuthGuardService ECM', () => {
let authGuard: AuthGuardEcm; let authGuard: AuthGuardEcm;
let authService: AuthenticationService; let authService: AuthenticationService;
let basicAlfrescoAuthService: BasicAlfrescoAuthService; let basicAlfrescoAuthService: BasicAlfrescoAuthService;
@ -37,19 +39,20 @@ describe('AuthGuardService ECM', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule, RouterTestingModule, MatDialogModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
BasicAlfrescoAuthService,
AppConfigService,
{ {
provide: OidcAuthenticationService, useValue: { provide: OidcAuthenticationService,
ssoLogin: () => { }, useValue: {
ssoLogin: () => {},
isPublicUrl: () => false, isPublicUrl: () => false,
hasValidIdToken: () => false, hasValidIdToken: () => false,
isLoggedIn: () => false isLoggedIn: () => false
} }
} },
{ provide: RedirectAuthService, useValue: { onLogin: EMPTY } }
] ]
}); });
localStorage.clear(); localStorage.clear();
@ -67,7 +70,7 @@ describe('AuthGuardService ECM', () => {
it('if the alfresco js api is logged in should canActivate be true', async () => { it('if the alfresco js api is logged in should canActivate be true', async () => {
spyOn(authService, 'isEcmLoggedIn').and.returnValue(true); spyOn(authService, 'isEcmLoggedIn').and.returnValue(true);
const route = {url : 'some-url'} as RouterStateSnapshot; const route = { url: 'some-url' } as RouterStateSnapshot;
expect(await authGuard.canActivate(null, route)).toBeTruthy(); expect(await authGuard.canActivate(null, route)).toBeTruthy();
}); });
@ -76,7 +79,7 @@ describe('AuthGuardService ECM', () => {
spyOn(authService, 'isBpmLoggedIn').and.returnValue(true); spyOn(authService, 'isBpmLoggedIn').and.returnValue(true);
appConfigService.config.auth.withCredentials = true; appConfigService.config.auth.withCredentials = true;
const route = {url : 'some-url'} as RouterStateSnapshot; const route = { url: 'some-url' } as RouterStateSnapshot;
expect(await authGuard.canActivate(null, route)).toBeTruthy(); expect(await authGuard.canActivate(null, route)).toBeTruthy();
}); });
@ -94,7 +97,7 @@ describe('AuthGuardService ECM', () => {
spyOn(router, 'navigateByUrl'); spyOn(router, 'navigateByUrl');
spyOn(authService, 'isEcmLoggedIn').and.returnValue(false); spyOn(authService, 'isEcmLoggedIn').and.returnValue(false);
const route = {url : 'some-url'} as RouterStateSnapshot; const route = { url: 'some-url' } as RouterStateSnapshot;
expect(await authGuard.canActivate(null, route)).toBeFalsy(); expect(await authGuard.canActivate(null, route)).toBeFalsy();
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url'));
@ -105,7 +108,7 @@ describe('AuthGuardService ECM', () => {
spyOn(authService, 'isEcmLoggedIn').and.returnValue(false); spyOn(authService, 'isEcmLoggedIn').and.returnValue(false);
spyOn(authService, 'isOauth').and.returnValue(true); spyOn(authService, 'isOauth').and.returnValue(true);
appConfigService.config.oauth2.silentLogin = false; appConfigService.config.oauth2.silentLogin = false;
const route = {url : 'some-url'} as RouterStateSnapshot; const route = { url: 'some-url' } as RouterStateSnapshot;
expect(await authGuard.canActivate(null, route)).toBeFalsy(); expect(await authGuard.canActivate(null, route)).toBeFalsy();
expect(router.navigateByUrl).toHaveBeenCalled(); expect(router.navigateByUrl).toHaveBeenCalled();
@ -126,7 +129,7 @@ describe('AuthGuardService ECM', () => {
scope: 'openid' scope: 'openid'
}; };
const route = {url : 'abc'} as RouterStateSnapshot; const route = { url: 'abc' } as RouterStateSnapshot;
expect(await authGuard.canActivate(null, route)).toBeFalsy(); expect(await authGuard.canActivate(null, route)).toBeFalsy();
expect(oidcAuthenticationService.ssoLogin).toHaveBeenCalledTimes(1); expect(oidcAuthenticationService.ssoLogin).toHaveBeenCalledTimes(1);
@ -137,7 +140,7 @@ describe('AuthGuardService ECM', () => {
spyOn(authService, 'isEcmLoggedIn').and.returnValue(false); spyOn(authService, 'isEcmLoggedIn').and.returnValue(false);
spyOn(authService, 'isOauth').and.returnValue(true); spyOn(authService, 'isOauth').and.returnValue(true);
appConfigService.config.oauth2.silentLogin = undefined; appConfigService.config.oauth2.silentLogin = undefined;
const route = {url : 'some-url'} as RouterStateSnapshot; const route = { url: 'some-url' } as RouterStateSnapshot;
expect(await authGuard.canActivate(null, route)).toBeFalsy(); expect(await authGuard.canActivate(null, route)).toBeFalsy();
expect(router.navigateByUrl).toHaveBeenCalled(); expect(router.navigateByUrl).toHaveBeenCalled();
@ -151,7 +154,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url' provider: 'ECM',
url: 'some-url'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url');
}); });
@ -164,7 +168,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url;q=123' provider: 'ECM',
url: 'some-url;q=123'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('some-url;q=123');
}); });
@ -177,7 +182,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: '/' provider: 'ECM',
url: '/'
}); });
expect(basicAlfrescoAuthService.getRedirect()).toEqual('/'); expect(basicAlfrescoAuthService.getRedirect()).toEqual('/');
}); });
@ -191,7 +197,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url' provider: 'ECM',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url'));
}); });
@ -208,7 +215,8 @@ describe('AuthGuardService ECM', () => {
authGuard.canActivate(null, route); authGuard.canActivate(null, route);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ECM', url: 'some-url' provider: 'ECM',
url: 'some-url'
}); });
expect(materialDialog.closeAll).toHaveBeenCalled(); expect(materialDialog.closeAll).toHaveBeenCalled();

View File

@ -17,24 +17,20 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { AuthGuardSsoRoleService } from './auth-guard-sso-role.service'; import { AuthGuardSsoRoleService } from './auth-guard-sso-role.service';
import { JwtHelperService } from '../services/jwt-helper.service'; import { JwtHelperService } from '../services/jwt-helper.service';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('Auth Guard SSO role service', () => { describe('Auth Guard SSO role service', () => {
let authGuard: AuthGuardSsoRoleService; let authGuard: AuthGuardSsoRoleService;
let jwtHelperService: JwtHelperService; let jwtHelperService: JwtHelperService;
let routerService: Router; let routerService: Router;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule, MatDialogModule]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
localStorage.clear(); localStorage.clear();
authGuard = TestBed.inject(AuthGuardSsoRoleService); authGuard = TestBed.inject(AuthGuardSsoRoleService);
@ -192,6 +188,5 @@ describe('Auth Guard SSO role service', () => {
router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'], excludedRoles: ['MOCK_ROOT_USER_ROLE'] }; router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'], excludedRoles: ['MOCK_ROOT_USER_ROLE'] };
expect(authGuard.canActivate(router)).toBeTruthy(); expect(authGuard.canActivate(router)).toBeTruthy();
}); });
}); });
}); });

View File

@ -20,11 +20,15 @@ import { Router, RouterStateSnapshot } from '@angular/router';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.service';
import { AuthGuard } from './auth-guard.service'; import { AuthGuard } from './auth-guard.service';
import { AuthenticationService } from '../services/authentication.service'; import { AuthenticationService } from '../services/authentication.service';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
import { OidcAuthenticationService } from '../services/oidc-authentication.service'; import { OidcAuthenticationService } from '../services/oidc-authentication.service';
import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
import { RedirectAuthService } from '../oidc/redirect-auth.service';
import { EMPTY } from 'rxjs';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { MatDialogModule } from '@angular/material/dialog';
import { RouterTestingModule } from '@angular/router/testing';
describe('AuthGuardService', () => { describe('AuthGuardService', () => {
let state; let state;
@ -38,14 +42,15 @@ describe('AuthGuardService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule, MatDialogModule, RouterTestingModule],
TranslateModule.forRoot(),
CoreTestingModule
],
providers: [ providers: [
AppConfigService,
StorageService,
{ provide: RedirectAuthService, useValue: { onLogin: EMPTY } },
{ {
provide: OidcAuthenticationService, useValue: { provide: OidcAuthenticationService,
ssoLogin: () => { }, useValue: {
ssoLogin: () => {},
isPublicUrl: () => false, isPublicUrl: () => false,
hasValidIdToken: () => false hasValidIdToken: () => false
} }
@ -144,7 +149,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: 'some-url' provider: 'ALL',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url'));
}); });
@ -160,7 +166,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: 'some-url;q=query' provider: 'ALL',
url: 'some-url;q=query'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url;q=query')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/login?redirectUrl=some-url;q=query'));
}); });
@ -175,7 +182,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: 'some-url' provider: 'ALL',
url: 'some-url'
}); });
expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url')); expect(router.navigateByUrl).toHaveBeenCalledWith(router.parseUrl('/fakeLoginRoute?redirectUrl=some-url'));
}); });
@ -189,7 +197,8 @@ describe('AuthGuardService', () => {
await authGuard.canActivate(null, state); await authGuard.canActivate(null, state);
expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({ expect(basicAlfrescoAuthService.setRedirect).toHaveBeenCalledWith({
provider: 'ALL', url: '/' provider: 'ALL',
url: '/'
}); });
}); });
}); });

View File

@ -27,9 +27,9 @@ import {
mockIdentityGroups, mockIdentityGroups,
roleMappingMock roleMappingMock
} from '../mock/identity-group.mock'; } from '../mock/identity-group.mock';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '../../../../api/src'; import { AdfHttpClient } from '../../../../api/src';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('IdentityGroupService', () => { describe('IdentityGroupService', () => {
let service: IdentityGroupService; let service: IdentityGroupService;
@ -38,10 +38,8 @@ describe('IdentityGroupService', () => {
beforeEach(fakeAsync(() => { beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule],
TranslateModule.forRoot(), providers: [AdfHttpClient]
CoreTestingModule
]
}); });
service = TestBed.inject(IdentityGroupService); service = TestBed.inject(IdentityGroupService);
adfHttpClient = TestBed.inject(AdfHttpClient); adfHttpClient = TestBed.inject(AdfHttpClient);
@ -50,7 +48,7 @@ describe('IdentityGroupService', () => {
it('should be able to fetch groups based on group name', (done) => { it('should be able to fetch groups based on group name', (done) => {
requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups)); requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.findGroupsByName({name: 'mock'}).subscribe((res) => { service.findGroupsByName({ name: 'mock' }).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
expect(res.length).toBe(5); expect(res.length).toBe(5);
@ -84,142 +82,126 @@ describe('IdentityGroupService', () => {
it('should able to fetch group roles by groupId', (done) => { it('should able to fetch group roles by groupId', (done) => {
spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles)); spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles));
service.getGroupRoles('mock-group-id').subscribe( service.getGroupRoles('mock-group-id').subscribe((res: any) => {
(res: any) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res.length).toEqual(3);
expect(res.length).toEqual(3); expect(res[0].name).toEqual('MOCK-ADMIN-ROLE');
expect(res[0].name).toEqual('MOCK-ADMIN-ROLE'); expect(res[1].name).toEqual('MOCK-USER-ROLE');
expect(res[1].name).toEqual('MOCK-USER-ROLE'); expect(res[2].name).toEqual('MOCK-ROLE-1');
expect(res[2].name).toEqual('MOCK-ROLE-1'); done();
done(); });
}
);
}); });
it('Should not able to fetch group roles if error occurred', (done) => { it('Should not able to fetch group roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getGroupRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getGroupRoles').and.returnValue(throwError(errorResponse));
service.getGroupRoles('mock-group-id') service.getGroupRoles('mock-group-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not group roles');
fail('expected an error, not group roles'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should return true if group has given role', (done) => { it('should return true if group has given role', (done) => {
spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles)); spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles));
service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-ROLE']).subscribe( service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-ROLE']).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeTruthy();
expect(res).toBeTruthy(); done();
done(); });
}
);
}); });
it('should return false if group does not have given role', (done) => { it('should return false if group does not have given role', (done) => {
spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles)); spyOn(service, 'getGroupRoles').and.returnValue(of(mockIdentityRoles));
service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-MODELER']).subscribe( service.checkGroupHasRole('mock-group-id', ['MOCK-ADMIN-MODELER']).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeFalsy();
expect(res).toBeFalsy(); done();
done(); });
}
);
}); });
it('should fetch client roles by groupId and clientId', (done) => { it('should fetch client roles by groupId and clientId', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles));
service.getClientRoles('mock-group-id', 'mock-client-id').subscribe( service.getClientRoles('mock-group-id', 'mock-client-id').subscribe((res: any) => {
(res: any) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res.length).toEqual(2);
expect(res.length).toEqual(2); expect(res).toEqual(clientRoles);
expect(res).toEqual(clientRoles); done();
done(); });
}
);
}); });
it('Should not fetch client roles if error occurred', (done) => { it('Should not fetch client roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getClientRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getClientRoles').and.returnValue(throwError(errorResponse));
service.getClientRoles('mock-group-id', 'mock-client-id') service.getClientRoles('mock-group-id', 'mock-client-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not client roles');
fail('expected an error, not client roles'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should return true if group has client access', (done) => { it('should return true if group has client access', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(clientRoles));
service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe( service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeTruthy();
expect(res).toBeTruthy(); done();
done(); });
}
);
}); });
it('should return false if group does not have client access', (done) => { it('should return false if group does not have client access', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe( service.checkGroupHasClientApp('mock-group-id', 'mock-client-id').subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeFalsy();
expect(res).toBeFalsy(); done();
done(); });
}
);
}); });
it('should return true if group has any client role', (done) => { it('should return true if group has any client role', (done) => {
spyOn(service, 'checkGroupHasAnyClientAppRole').and.returnValue(of(true)); spyOn(service, 'checkGroupHasAnyClientAppRole').and.returnValue(of(true));
service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-USER-ROLE']).subscribe( service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-USER-ROLE']).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeTruthy();
expect(res).toBeTruthy(); done();
done(); });
}
);
}); });
it('should return false if group does not have any client role', (done) => { it('should return false if group does not have any client role', (done) => {
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-ADMIN-MODELER']).subscribe( service.checkGroupHasAnyClientAppRole('mock-group-id', 'mock-client-id', ['MOCK-ADMIN-MODELER']).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeFalsy();
expect(res).toBeFalsy(); done();
done(); });
}
);
}); });
it('should be able to fetch the client id', (done) => { it('should be able to fetch the client id', (done) => {
requestSpy.and.returnValue(Promise.resolve([{id: 'mock-app-id', name: 'mock-app-name'}])); requestSpy.and.returnValue(Promise.resolve([{ id: 'mock-app-id', name: 'mock-app-name' }]));
service.getClientIdByApplicationName('mock-app-name').subscribe((clientId) => { service.getClientIdByApplicationName('mock-app-name').subscribe((clientId) => {
expect(clientId).toBeDefined(); expect(clientId).toBeDefined();
expect(clientId).not.toBeNull(); expect(clientId).not.toBeNull();
@ -245,29 +227,29 @@ describe('IdentityGroupService', () => {
it('Should not able to fetch all group if error occurred', (done) => { it('Should not able to fetch all group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getGroups').and.returnValue(throwError(errorResponse)); spyOn(service, 'getGroups').and.returnValue(throwError(errorResponse));
service.getGroups() service.getGroups().subscribe(
.subscribe( () => {
() => { fail('expected an error, not groups');
fail('expected an error, not groups'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to query groups based on first & max params', (done) => { it('should be able to query groups based on first & max params', (done) => {
spyOn(service, 'getTotalGroupsCount').and.returnValue(of(mockIdentityGroupsCount)); spyOn(service, 'getTotalGroupsCount').and.returnValue(of(mockIdentityGroupsCount));
requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups)); requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.queryGroups({first: 0, max: 5}).subscribe((res) => { service.queryGroups({ first: 0, max: 5 }).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
expect(res.entries.length).toBe(5); expect(res.entries.length).toBe(5);
@ -287,23 +269,23 @@ describe('IdentityGroupService', () => {
it('Should not able to query groups if error occurred', (done) => { it('Should not able to query groups if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'queryGroups').and.returnValue(throwError(errorResponse)); spyOn(service, 'queryGroups').and.returnValue(throwError(errorResponse));
service.queryGroups({first: 0, max: 5}) service.queryGroups({ first: 0, max: 5 }).subscribe(
.subscribe( () => {
() => { fail('expected an error, not query groups');
fail('expected an error, not query groups'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to create group', (done) => { it('should be able to create group', (done) => {
@ -317,23 +299,23 @@ describe('IdentityGroupService', () => {
it('Should not able to create group if error occurred', (done) => { it('Should not able to create group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'createGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'createGroup').and.returnValue(throwError(errorResponse));
service.createGroup(mockIdentityGroup1) service.createGroup(mockIdentityGroup1).subscribe(
.subscribe( () => {
() => { fail('expected an error, not to create group');
fail('expected an error, not to create group'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to update group', (done) => { it('should be able to update group', (done) => {
@ -347,23 +329,23 @@ describe('IdentityGroupService', () => {
it('Should not able to update group if error occurred', (done) => { it('Should not able to update group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'updateGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'updateGroup').and.returnValue(throwError(errorResponse));
service.updateGroup('mock-group-id', mockIdentityGroup1) service.updateGroup('mock-group-id', mockIdentityGroup1).subscribe(
.subscribe( () => {
() => { fail('expected an error, not to update group');
fail('expected an error, not to update group'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to delete group', (done) => { it('should be able to delete group', (done) => {
@ -377,22 +359,22 @@ describe('IdentityGroupService', () => {
it('Should not able to delete group if error occurred', (done) => { it('Should not able to delete group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'deleteGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'deleteGroup').and.returnValue(throwError(errorResponse));
service.deleteGroup('mock-group-id') service.deleteGroup('mock-group-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not to delete group');
fail('expected an error, not to delete group'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
}); });

View File

@ -32,19 +32,18 @@ import { IdentityUserService } from './identity-user.service';
import { JwtHelperService } from './jwt-helper.service'; import { JwtHelperService } from './jwt-helper.service';
import { mockToken } from '../mock/jwt-helper.service.spec'; import { mockToken } from '../mock/jwt-helper.service.spec';
import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityRoleModel } from '../models/identity-role.model';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '../../../../api/src'; import { AdfHttpClient } from '../../../../api/src';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('IdentityUserService', () => { describe('IdentityUserService', () => {
const mockRoles = [ const mockRoles = [
{ id: 'id-1', name: 'MOCK-ADMIN-ROLE'}, { id: 'id-1', name: 'MOCK-ADMIN-ROLE' },
{ id: 'id-2', name: 'MOCK-USER-ROLE'}, { id: 'id-2', name: 'MOCK-USER-ROLE' },
{ id: 'id-3', name: 'MOCK_MODELER-ROLE' }, { id: 'id-3', name: 'MOCK_MODELER-ROLE' },
{ id: 'id-4', name: 'MOCK-ROLE-1' }, { id: 'id-4', name: 'MOCK-ROLE-1' },
{ id: 'id-5', name: 'MOCK-ROLE-2'} { id: 'id-5', name: 'MOCK-ROLE-2' }
]; ];
let storageService: StorageService; let storageService: StorageService;
@ -54,10 +53,8 @@ describe('IdentityUserService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule],
TranslateModule.forRoot(), providers: [StorageService, AdfHttpClient]
CoreTestingModule
]
}); });
storageService = TestBed.inject(StorageService); storageService = TestBed.inject(StorageService);
service = TestBed.inject(IdentityUserService); service = TestBed.inject(IdentityUserService);
@ -87,111 +84,103 @@ describe('IdentityUserService', () => {
it('should fetch users ', (done) => { it('should fetch users ', (done) => {
spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers)); spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers));
service.getUsers().subscribe( service.getUsers().subscribe((res) => {
res => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res[0].id).toEqual('mock-user-id-1');
expect(res[0].id).toEqual('mock-user-id-1'); expect(res[0].username).toEqual('userName1');
expect(res[0].username).toEqual('userName1'); expect(res[1].id).toEqual('mock-user-id-2');
expect(res[1].id).toEqual('mock-user-id-2'); expect(res[1].username).toEqual('userName2');
expect(res[1].username).toEqual('userName2'); expect(res[2].id).toEqual('mock-user-id-3');
expect(res[2].id).toEqual('mock-user-id-3'); expect(res[2].username).toEqual('userName3');
expect(res[2].username).toEqual('userName3'); done();
done(); });
}
);
}); });
it('Should not fetch users if error occurred', (done) => { it('Should not fetch users if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse)); spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse));
service.getUsers() service.getUsers().subscribe(
.subscribe( () => {
() => { fail('expected an error, not users');
fail('expected an error, not users'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error');
done();
}
);
});
it('should fetch roles by userId', (done) => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.getUserRoles('mock-user-id').subscribe(
(res: IdentityRoleModel[]) => {
expect(res).toBeDefined();
expect(res[0].name).toEqual('MOCK-ADMIN-ROLE');
expect(res[1].name).toEqual('MOCK-USER-ROLE');
expect(res[4].name).toEqual('MOCK-ROLE-2');
done(); done();
} }
); );
}); });
it('should fetch roles by userId', (done) => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.getUserRoles('mock-user-id').subscribe((res: IdentityRoleModel[]) => {
expect(res).toBeDefined();
expect(res[0].name).toEqual('MOCK-ADMIN-ROLE');
expect(res[1].name).toEqual('MOCK-USER-ROLE');
expect(res[4].name).toEqual('MOCK-ROLE-2');
done();
});
});
it('Should not fetch roles if error occurred', (done) => { it('Should not fetch roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getUserRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getUserRoles').and.returnValue(throwError(errorResponse));
service.getUserRoles('mock-user-id') service.getUserRoles('mock-user-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not users');
fail('expected an error, not users'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should fetch users by roles', (done) => { it('should fetch users by roles', (done) => {
spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers)); spyOn(service, 'getUsers').and.returnValue(of(mockIdentityUsers));
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.getUsersByRolesWithCurrentUser([mockRoles[0].name]).then( service.getUsersByRolesWithCurrentUser([mockRoles[0].name]).then((res) => {
res => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res[0].id).toEqual('mock-user-id-1');
expect(res[0].id).toEqual('mock-user-id-1'); expect(res[0].username).toEqual('userName1');
expect(res[0].username).toEqual('userName1'); expect(res[1].id).toEqual('mock-user-id-2');
expect(res[1].id).toEqual('mock-user-id-2'); expect(res[1].username).toEqual('userName2');
expect(res[1].username).toEqual('userName2'); expect(res[2].id).toEqual('mock-user-id-3');
expect(res[2].id).toEqual('mock-user-id-3'); expect(res[2].username).toEqual('userName3');
expect(res[2].username).toEqual('userName3'); done();
done(); });
}
);
}); });
it('Should not fetch users by roles if error occurred', (done) => { it('Should not fetch users by roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse)); spyOn(service, 'getUsers').and.returnValue(throwError(errorResponse));
service.getUsersByRolesWithCurrentUser([mockRoles[0].name]) service.getUsersByRolesWithCurrentUser([mockRoles[0].name]).catch((error) => {
.catch( expect(error.status).toEqual(404);
(error) => { expect(error.statusText).toEqual('Not Found');
expect(error.status).toEqual(404); expect(error.error).toEqual('Mock Error');
expect(error.statusText).toEqual('Not Found'); done();
expect(error.error).toEqual('Mock Error'); });
done();
}
);
}); });
it('should fetch users by roles without current user', (done) => { it('should fetch users by roles without current user', (done) => {
@ -199,91 +188,77 @@ describe('IdentityUserService', () => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
spyOn(service, 'getCurrentUserInfo').and.returnValue(mockIdentityUsers[0]); spyOn(service, 'getCurrentUserInfo').and.returnValue(mockIdentityUsers[0]);
service.getUsersByRolesWithoutCurrentUser([mockRoles[0].name]).then( service.getUsersByRolesWithoutCurrentUser([mockRoles[0].name]).then((res) => {
res => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res[0].id).toEqual('mock-user-id-2');
expect(res[0].id).toEqual('mock-user-id-2'); expect(res[0].username).toEqual('userName2');
expect(res[0].username).toEqual('userName2'); expect(res[1].id).toEqual('mock-user-id-3');
expect(res[1].id).toEqual('mock-user-id-3'); expect(res[1].username).toEqual('userName3');
expect(res[1].username).toEqual('userName3'); done();
done(); });
}
);
}); });
it('should return true when user has access to an application', (done) => { it('should return true when user has access to an application', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles));
service.checkUserHasClientApp('user-id', 'app-name').subscribe( service.checkUserHasClientApp('user-id', 'app-name').subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeTruthy();
expect(res).toBeTruthy(); done();
done(); });
}
);
}); });
it('should return false when user does not have access to an application', (done) => { it('should return false when user does not have access to an application', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkUserHasClientApp('user-id', 'app-name').subscribe( service.checkUserHasClientApp('user-id', 'app-name').subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeFalsy();
expect(res).toBeFalsy(); done();
done(); });
}
);
}); });
it('should return true when user has any given application role', (done) => { it('should return true when user has any given application role', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getClientRoles').and.returnValue(of(mockRoles));
service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name] ).subscribe( service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name]).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeTruthy();
expect(res).toBeTruthy(); done();
done(); });
}
);
}); });
it('should return false when user does not have any given application role', (done) => { it('should return false when user does not have any given application role', (done) => {
spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client')); spyOn(service, 'getClientIdByApplicationName').and.returnValue(of('mock-client'));
spyOn(service, 'getClientRoles').and.returnValue(of([])); spyOn(service, 'getClientRoles').and.returnValue(of([]));
service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name]).subscribe( service.checkUserHasAnyClientAppRole('user-id', 'app-name', [mockRoles[1].name]).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeFalsy();
expect(res).toBeFalsy(); done();
done(); });
}
);
}); });
it('should return true if user has given role', (done) => { it('should return true if user has given role', (done) => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-1']).subscribe( service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-1']).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeTruthy();
expect(res).toBeTruthy(); done();
done(); });
}
);
}); });
it('should return false if user does not have given role', (done) => { it('should return false if user does not have given role', (done) => {
spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles)); spyOn(service, 'getUserRoles').and.returnValue(of(mockRoles));
service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-10']).subscribe( service.checkUserHasRole('mock-user-id', ['MOCK-ROLE-10']).subscribe((res: boolean) => {
(res: boolean) => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(res).toBeFalsy();
expect(res).toBeFalsy(); done();
done(); });
}
);
}); });
it('should be able to query users based on query params (first & max params)', (done) => { it('should be able to query users based on query params (first & max params)', (done) => {
requestSpy.and.returnValue(Promise.resolve(mockIdentityUsers)); requestSpy.and.returnValue(Promise.resolve(mockIdentityUsers));
service.queryUsers({first: 0, max: 5}).subscribe((res) => { service.queryUsers({ first: 0, max: 5 }).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
expect(res.entries.length).toBe(5); expect(res.entries.length).toBe(5);
@ -300,23 +275,23 @@ describe('IdentityUserService', () => {
it('Should not be able to query users if error occurred', (done) => { it('Should not be able to query users if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'queryUsers').and.returnValue(throwError(errorResponse)); spyOn(service, 'queryUsers').and.returnValue(throwError(errorResponse));
service.queryUsers({first: 0, max: 5}) service.queryUsers({ first: 0, max: 5 }).subscribe(
.subscribe( () => {
() => { fail('expected an error, not users');
fail('expected an error, not users'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to create user', (done) => { it('should be able to create user', (done) => {
@ -330,23 +305,23 @@ describe('IdentityUserService', () => {
it('Should not able to create user if error occurred', (done) => { it('Should not able to create user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'createUser').and.returnValue(throwError(errorResponse)); spyOn(service, 'createUser').and.returnValue(throwError(errorResponse));
service.createUser(mockIdentityUser1) service.createUser(mockIdentityUser1).subscribe(
.subscribe( () => {
() => { fail('expected an error, not to create user');
fail('expected an error, not to create user'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to update user', (done) => { it('should be able to update user', (done) => {
@ -360,23 +335,23 @@ describe('IdentityUserService', () => {
it('Should not able to update user if error occurred', (done) => { it('Should not able to update user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'updateUser').and.returnValue(throwError(errorResponse)); spyOn(service, 'updateUser').and.returnValue(throwError(errorResponse));
service.updateUser('mock-id-2', mockIdentityUser2) service.updateUser('mock-id-2', mockIdentityUser2).subscribe(
.subscribe( () => {
() => { fail('expected an error, not to update user');
fail('expected an error, not to update user'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to delete group', (done) => { it('should be able to delete group', (done) => {
@ -390,23 +365,23 @@ describe('IdentityUserService', () => {
it('Should not able to delete user if error occurred', (done) => { it('Should not able to delete user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'deleteUser').and.returnValue(throwError(errorResponse)); spyOn(service, 'deleteUser').and.returnValue(throwError(errorResponse));
service.deleteUser('mock-user-id') service.deleteUser('mock-user-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not to delete user');
fail('expected an error, not to delete user'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to fetch involved groups based on user id', (done) => { it('should be able to fetch involved groups based on user id', (done) => {
@ -426,23 +401,23 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch involved groups if error occurred', (done) => { it('Should not be able to fetch involved groups if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getInvolvedGroups').and.returnValue(throwError(errorResponse)); spyOn(service, 'getInvolvedGroups').and.returnValue(throwError(errorResponse));
service.getInvolvedGroups('mock-user-id') service.getInvolvedGroups('mock-user-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not involved groups');
fail('expected an error, not involved groups'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to join the group', (done) => { it('should be able to join the group', (done) => {
@ -456,23 +431,23 @@ describe('IdentityUserService', () => {
it('Should not able to join group if error occurred', (done) => { it('Should not able to join group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'joinGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'joinGroup').and.returnValue(throwError(errorResponse));
service.joinGroup(mockJoinGroupRequest) service.joinGroup(mockJoinGroupRequest).subscribe(
.subscribe( () => {
() => { fail('expected an error, not to join group');
fail('expected an error, not to join group'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to leave the group', (done) => { it('should be able to leave the group', (done) => {
@ -486,23 +461,23 @@ describe('IdentityUserService', () => {
it('Should not able to leave group if error occurred', (done) => { it('Should not able to leave group if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'leaveGroup').and.returnValue(throwError(errorResponse)); spyOn(service, 'leaveGroup').and.returnValue(throwError(errorResponse));
service.leaveGroup('mock-user-id', 'mock-group-id') service.leaveGroup('mock-user-id', 'mock-group-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not to leave group');
fail('expected an error, not to leave group'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to fetch available roles based on user id', (done) => { it('should be able to fetch available roles based on user id', (done) => {
@ -524,23 +499,23 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch available roles based on user id if error occurred', (done) => { it('Should not be able to fetch available roles based on user id if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getAvailableRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getAvailableRoles').and.returnValue(throwError(errorResponse));
service.getAvailableRoles('mock-user-id') service.getAvailableRoles('mock-user-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not available roles');
fail('expected an error, not available roles'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to fetch assigned roles based on user id', (done) => { it('should be able to fetch assigned roles based on user id', (done) => {
@ -562,23 +537,23 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch assigned roles based on user id if error occurred', (done) => { it('Should not be able to fetch assigned roles based on user id if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getAssignedRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getAssignedRoles').and.returnValue(throwError(errorResponse));
service.getAssignedRoles('mock-user-id') service.getAssignedRoles('mock-user-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not assigned roles');
fail('expected an error, not assigned roles'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to fetch effective roles based on user id', (done) => { it('should be able to fetch effective roles based on user id', (done) => {
@ -600,23 +575,23 @@ describe('IdentityUserService', () => {
it('Should not be able to fetch effective roles based on user id if error occurred', (done) => { it('Should not be able to fetch effective roles based on user id if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'getEffectiveRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'getEffectiveRoles').and.returnValue(throwError(errorResponse));
service.getEffectiveRoles('mock-user-id') service.getEffectiveRoles('mock-user-id').subscribe(
.subscribe( () => {
() => { fail('expected an error, not effective roles');
fail('expected an error, not effective roles'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to assign roles to the user', (done) => { it('should be able to assign roles to the user', (done) => {
@ -630,23 +605,23 @@ describe('IdentityUserService', () => {
it('Should not able to assign roles to the user if error occurred', (done) => { it('Should not able to assign roles to the user if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'assignRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'assignRoles').and.returnValue(throwError(errorResponse));
service.assignRoles('mock-user-id', [mockIdentityRole]) service.assignRoles('mock-user-id', [mockIdentityRole]).subscribe(
.subscribe( () => {
() => { fail('expected an error, not to assigen roles to the user');
fail('expected an error, not to assigen roles to the user'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should be able to remove roles', (done) => { it('should be able to remove roles', (done) => {
@ -660,22 +635,22 @@ describe('IdentityUserService', () => {
it('Should not able to remove roles if error occurred', (done) => { it('Should not able to remove roles if error occurred', (done) => {
const errorResponse = new HttpErrorResponse({ const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404,
statusText: 'Not Found'
}); });
spyOn(service, 'removeRoles').and.returnValue(throwError(errorResponse)); spyOn(service, 'removeRoles').and.returnValue(throwError(errorResponse));
service.removeRoles('mock-user-id', [mockIdentityRole]) service.removeRoles('mock-user-id', [mockIdentityRole]).subscribe(
.subscribe( () => {
() => { fail('expected an error, not to remove roles');
fail('expected an error, not to remove roles'); },
}, (error) => {
(error) => { expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
}); });

View File

@ -15,11 +15,11 @@
* limitations under the License. * limitations under the License.
*/ */
import { CoreTestingModule } from '../../testing';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { UserAccessService } from './user-access.service'; import { UserAccessService } from './user-access.service';
import { JwtHelperService } from './jwt-helper.service'; import { JwtHelperService } from './jwt-helper.service';
import { AppConfigService } from '../../app-config'; import { AppConfigService } from '../../app-config';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('UserAccessService', () => { describe('UserAccessService', () => {
let userAccessService: UserAccessService; let userAccessService: UserAccessService;
@ -28,7 +28,7 @@ describe('UserAccessService', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CoreTestingModule], imports: [HttpClientTestingModule],
providers: [UserAccessService] providers: [UserAccessService]
}); });
userAccessService = TestBed.inject(UserAccessService); userAccessService = TestBed.inject(UserAccessService);
@ -83,7 +83,6 @@ describe('UserAccessService', () => {
}); });
describe('Access present in realm_access', () => { describe('Access present in realm_access', () => {
it('should return true when the user has one of the global roles', () => { it('should return true when the user has one of the global roles', () => {
spyRealmAccess(['MOCK_USER_ROLE', 'MOCK_USER_ROLE_2'], {}); spyRealmAccess(['MOCK_USER_ROLE', 'MOCK_USER_ROLE_2'], {});
userAccessService.fetchUserAccess(); userAccessService.fetchUserAccess();
@ -118,7 +117,6 @@ describe('UserAccessService', () => {
}); });
describe('Access present in hxp_authorization', () => { describe('Access present in hxp_authorization', () => {
it('should return true when the user has one of the global roles', () => { it('should return true when the user has one of the global roles', () => {
spyHxpAuthorization('mockApp1', ['MOCK_GLOBAL_USER_ROLE']); spyHxpAuthorization('mockApp1', ['MOCK_GLOBAL_USER_ROLE']);
appConfigService.config = { application: { key: 'mockApp1' } }; appConfigService.config = { application: { key: 'mockApp1' } };

View File

@ -17,7 +17,6 @@
import { TestBed, ComponentFixture } from '@angular/core/testing'; import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MaterialModule } from '../material.module'; import { MaterialModule } from '../material.module';
import { CoreTestingModule } from '../testing/core.testing.module';
import { CUSTOM_ELEMENTS_SCHEMA, Component } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA, Component } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
@ -25,14 +24,11 @@ import { TranslateModule } from '@ngx-translate/core';
selector: 'adf-custom-container', selector: 'adf-custom-container',
template: ` template: `
<adf-buttons-action-menu> <adf-buttons-action-menu>
<button mat-menu-item (click)="assignValue()"> <button mat-menu-item (click)="assignValue()"><mat-icon>settings</mat-icon><span> Button </span></button>
<mat-icon>settings</mat-icon><span> Button </span>
</button>
</adf-buttons-action-menu> </adf-buttons-action-menu>
` `
}) })
export class CustomContainerComponent { export class CustomContainerComponent {
value: number; value: number;
assignValue() { assignValue() {
@ -42,35 +38,21 @@ export class CustomContainerComponent {
@Component({ @Component({
selector: 'adf-custom-empty-container', selector: 'adf-custom-empty-container',
template: ` template: ` <adf-buttons-action-menu> </adf-buttons-action-menu> `
<adf-buttons-action-menu>
</adf-buttons-action-menu>
`
}) })
export class CustomEmptyContainerComponent { export class CustomEmptyContainerComponent {}
}
describe('ButtonsMenuComponent', () => { describe('ButtonsMenuComponent', () => {
describe('When Buttons are injected', () => { describe('When Buttons are injected', () => {
let fixture: ComponentFixture<CustomContainerComponent>; let fixture: ComponentFixture<CustomContainerComponent>;
let component: CustomContainerComponent; let component: CustomContainerComponent;
let element: HTMLElement; let element: HTMLElement;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot()],
TranslateModule.forRoot(), declarations: [CustomContainerComponent],
CoreTestingModule, schemas: [CUSTOM_ELEMENTS_SCHEMA]
MaterialModule
],
declarations: [
CustomContainerComponent
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
}); });
fixture = TestBed.createComponent(CustomContainerComponent); fixture = TestBed.createComponent(CustomContainerComponent);
element = fixture.debugElement.nativeElement; element = fixture.debugElement.nativeElement;
@ -111,17 +93,9 @@ describe('ButtonsMenuComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), MaterialModule],
TranslateModule.forRoot(), declarations: [CustomEmptyContainerComponent],
CoreTestingModule, schemas: [CUSTOM_ELEMENTS_SCHEMA]
MaterialModule
],
declarations: [
CustomEmptyContainerComponent
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
}); });
fixture = TestBed.createComponent(CustomEmptyContainerComponent); fixture = TestBed.createComponent(CustomEmptyContainerComponent);
element = fixture.nativeElement; element = fixture.nativeElement;

View File

@ -21,20 +21,15 @@ import { MatCheckbox, MatCheckboxChange } from '@angular/material/checkbox';
import { CardViewUpdateService } from '../../services/card-view-update.service'; import { CardViewUpdateService } from '../../services/card-view-update.service';
import { CardViewBoolItemComponent } from './card-view-boolitem.component'; import { CardViewBoolItemComponent } from './card-view-boolitem.component';
import { CardViewBoolItemModel } from '../../models/card-view-boolitem.model'; import { CardViewBoolItemModel } from '../../models/card-view-boolitem.model';
import { CoreTestingModule } from '../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
describe('CardViewBoolItemComponent', () => { describe('CardViewBoolItemComponent', () => {
let fixture: ComponentFixture<CardViewBoolItemComponent>; let fixture: ComponentFixture<CardViewBoolItemComponent>;
let component: CardViewBoolItemComponent; let component: CardViewBoolItemComponent;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot()]
TranslateModule.forRoot(),
CoreTestingModule
]
}); });
fixture = TestBed.createComponent(CardViewBoolItemComponent); fixture = TestBed.createComponent(CardViewBoolItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
@ -52,7 +47,6 @@ describe('CardViewBoolItemComponent', () => {
}); });
describe('Rendering', () => { describe('Rendering', () => {
it('should render the label and value if the property is editable', () => { it('should render the label and value if the property is editable', () => {
component.editable = true; component.editable = true;
component.property.editable = true; component.property.editable = true;
@ -169,7 +163,6 @@ describe('CardViewBoolItemComponent', () => {
}); });
describe('Update', () => { describe('Update', () => {
beforeEach(() => { beforeEach(() => {
component.editable = true; component.editable = true;
component.property.editable = true; component.property.editable = true;
@ -180,7 +173,7 @@ describe('CardViewBoolItemComponent', () => {
it('should trigger the update event when changing the checkbox', () => { it('should trigger the update event when changing the checkbox', () => {
const cardViewUpdateService = TestBed.inject(CardViewUpdateService); const cardViewUpdateService = TestBed.inject(CardViewUpdateService);
spyOn(cardViewUpdateService, 'update'); spyOn(cardViewUpdateService, 'update');
const property = { ... component.property }; const property = { ...component.property };
component.changed({ checked: true } as MatCheckboxChange); component.changed({ checked: true } as MatCheckboxChange);
@ -204,14 +197,12 @@ describe('CardViewBoolItemComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const property = { ...component.property }; const property = { ...component.property };
const disposableUpdate = cardViewUpdateService.itemUpdated$.subscribe( const disposableUpdate = cardViewUpdateService.itemUpdated$.subscribe((updateNotification) => {
(updateNotification) => { expect(updateNotification.target).toEqual(property);
expect(updateNotification.target).toEqual(property); expect(updateNotification.changed).toEqual({ boolKey: true });
expect(updateNotification.changed).toEqual({ boolKey: true }); disposableUpdate.unsubscribe();
disposableUpdate.unsubscribe(); done();
done(); });
}
);
const labelElement = fixture.debugElement.query(By.directive(MatCheckbox)).nativeElement.querySelector('label'); const labelElement = fixture.debugElement.query(By.directive(MatCheckbox)).nativeElement.querySelector('label');
labelElement.click(); labelElement.click();

View File

@ -20,7 +20,6 @@ import { By } from '@angular/platform-browser';
import { CardViewDateItemModel } from '../../models/card-view-dateitem.model'; import { CardViewDateItemModel } from '../../models/card-view-dateitem.model';
import { CardViewUpdateService } from '../../services/card-view-update.service'; import { CardViewUpdateService } from '../../services/card-view-update.service';
import { CardViewDateItemComponent } from './card-view-dateitem.component'; import { CardViewDateItemComponent } from './card-view-dateitem.component';
import { CoreTestingModule } from '../../../testing/core.testing.module';
import { ClipboardService } from '../../../clipboard/clipboard.service'; import { ClipboardService } from '../../../clipboard/clipboard.service';
import { CardViewDatetimeItemModel } from '../../models/card-view-datetimeitem.model'; import { CardViewDatetimeItemModel } from '../../models/card-view-datetimeitem.model';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
@ -29,6 +28,14 @@ import { MatDatetimepickerInputEvent } from '@mat-datetimepicker/core';
import { HarnessLoader } from '@angular/cdk/testing'; import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatChipHarness } from '@angular/material/chips/testing'; import { MatChipHarness } from '@angular/material/chips/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { TranslationMock } from '../../../mock';
import { TranslationService } from '../../../translation';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatDialogModule } from '@angular/material/dialog';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { MatDatepickerModule } from '@angular/material/datepicker';
describe('CardViewDateItemComponent', () => { describe('CardViewDateItemComponent', () => {
let loader: HarnessLoader; let loader: HarnessLoader;
@ -38,7 +45,16 @@ describe('CardViewDateItemComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), CoreTestingModule] imports: [
TranslateModule.forRoot(),
NoopAnimationsModule,
HttpClientTestingModule,
MatSnackBarModule,
MatDatepickerModule,
MatDialogModule,
MatTooltipModule
],
providers: [ClipboardService, { provide: TranslationService, useClass: TranslationMock }]
}); });
appConfigService = TestBed.inject(AppConfigService); appConfigService = TestBed.inject(AppConfigService);
appConfigService.config.dateValues = { appConfigService.config.dateValues = {

View File

@ -17,7 +17,6 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { IdentityGroupService } from './identity-group.service'; import { IdentityGroupService } from './identity-group.service';
import { import {
mockHttpErrorResponse, mockHttpErrorResponse,
@ -27,19 +26,17 @@ import {
} from '../mock/identity-group.service.mock'; } from '../mock/identity-group.service.mock';
import { mockFoodGroups } from '../mock/group-cloud.mock'; import { mockFoodGroups } from '../mock/group-cloud.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api'; import { AdfHttpClient } from '@alfresco/adf-core/api';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('IdentityGroupService', () => { describe('IdentityGroupService', () => {
let service: IdentityGroupService; let service: IdentityGroupService;
let adfHttpClient: AdfHttpClient; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy; let requestSpy: jasmine.Spy;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), HttpClientTestingModule],
TranslateModule.forRoot(), providers: [IdentityGroupService]
ProcessServiceCloudTestingModule
]
}); });
service = TestBed.inject(IdentityGroupService); service = TestBed.inject(IdentityGroupService);
adfHttpClient = TestBed.inject(AdfHttpClient); adfHttpClient = TestBed.inject(AdfHttpClient);
@ -47,21 +44,18 @@ describe('IdentityGroupService', () => {
}); });
describe('Search', () => { describe('Search', () => {
it('should fetch groups', (done) => { it('should fetch groups', (done) => {
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups)); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake').subscribe( service.search('fake').subscribe((res) => {
res => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(searchSpy).toHaveBeenCalled();
expect(searchSpy).toHaveBeenCalled(); expect(service.queryParams).toEqual({
expect(service.queryParams).toEqual({ search: 'fake'
search: 'fake' });
}); done();
done(); });
}
);
}); });
it('should not fetch groups if error occurred', (done) => { it('should not fetch groups if error occurred', (done) => {
@ -69,113 +63,104 @@ describe('IdentityGroupService', () => {
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake') service.search('fake').subscribe(
.subscribe( () => {
() => { fail('expected an error, not groups');
fail('expected an error, not groups'); },
}, (error) => {
(error) => { expect(searchSpy).toHaveBeenCalled();
expect(searchSpy).toHaveBeenCalled(); expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should fetch groups by roles', (done) => { it('should fetch groups by roles', (done) => {
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups)); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles).subscribe( service.search('fake', mockSearchGroupByRoles).subscribe((res) => {
res => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(searchSpy).toHaveBeenCalled();
expect(searchSpy).toHaveBeenCalled(); expect(service.queryParams).toEqual({
expect(service.queryParams).toEqual({ search: 'fake',
search: 'fake', role: 'fake-role-1,fake-role-2'
role: 'fake-role-1,fake-role-2' });
}); done();
done(); });
}
);
}); });
it('should not fetch groups by roles if error occurred', (done) => { it('should not fetch groups by roles if error occurred', (done) => {
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse)); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles) service.search('fake', mockSearchGroupByRoles).subscribe(
.subscribe( () => {
() => { fail('expected an error, not groups');
fail('expected an error, not groups'); },
}, (error) => {
(error) => { expect(searchSpy).toHaveBeenCalled();
expect(searchSpy).toHaveBeenCalled(); expect(service.queryParams).toEqual({
expect(service.queryParams).toEqual({ search: 'fake',
search: 'fake', role: 'fake-role-1,fake-role-2'
role: 'fake-role-1,fake-role-2' });
}); expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
it('should fetch groups within app', (done) => { it('should fetch groups within app', (done) => {
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups)); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByApp).subscribe( service.search('fake', mockSearchGroupByApp).subscribe((res) => {
res => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(service.queryParams).toEqual({
expect(service.queryParams).toEqual({ search: 'fake',
search: 'fake', application: 'fake-app-name'
application: 'fake-app-name' });
}); done();
done(); });
}
);
}); });
it('should fetch groups within app with roles', (done) => { it('should fetch groups within app with roles', (done) => {
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups)); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByRolesAndApp).subscribe( service.search('fake', mockSearchGroupByRolesAndApp).subscribe((res) => {
res => { expect(res).toBeDefined();
expect(res).toBeDefined(); expect(service.queryParams).toEqual({
expect(service.queryParams).toEqual({ search: 'fake',
search: 'fake', application: 'fake-app-name',
application: 'fake-app-name', role: 'fake-role-1,fake-role-2'
role: 'fake-role-1,fake-role-2' });
}); done();
done(); });
}
);
}); });
it('should not fetch groups within app if error occurred', (done) => { it('should not fetch groups within app if error occurred', (done) => {
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse)); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByApp) service.search('fake', mockSearchGroupByApp).subscribe(
.subscribe( () => {
() => { fail('expected an error, not groups');
fail('expected an error, not groups'); },
}, (error) => {
(error) => { expect(searchSpy).toHaveBeenCalled();
expect(searchSpy).toHaveBeenCalled(); expect(service.queryParams).toEqual({
expect(service.queryParams).toEqual({ search: 'fake',
search: 'fake', application: 'fake-app-name'
application: 'fake-app-name' });
}); expect(error.status).toEqual(404);
expect(error.status).toEqual(404); expect(error.statusText).toEqual('Not Found');
expect(error.statusText).toEqual('Not Found'); expect(error.error).toEqual('Mock Error');
expect(error.error).toEqual('Mock Error'); done();
done(); }
} );
);
}); });
}); });
}); });