|
1 | 1 | import { TestBed } from '@angular/core/testing';
|
| 2 | +import { |
| 3 | + HttpClientTestingModule, |
| 4 | + HttpTestingController, |
| 5 | +} from '@angular/common/http/testing'; |
| 6 | +import { HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http'; |
| 7 | +import { AuthService } from '../auth/auth.service'; |
2 | 8 | import { AuthInterceptor } from './auth-interceptor.service';
|
3 | 9 | import { SocialAuthServiceConfigMock } from 'src/app/testing/social-auth.mock';
|
4 | | -import { HttpClientTestingModule } from '@angular/common/http/testing'; |
5 | 10 |
|
6 | 11 | describe('AuthInterceptor', () => {
|
7 | | - let service: AuthInterceptor; |
| 12 | + let httpMock: HttpTestingController; |
| 13 | + let httpClient: HttpClient; |
| 14 | + let authService: AuthService; |
8 | 15 |
|
9 | 16 | beforeEach(() => {
|
10 | 17 | TestBed.configureTestingModule({
|
11 | 18 | imports: [HttpClientTestingModule],
|
12 | | - providers: [AuthInterceptor, SocialAuthServiceConfigMock], |
| 19 | + providers: [ |
| 20 | + AuthService, // Inject the necessary dependencies. |
| 21 | + { |
| 22 | + provide: HTTP_INTERCEPTORS, |
| 23 | + useClass: AuthInterceptor, |
| 24 | + multi: true, |
| 25 | + }, |
| 26 | + SocialAuthServiceConfigMock, |
| 27 | + ], |
13 | 28 | });
|
14 | | - service = TestBed.inject(AuthInterceptor); |
| 29 | + |
| 30 | + httpMock = TestBed.inject(HttpTestingController); |
| 31 | + httpClient = TestBed.inject(HttpClient); |
| 32 | + authService = TestBed.inject(AuthService); |
| 33 | + }); |
| 34 | + |
| 35 | + afterEach(() => { |
| 36 | + httpMock.verify(); |
15 | 37 | });
|
16 | 38 |
|
17 | | - it('should be created', () => { |
18 | | - expect(service).toBeTruthy(); |
| 39 | + it('should add Authorization header with bearer token', () => { |
| 40 | + const mockToken = 'mock_token'; |
| 41 | + spyOn(authService, 'getToken').and.returnValue(mockToken); |
| 42 | + httpClient.get('/api/data').subscribe(); |
| 43 | + const req = httpMock.expectOne('/api/data'); |
| 44 | + expect(req.request.headers.has('Authorization')).toBeTrue(); |
| 45 | + expect(req.request.headers.get('Authorization')).toBe( |
| 46 | + `Bearer ${mockToken}` |
| 47 | + ); |
19 | 48 | });
|
20 | 49 | });
|
0 commit comments