Angular 无法使用Karma和Jasmine测试http拦截器
我正在尝试测试http拦截器,但我找不到任何方法 我不知道为什么url不匹配,因为我的令牌已登录到控制台,请求url也相同。我在没有拦截器的情况下使用此方法测试了我的所有其他http服务,所有内容都通过了 这是拦截器类,代码工作并在每个请求中添加我的承载令牌,它使用在测试中模拟的Ionic Platform本机类:Angular 无法使用Karma和Jasmine测试http拦截器,angular,unit-testing,typescript,ionic3,karma-jasmine,Angular,Unit Testing,Typescript,Ionic3,Karma Jasmine,我正在尝试测试http拦截器,但我找不到任何方法 我不知道为什么url不匹配,因为我的令牌已登录到控制台,请求url也相同。我在没有拦截器的情况下使用此方法测试了我的所有其他http服务,所有内容都通过了 这是拦截器类,代码工作并在每个请求中添加我的承载令牌,它使用在测试中模拟的Ionic Platform本机类: @Injectable() export class AddHeaderInterceptor implements HttpInterceptor { public cons
@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
public constructor(
private auth: AuthService, private platform: Platform,
private config: ConfigurationService
) {}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.debug('req', req.url);
return Observable.fromPromise(this.platform.ready())
.switchMap(() => Observable.fromPromise(this.auth.getToken()))
.switchMap((tokens: TokenCacheItem[]) => {
const baseUrl = new RegExp(this.config.getValue('baseUrl'), 'g');
if (! req.url.match(baseUrl)) {
return Observable.of(null);
}
if (tokens.length > 0) {
return Observable.of(tokens[0].accessToken);
}
return Observable.throw(null);
})
.switchMap((token: string) => {
console.debug('token', token);
if (!token || token === null) {
return next.handle(req);
}
const headers = req.headers
.set('Authorization', `Bearer ${token}`)
.append('Content-Type', 'application/json');
const clonedRequest = req.clone({ headers });
return next.handle(clonedRequest);
});
}
}
describe('AddHeaderInterceptor Service', () => {
let http: HttpTestingController;
let httpClient: HttpClient;
let auth: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
ConfigurationService,
{
provide: HTTP_INTERCEPTORS,
useClass: AddHeaderInterceptor,
multi: true,
},
{ provide: Platform, useClass: PlatformMock },
{ provide: LogService, useClass: LogServiceMock },
{ provide: AuthService, useClass: AuthServiceMock }
],
});
http = TestBed.get(HttpTestingController);
httpClient = TestBed.get(HttpClient);
auth = TestBed.get(AuthService);
});
it('should add Auth header to request', () => {
httpClient.get('/test').subscribe(res => expect(res).toBeTruthy());
const req = http.expectOne({ method: 'GET' });
expect(req.request.url.includes('test')).toBeTruthy();
expect(req.request.headers.has('Authorization')).toBeTruthy();
expect(req.request.headers.get('Authorization')).toEqual('Bearer TEST');
req.flush({
hello: 'world'
});
});
});
平台模拟:
export class PlatformMock {
public ready(): Promise<string> {
return Promise.resolve('READY');
}
}
我总是犯同样的错误:
错误:应为条件“Match method:GET,URL:(any)”提供一个匹配请求,但未找到任何请求
看起来请求从未启动过,我试图创建一个类实例并直接调用intercept方法,但我已经得到了相同的错误。
我试图从auth服务中监视getToken
方法,但它从未被调用。
所以我不知道为什么失败了
我试图用另一个url调用另一个服务,但仍然出现相同的错误
我尝试将绝对或相对URL与http.expectOne('http://localhost:8080/test)
而且还是一样的:
应为条件“匹配URL:
“,没有找到
有人有想法吗?我使用karma done函数并直接构造Addheader对象找到了一个解决方案:
fdescribe('AddHeaderInterceptor Service', () => {
let http: HttpTestingController;
let httpClient: HttpClient;
let auth: AuthService;
let logger: LogService;
let config: ConfigurationService;
let platform: Platform;
let interceptor: AddHeaderInterceptor;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
ConfigurationService,
{
provide: HTTP_INTERCEPTORS,
useClass: AddHeaderInterceptor,
multi: true,
},
{ provide: Platform, useClass: PlatformMocked },
{ provide: LogService, useClass: LogServiceMock },
{ provide: AuthService, useClass: AuthServiceMock }
],
});
config = TestBed.get(ConfigurationService);
auth = TestBed.get(AuthService);
logger = TestBed.get(LogService);
platform = TestBed.get(Platform);
httpClient = TestBed.get(HttpClient);
http = TestBed.get(HttpTestingController);
interceptor = new AddHeaderInterceptor(logger, auth, platform, config);
});
fit('should add header to request', (done) => {
expect((interceptor as any) instanceof AddHeaderInterceptor).toBeTruthy();
const next: any = {
handle: (request: HttpRequest<any>) => {
expect(request.headers.has('Authorization')).toBeTruthy();
expect(request.headers.get('Authorization')).toEqual('Bearer TESTO');
return Observable.of({ hello: 'world' });
}
};
const req = new HttpRequest<any>('GET', config.getValue('baseUrl') + 'test');
interceptor.intercept(req, next).subscribe(obj => done());
});
});
fdescribe('AddHeaderInterceptor服务',()=>{
让http:HttpTestingController;
let-httpClient:httpClient;
让auth:AuthService;
let logger:LogService;
let config:ConfigurationService;
让平台:平台;
let拦截器:AddHeaderInterceptor;
在每个之前(()=>{
TestBed.configureTestingModule({
导入:[HttpClientTestingModule],
供应商:[
配置服务,
{
提供:HTTP_拦截器,
useClass:AddHeaderInterceptor,
多:是的,
},
{provide:Platform,useClass:PlatformMocked},
{提供:LogService,useClass:LogServiceMock},
{提供:AuthService,useClass:AuthServiceMock}
],
});
config=TestBed.get(ConfigurationService);
auth=TestBed.get(AuthService);
logger=TestBed.get(LogService);
platform=TestBed.get(平台);
httpClient=TestBed.get(httpClient);
http=TestBed.get(HttpTestingController);
拦截器=新的AddHeaderInterceptor(记录器、身份验证、平台、配置);
});
fit('应将标题添加到请求',(完成)=>{
expect((拦截器作为任何拦截器)AddHeaderInterceptor.toBeTruthy()的实例;
const next:任何={
句柄:(请求:HttpRequest)=>{
expect(request.headers.has('Authorization')).toBeTruthy();
expect(request.headers.get('Authorization')).toEqual('Bearer TESTO');
返回可观测值({hello:'world'});
}
};
const req=new-HttpRequest('GET',config.getValue('baseUrl')+'test');
interceptor.intercept(req,next).subscribe(obj=>done());
});
});
当我开始在拦截器中使用相同的fromPromise->switchMap模式时,我遇到了相同的情况。这似乎导致了测试问题(尽管代码似乎工作正常)。没有对承诺的呼唤,它工作得很好
不知道为什么-但是你的测试解决方案对我有效。谢谢 我遇到了同样的问题。使用rxjs@6
from(somePromise)
导致测试失败。如果我没有承诺一切都会成功。这对我来说似乎是一个错误。我将提交一个问题。问题已打开并已创建
fdescribe('AddHeaderInterceptor Service', () => {
let http: HttpTestingController;
let httpClient: HttpClient;
let auth: AuthService;
let logger: LogService;
let config: ConfigurationService;
let platform: Platform;
let interceptor: AddHeaderInterceptor;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
ConfigurationService,
{
provide: HTTP_INTERCEPTORS,
useClass: AddHeaderInterceptor,
multi: true,
},
{ provide: Platform, useClass: PlatformMocked },
{ provide: LogService, useClass: LogServiceMock },
{ provide: AuthService, useClass: AuthServiceMock }
],
});
config = TestBed.get(ConfigurationService);
auth = TestBed.get(AuthService);
logger = TestBed.get(LogService);
platform = TestBed.get(Platform);
httpClient = TestBed.get(HttpClient);
http = TestBed.get(HttpTestingController);
interceptor = new AddHeaderInterceptor(logger, auth, platform, config);
});
fit('should add header to request', (done) => {
expect((interceptor as any) instanceof AddHeaderInterceptor).toBeTruthy();
const next: any = {
handle: (request: HttpRequest<any>) => {
expect(request.headers.has('Authorization')).toBeTruthy();
expect(request.headers.get('Authorization')).toEqual('Bearer TESTO');
return Observable.of({ hello: 'world' });
}
};
const req = new HttpRequest<any>('GET', config.getValue('baseUrl') + 'test');
interceptor.intercept(req, next).subscribe(obj => done());
});
});