gpt4 book ai didi

javascript - Angular 单元测试授权 header 拦截器不起作用

转载 作者:行者123 更新时间:2023-11-30 06:19:20 24 4
gpt4 key购买 nike

错误:预期有一个符合条件“按功能匹配:”的匹配请求,但没有找到。我搜索了很多东西并尝试了一些解决方案。但他们都没有工作。这是我的第一个单元测试项目。这是我的代码。

授权拦截器

export const API_URL = new InjectionToken<string>('apiUrl');
export class JwtInterceptor implements HttpInterceptor {
constructor(@Inject(API_URL) private apiUrl: string) {
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

request = request.clone({url: this.prepareUrl(request.url)});

let authToken = localStorage.getItem('auth_token');
if (authToken) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`
}
});
}
else {
// use proxy url for cors error
request = request.clone({url: this.prepareUrl('https://cors-anywhere.herokuapp.com/' + request.url)});
// Encode the String
let encodedString = btoa(`${environment.clientId}:${environment.clientSecret}`);
request = request.clone({
setHeaders: {
Authorization: `Basic ${encodedString}`
}
});
}
return next.handle(request);

}

private isAbsoluteUrl(url: string): boolean {
const absolutePattern = /^https?:\/\//i;
return absolutePattern.test(url);
}

private prepareUrl(url: string): string {
url = this.isAbsoluteUrl(url) ? url : this.apiUrl + '/' + url;
return url.replace(/([^:]\/)\/+/g, '$1');
}

}

Auth 拦截器规范

describe('Jwt Interceptor', ()=> { 

let httpTestingController: HttpTestingController;
let http: HttpClient;

beforeEach(()=> {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
}]
});

httpTestingController = TestBed.get(HttpTestingController);
http = TestBed.get(HttpClient);
});

it('should add Authorization header in each request', ()=> {
http.get('/data').subscribe(response => {
expect(response).toBeTruthy();
});

const req = httpTestingController.expectOne(
req => req.headers.has('Authorization')
);
expect(req.request.headers.has('Authorization')).toEqual(true);
expect(req.request.method).toEqual('GET');

req.flush({hello: 'world'});
});
afterEach(()=> {
httpTestingController.verify();
});
});

我还尝试使用模拟服务设置授权 header 。任何人都可以帮助我在这里缺少什么吗?

最佳答案

最后,我找到了一个解决方案,这是我用于 auth 拦截器测试的最终代码。使用您的任何服务方法发出 http 请求。因此,它可以正确地验证拦截器。此外,我还忘记在 TestBed 配置中提供 apiUrl。

import {TestBed} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {HTTP_INTERCEPTORS, HttpClient} from '@angular/common/http';
import {API_URL, JwtInterceptor} from './jwt.interceptor';
import {DataService} from './data.service';

describe('JwtInterceptor', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
let service: DataService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
DataService,
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
{
provide: API_URL,
useValue: {apiUrl: 'localhost'}
}]
});
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(DataService);
// for localstorage mocking
let store = {};
const mockLocalStorage = {
getItem: (key: string): string => {
return key in store ? store[key] : null;
},
setItem: (key: string, value: string) => {
store[key] = `${value}`;
},
removeItem: (key: string) => {
delete store[key];
},
clear: () => {
store = {};
}
};
spyOn(localStorage, 'getItem').and.callFake(mockLocalStorage.getItem);
spyOn(localStorage, 'setItem').and.callFake(mockLocalStorage.setItem);
spyOn(localStorage, 'removeItem').and.callFake(mockLocalStorage.removeItem);
spyOn(localStorage, 'clear').and.callFake(mockLocalStorage.clear);
});



afterEach(() => {
httpTestingController.verify();
});



describe('making http calls', () => {
it('adds authorization header', () => {
const apiUrl = TestBed.get(API_URL);
service.getData().subscribe(response => {
expect(response).toBeTruthy();
});

localStorage.setItem('auth_token', 'any auth token here');
const authToken = localStorage.getItem('auth_token');
const req = httpTestingController.expectOne(apiUrl + '/getData');
expect(req.request.headers.has('Authorization')).toEqual(true);
expect(req.request.headers.get('Authorization')).toEqual(`Bearer ${authToken}`);
});
});

});

关于javascript - Angular 单元测试授权 header 拦截器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54129330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com