What is needed to do in this test, it is expected the request successfully get to the backend
(which is HttpTestingController
in this case) and in between client and backend, the interceptors intercept the request. Interceptors check and set conditions before letting it on or hold until conditions are met.
For the currently issue, if HTTP_INTERCEPTORS
is added to the providers, HttpTestingController
aka mockBackend
stops working and cannot use debugger and any examples to show why this could be a problem. Error message gives by karma.
Error: Expected one matching request for criteria "Match URL: /example", found none.
After remove the HTTP_INTERCEPTORS
in the provider, it starts to work again but I don't have access to the interceptorService
and cannot check some of the conditions. Lastly the interceptor does not seem to work in the unit test, could it be that I have too many layers between my home.component.ts
to my interceptorService
.
I looked at this question on stackoverflow, but I believe the order I called is correct, and I use the example from this link to create my test with interceptor.
http.service.ts
refreshSession(): Promise<boolean> {
return http.get(url, {}).then(()=>true).catch(()=>false);
}
app.spec.ts
beforeEach(() => {
TestBed.ConfigureTestingModule({
declarations: [ home.spec.ts ],
imports: [ HttpClientTestingModule ],
providers: [
interceptorService,
{
provide: HTTP_INTERCEPTORS,
useClass: interceptorService,
multi: true,
},
],
});
http = TestBed.get(HttpService);
interceptor = TestBed.get(interceptorService);
mockBackend = TestBed.get(HttpTestingController);
});
it('http requests make to the end', () => {
http.refreshSession().then(hasRefreshed => {
expect(hasRefreshed).toBeTruthy();
});
let header = new HttpHeaders();
header = header.append('token', 'abc');
let response = new HttpResponse({
status: 200,
headers: header,
});
interceptor.token = '123';
expect(interceptor.token).toBeDefined();
let backend = mockBackend.expectOne({
url: '/example',
method: 'GET',
});
backend.flush(response);
});