|
| 1 | +import { TestBed } from '@angular/core/testing'; |
| 2 | +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; |
| 3 | +import { HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http'; |
| 4 | +import { JwtInterceptor } from './jwt.interceptor'; |
| 5 | +import { AuthenticationService } from '../_services/authentication.service'; |
| 6 | +import { API_CONFIG } from '../app/api.config'; |
| 7 | + |
| 8 | +describe('JwtInterceptor', () => { |
| 9 | + let httpMock: HttpTestingController; |
| 10 | + let httpClient: HttpClient; |
| 11 | + let mockAuthService: jasmine.SpyObj<AuthenticationService>; |
| 12 | + |
| 13 | + beforeEach(() => { |
| 14 | + mockAuthService = jasmine.createSpyObj('AuthenticationService', ['userValue'], { |
| 15 | + userValue: { accessToken: 'fake-jwt-token' }, |
| 16 | + }); |
| 17 | + |
| 18 | + TestBed.configureTestingModule({ |
| 19 | + imports: [HttpClient], |
| 20 | + providers: [ |
| 21 | + { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, |
| 22 | + { provide: AuthenticationService, useValue: mockAuthService }, |
| 23 | + provideHttpClientTesting(), |
| 24 | + ], |
| 25 | + }); |
| 26 | + |
| 27 | + httpMock = TestBed.inject(HttpTestingController); |
| 28 | + httpClient = TestBed.inject(HttpClient); |
| 29 | + }); |
| 30 | + |
| 31 | + afterEach(() => { |
| 32 | + // Check if all Http requests were handled |
| 33 | + httpMock.verify(); |
| 34 | + }); |
| 35 | + |
| 36 | + it('should add an Authorization header', () => { |
| 37 | + httpClient.get(`${API_CONFIG.baseUrl}/user/test`).subscribe(); |
| 38 | + |
| 39 | + const httpRequest = httpMock.expectOne(`${API_CONFIG.baseUrl}/user/test`); |
| 40 | + |
| 41 | + expect(httpRequest.request.headers.has('Authorization')).toBeTruthy(); |
| 42 | + expect(httpRequest.request.headers.get('Authorization')).toBe('Bearer fake-jwt-token'); |
| 43 | + }); |
| 44 | + |
| 45 | + it('should not add an Authorization header if the user is not logged in', () => { |
| 46 | + mockAuthService = jasmine.createSpyObj('AuthenticationService', ['userValue'], { |
| 47 | + userValue: {}, |
| 48 | + }); |
| 49 | + |
| 50 | + httpClient.get(`${API_CONFIG.baseUrl}/user/test`).subscribe(); |
| 51 | + |
| 52 | + const httpRequest = httpMock.expectOne(`${API_CONFIG.baseUrl}/user/test`); |
| 53 | + |
| 54 | + expect(httpRequest.request.headers.has('Authorization')).toBeFalsy(); |
| 55 | + }); |
| 56 | + |
| 57 | + it('should not add an Authorization header for non-API URLs', () => { |
| 58 | + httpClient.get('https://example.com/test').subscribe(); |
| 59 | + |
| 60 | + const httpRequest = httpMock.expectOne('https://example.com/test'); |
| 61 | + |
| 62 | + expect(httpRequest.request.headers.has('Authorization')).toBeFalsy(); |
| 63 | + }); |
| 64 | +}); |
0 commit comments