Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove tick from tests and await async functions correctly #356

Merged
merged 18 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed, fakeAsync, tick, flush } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { BehaviorSubject, of, Subject } from 'rxjs';
import { BehaviorSubject, firstValueFrom, of, Subject } from 'rxjs';
import { AppConfigService } from 'src/app/services/app-config.service';
import { TokenService } from 'src/app/services/token.service';
import { PrevAuthGuard } from './prev-auth-guard';
Expand Down Expand Up @@ -187,175 +187,170 @@ describe('PrevAuthGuard', () => {
});
});

it('should redirect user to error page when token validation fails', fakeAsync(() => {
it('should redirect user to error page when token validation fails', async () => {
const route = new ActivatedRouteSnapshot();
route.data = { scopes: [['test-scope']] };

const state = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', [], { url: '/test' });

// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');
// Mock the token service to simulate validation failure
tokenService.getOauthToken.and.returnValue('test-token'); // Mock token exists
tokenService.validateToken.and.returnValue(of(false)); // Mock validation failure

// Mock token validation fails
tokenService.validateToken.and.returnValue(of(false));
// Spy on the redirectToErrorPage method
const redirectToErrorPageSpy = spyOn(guard, 'redirectToErrorPage');

// Use `firstValueFrom` to handle asynchronous observable completion
await firstValueFrom(guard.canActivate(route, state));

// Assert that redirectToErrorPage was called
expect(redirectToErrorPageSpy).toHaveBeenCalled();
});

it('should redirect to error page when getTokenInfo returns false', async () => {
const route = new MockActivatedRouteSnapshot();
route.data = { scopes: [['test-scope']] };
const state = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', [], {
url: '/test',
});

// Mock getTokenInfo to return a resolved Promise with false
spyOn<any>(guard, 'getTokenInfo').and.returnValue(Promise.resolve(false));

// Spy on redirectToErrorPage
spyOn(guard, 'redirectToErrorPage');

guard.canActivate(route, state);

tick();
flush(); // Flush any remaining async operations
// Start the canActivate observable and wait for its completion
await firstValueFrom(guard.canActivate(route, state));

// Assert that redirectToErrorPage was called
expect(guard.redirectToErrorPage).toHaveBeenCalled();
}));
})

it('should redirect to error page when getTokenInfo returns false', fakeAsync(() => {
const route = new MockActivatedRouteSnapshot();
route.data = { scopes: [['test-scope']] };
const state = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', [], {
url: '/test'
});

// Spy on getTokenInfo to return false
spyOn(guard, 'getTokenInfo' as any).and.returnValue(Promise.resolve(false));

// Spy on redirectToErrorPage
spyOn(guard, 'redirectToErrorPage');

guard.canActivate(route, state).subscribe();

tick();
flush(); // Flush any remaining async operations

it('should redirect to error page when getTokenInfo returns undefined', async () => {
const route = new MockActivatedRouteSnapshot();
route.data = { scopes: [['test-scope']] };
const state = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', [], {
url: '/test',
});

expect(guard.redirectToErrorPage).toHaveBeenCalled();
}));

it('should redirect to error page when getTokenInfo returns undefined', fakeAsync(() => {
const route = new MockActivatedRouteSnapshot();
route.data = { scopes: [['test-scope']] };
const state = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', [], {
url: '/test'
});

// Spy on getTokenInfo to return undefined
spyOn(guard, 'getTokenInfo' as any).and.returnValue(Promise.resolve(undefined));
// Mock getTokenInfo to return a resolved Promise with undefined
spyOn<any>(guard, 'getTokenInfo').and.returnValue(Promise.resolve(undefined));

// Spy on redirectToErrorPage
spyOn(guard, 'redirectToErrorPage');

guard.canActivate(route, state).subscribe();
// Spy on redirectToErrorPage
spyOn(guard, 'redirectToErrorPage');

tick();
flush(); // Flush any remaining async operations
// Start the canActivate observable and wait for its completion
await firstValueFrom(guard.canActivate(route, state));

expect(guard.redirectToErrorPage).toHaveBeenCalled();
}));

describe('getTokenInfo', () => {
let mockRoute: any;

beforeEach(() => {
mockRoute = {
routeConfig: { path: 'test-path' },
params: {},
queryParams: {},
data: { scopes: [['test-scope']] }
};
// Assert that redirectToErrorPage was called
expect(guard.redirectToErrorPage).toHaveBeenCalled();
});
});

