我试图测试一个http拦截器,我找不到任何方法来做到这一点。
我不知道为什么url不匹配,因为我的令牌记录在控制台中,请求url也是一样的。我使用这种方法测试了所有其他的http服务而没有拦截器,一切都通过了......
这是拦截器类,代码工作并在每个请求中添加我的承载令牌,它使用在测试中模拟的Ionic Platform本机类:
@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);
});
}
}
令牌记录在karma控制台中,我也检查了url并且总是有好的url,但是测试失败了。
这是我的auth服务模拟:
export class AuthServiceMock {
getToken() {
return Promise.resolve([
{ accessToken: 'TEST' }
]);
}
}
平台模拟:
export class PlatformMock {
public ready(): Promise<string> {
return Promise.resolve('READY');
}
}
以下是测试:
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'
});
});
});
我总是得到同样的错误:
错误:期望一个匹配的条件请求“匹配方法:GET,URL :(任何)”,找不到。
看起来请求永远不会启动,我试图创建一个类实例并直接调用拦截方法,我已经得到了相同的错误。我试图窥探来自auth服务的getToken
method并且它从未被调用过。所以我不知道为什么失败了。
我试图用另一个url调用另一个服务,但我仍然遇到同样的错误。
我尝试使用绝对或相对网址与http.expectOne('http://localhost:8080/test')
,它仍然是相同的:
预期一个匹配的标准匹配请求“匹配URL:http://localhost:8080/test”,找不到。
有人有想法吗?
我找到了使用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());
});
});
当我开始在拦截器中使用相同的fromPromise - > switchMap模式时,我遇到了同样的情况。这似乎导致测试问题(虽然代码似乎工作正常)。没有对诺言的召唤,它就可以了。
不知道为什么 - 但你的测试解决方案对我有用。谢谢!