Search code examples
angularangular-httpclient-interceptors

mock the server response even the server is unreachable


Things I know (please correct me if I'm wrong, thank you :)):

  • HttpInterceptor works in a way similar to Aspect-oriented programming;
  • adding/modifying httpOptions can be achieved for requests;
  • modifying the response with clone() can also be achieved for response;

My problems

I want to test some libraries while their related servers can be down sometimes when developing I just care about the data no interaction with server is okay

Is it possible that I can just return a mock data already prepared without requesting the server when the request met some patterns even the service lies in other libraries?

My Requirements

  • all the logic in the libraries stays the same;
  • using the mock data to respond to the http request from the libraries;

Updated 2019-01-15

Thanks to the help of @Sachin Gupta, I tested the interceptor further with this demo.

What have been done:

  • auth-interceptor.ts to add headers for the request;
  • logging-interceptor.ts added to track the request details and time cost;
  • data-mocking-interceptor.ts to stop the request to the server and return the mock data directly.

Solution

  • Have a look at this.

    https://stackblitz.com/edit/angular-json-http-response-catch

    If the server is reachable, the data is populated, otherwise mocked is sent as response

    Interceptor

    export class NoopInterceptor implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler):
        Observable<HttpEvent<any>> {
          let response = new HttpResponse();
          response = response.clone({body: [{"sads":"ewre"}]});
       
        return next.handle(req).pipe(catchError((err) => {return of(response).pipe(delay(10))}) );
      }
    }