it('should initiate token check when no token exists', async () => {
// Mock no existing token
tokenService.getOauthToken.and.returnValue(null);

// Mock config service
appConfigService.getConfig.and.returnValue({
application: {
baseUrl: 'http://test.com',
lazyAuthenticate: false,
enableLocalStorageToken: true,
acronym: 'WFPREV',
environment: 'DEV',
version: '0.0.0'
},
webade: {
oauth2Url: 'http://oauth.test',
clientId: 'test-client',
authScopes: 'WFPREV.*'
},
rest: {}
});

// Mock checkForToken
spyOn(guard, 'checkForToken').and.returnValue(of(true));
describe('getTokenInfo', () => {
let mockRoute: any;

const result = await guard['getTokenInfo'](mockRoute);
beforeEach(() => {
mockRoute = {
routeConfig: { path: 'test-path' },
params: {},
queryParams: {},
data: { scopes: [['test-scope']] }
};
});

expect(guard.checkForToken).toHaveBeenCalled();
});
it('should initiate token check when no token exists', async () => {
// Mock no existing token
tokenService.getOauthToken.and.returnValue(null);

// Mock config service
appConfigService.getConfig.and.returnValue({
application: {
baseUrl: 'http://test.com',
lazyAuthenticate: false,
enableLocalStorageToken: true,
acronym: 'WFPREV',
environment: 'DEV',
version: '0.0.0'
},
webade: {
oauth2Url: 'http://oauth.test',
clientId: 'test-client',
authScopes: 'WFPREV.*'
},
rest: {}
});

// Mock checkForToken
spyOn(guard, 'checkForToken').and.returnValue(of(true));

const result = await guard['getTokenInfo'](mockRoute);

expect(guard.checkForToken).toHaveBeenCalled();
});

it('should return true when token exists and passes route access', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');
it('should return true when token exists and passes route access', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');

// Mock token validation
tokenService.validateToken.and.returnValue(of(true));
// Mock token validation
tokenService.validateToken.and.returnValue(of(true));

const result = await guard['getTokenInfo'](mockRoute);
const result = await guard['getTokenInfo'](mockRoute);

expect(result).toBeTruthy();
});
expect(result).toBeTruthy();
});

it('should redirect to error page when token validation fails', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');
it('should redirect to error page when token validation fails', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');

// Mock token validation fails
tokenService.validateToken.and.returnValue(of(false));
// Mock token validation fails
tokenService.validateToken.and.returnValue(of(false));

// Spy on redirectToErrorPage
spyOn(guard, 'redirectToErrorPage');
// Spy on redirectToErrorPage
spyOn(guard, 'redirectToErrorPage');

const result = await guard['getTokenInfo'](mockRoute);
const result = await guard['getTokenInfo'](mockRoute);

expect(guard.redirectToErrorPage).toHaveBeenCalled();
expect(guard.redirectToErrorPage).toHaveBeenCalled();
});
});
});

describe('canAccessRoute', () => {
it('should return false when no token exists', async () => {
// Mock no token
tokenService.getOauthToken.and.returnValue(null);
describe('canAccessRoute', () => {
it('should return false when no token exists', async () => {
// Mock no token
tokenService.getOauthToken.and.returnValue(null);

const result = await guard.canAccessRoute([['test-scope']], tokenService);
const result = await guard.canAccessRoute([['test-scope']], tokenService);

expect(result).toBeFalse();
});
expect(result).toBeFalse();
});

it('should return true when token is validated successfully', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');
it('should return true when token is validated successfully', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');

// Mock token validation
tokenService.validateToken.and.returnValue(of(true));
// Mock token validation
tokenService.validateToken.and.returnValue(of(true));

const result = await guard.canAccessRoute([['test-scope']], tokenService);
const result = await guard.canAccessRoute([['test-scope']], tokenService);

expect(result).toBeTrue();
});
expect(result).toBeTrue();
});

it('should return false when token validation fails', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');
it('should return false when token validation fails', async () => {
// Mock token exists
tokenService.getOauthToken.and.returnValue('test-token');

// Mock token validation fails
tokenService.validateToken.and.returnValue(of(false));
// Mock token validation fails
tokenService.validateToken.and.returnValue(of(false));

const result = await guard.canAccessRoute([['test-scope']], tokenService);
const result = await guard.canAccessRoute([['test-scope']], tokenService);

expect(result).toBeFalse();
expect(result).toBeFalse();
});
});
});

});
});
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class PrevAuthGuard extends AuthGuard {
map(result => {
if (result === false || result === undefined) {
this.redirectToErrorPage();
return of(false);
return false;
}
return result;
}),
Expand Down Expand Up @@ -77,7 +77,7 @@ export class PrevAuthGuard extends AuthGuard {
Object.keys(route.queryParams).forEach((paramKey) => {
queryParamStr += paramKey + '=' + route.queryParams[paramKey] + '&';
});
queryParamStr = queryParamStr.substr(0, queryParamStr.length - 1);
queryParamStr = queryParamStr.slice(0, -1)
redirectUri = redirectUri.concat(queryParamStr);
}
return this.checkForToken(redirectUri, route).pipe(
Expand Down
Loading