Testing an http interceptor has been quite the challenge for me. Despite having my token logged in the console and ensuring that the request URL matches, I still can't figure out why it's not working with the interceptor in place. Interestingly, all my other http services pass without any issues when tested using the same method.
The interceptor class below adds the bearer token to every request successfully. It relies on the Ionic Platform native class, which is mocked during testing:
@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);
}
The error message "Expected one matching request" keeps popping up no matter what I try. Even when I spy on the `getToken` method from the auth service, it never gets called. This issue persists whether I use absolute or relative URLs in `http.expectOne()`. Any suggestions on how to fix this?