DEV Community

Angular Http Mock Interceptor for mocked backend

sanidz on March 06, 2019

Skip to end for stackblitz example Problem: Display list from api example <ul> <li *ngFor="let user of users"&gt...
Collapse
 
anetz89 profile image
Markus

Hi sandiz,
thank you for this interesting article! A small addon to your code:
Unless you do not need to intercept the standard http requests (to add a console log by using the HttpRequestInterceptor) you can modify your app.module.ts this way:
// ...
providers: [
...isMock ? [{
provide: HTTP_INTERCEPTORS,
useClass: HttpMockRequestInterceptor,
multi: true
}] : []
],
// ...

This assures that no interceptor is loaded in non-mock environments.

Collapse
 
hugoscavino profile image
Hugo Scavino

Your solution helped me with a cypress test. I was able to mock out the authentication without re-writing the code or adding hard-coded variables.

Collapse
 
mfaghfoory profile image
Meysam Faghfouri

Very interesting article! thanks for this!

Collapse
 
yagoferrer profile image
Yago

Hi Sanidz, I was wondering if that would also intercept a non-angular request. I would like to mock a Google Location API to save $$ when running e2e test.
Thanks!

Collapse
 
sanidz profile image
sanidz

Well, it is just a regular Angular Service, so it can intercept all requests coming from that app.

However if those requests are coming from another app you could just:
1 start local json server and mock needed google.apis
2 edit google api urls to hit new local mocked ones or if not possible
2.a edit hosts file so that your local json server acts and responds to all existing and real google api urls.

github.com/typicode/json-server

It also depends which e2e tests, cypress for example has full suport for endpoint mocking and could mock all requests out of the box :)

Collapse
 
danielsc profile image
Daniel Schreiber

Hi sanidz, I found that with Angular 9/Ivy the prod build will still contain the mock data/interceptor - did you find any way to solve this?