Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7bc6d76

Browse files
write unit test for auth interceptor
1 parent acec25c commit 7bc6d76

File tree

1 file changed

+35
-6
lines changed

1 file changed

+35
-6
lines changed
Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,49 @@
11
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';
28
import { AuthInterceptor } from './auth-interceptor.service';
39
import { SocialAuthServiceConfigMock } from 'src/app/testing/social-auth.mock';
4-
import { HttpClientTestingModule } from '@angular/common/http/testing';
510

611
describe('AuthInterceptor', () => {
7-
let service: AuthInterceptor;
12+
let httpMock: HttpTestingController;
13+
let httpClient: HttpClient;
14+
let authService: AuthService;
815

916
beforeEach(() => {
1017
TestBed.configureTestingModule({
1118
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+
],
1328
});
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();
1537
});
1638

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+
);
1948
});
2049
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /