Javascript angular中的单元测试授权标头拦截器不工作
错误:应为条件“按函数匹配:”提供一个匹配请求,但未找到任何匹配请求。 我搜索了很多东西,尝试了一些解决方案。但没有一个成功。这是我的第一个单元测试项目。这是我的密码 身份验证拦截器Javascript angular中的单元测试授权标头拦截器不工作,javascript,angular,unit-testing,karma-jasmine,angular-http-interceptors,Javascript,Angular,Unit Testing,Karma Jasmine,Angular Http Interceptors,错误:应为条件“按函数匹配:”提供一个匹配请求,但未找到任何匹配请求。 我搜索了很多东西,尝试了一些解决方案。但没有一个成功。这是我的第一个单元测试项目。这是我的密码 身份验证拦截器 export const API_URL = new InjectionToken<string>('apiUrl'); export class JwtInterceptor implements HttpInterceptor { constructor(@Inject(API_URL) pri
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拦截器测试的最终代码。使用任何服务方法发出http请求。因此,它可以正确地验证拦截器。此外,我还忘了在测试台配置中提供APIRL
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}`);
});
});
});
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}`);
});
});
});