-
Notifications
You must be signed in to change notification settings - Fork 219
/
__auth._authentication.guard.spec.ts
84 lines (72 loc) · 2.64 KB
/
__auth._authentication.guard.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { TestBed } from '@angular/core/testing';
<% if (props.tools.includes('jest')) { -%>
import { Router, ActivatedRouteSnapshot } from '@angular/router';
<% } else { -%>
import { Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
<% } -%>
import { CredentialsService } from './credentials.service';
import { MockCredentialsService } from './credentials.service.mock';
import { AuthenticationGuard } from './authentication.guard';
describe('AuthenticationGuard', () => {
let authenticationGuard: AuthenticationGuard;
let credentialsService: MockCredentialsService;
let mockRouter: any;
<% if (props.tools.includes('jest')) { -%>
let mockSnapshot: any;
<% } else { -%>
let mockSnapshot: RouterStateSnapshot;
<% } -%>
beforeEach(() => {
mockRouter = {
<% if (props.tools.includes('jest')) { -%>
navigate: jest.fn()
<% } else { -%>
navigate: jasmine.createSpy('navigate')
<% } -%>
};
<% if (props.tools.includes('jest')) { -%>
mockSnapshot = jest.fn(() => ({
toString: jest.fn()
}));
<% } else { -%>
mockSnapshot = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', ['toString']);
<% } -%>
TestBed.configureTestingModule({
providers: [
AuthenticationGuard,
{ provide: CredentialsService, useClass: MockCredentialsService },
{ provide: Router, useValue: mockRouter }
]
});
authenticationGuard = TestBed.inject(AuthenticationGuard);
credentialsService = TestBed.inject(CredentialsService);
});
it('should have a canActivate method', () => {
expect(typeof authenticationGuard.canActivate).toBe('function');
});
it('should return true if user is authenticated', () => {
expect(authenticationGuard.canActivate(new ActivatedRouteSnapshot(), mockSnapshot)).toBe(true);
});
it('should return false and redirect to login if user is not authenticated', () => {
// Arrange
credentialsService.credentials = null;
// Act
const result = authenticationGuard.canActivate(new ActivatedRouteSnapshot(), mockSnapshot);
// Assert
expect(mockRouter.navigate).toHaveBeenCalledWith(['/login'], {
queryParams: { redirect: undefined },
replaceUrl: true
});
expect(result).toBe(false);
});
it('should save url as queryParam if user is not authenticated', () => {
credentialsService.credentials = null;
mockRouter.url = '/about';
mockSnapshot.url = '/about';
authenticationGuard.canActivate(new ActivatedRouteSnapshot(), mockSnapshot);
expect(mockRouter.navigate).toHaveBeenCalledWith(['/login'], {
queryParams: { redirect: mockRouter.url },
replaceUrl: true
});
});
});