error: Expected one matching request for criteria "Match by function: ", found none. I searched for many things and tried a few solutions. But none of them worked. This is my first project for unit testing. Here's my code.
Auth Interceptor
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 Interceptor Spec
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();
});
});
I also tried by setting authorization headers using mock service. Can anyone help me what I am missing here?