title: How to test angular http interceptors with injected objects
body: <p>I am trying to test if my interceptor dispatches the correct action to an ngrx Store if a backend responds with a 419 status code - which we use to signal that a users session expired.</p>
  
  <p>It is working if i try it by hand - but i cannot get a unittest to verify this. The call to my store never happens. I assume the store i spy on is not the store injected into the interceptor or i expect the call to early somehow?</p>
  
  <p>This is my code so far:</p>
  
  <pre><code>fdescribe('Http Session Timeout Interceptor', () =&gt; {
      let store: Store&lt;AppState&gt;;
  
      beforeEach(() =&gt; {
  
          TestBed.configureTestingModule({
              imports: [HttpClientTestingModule, StoreModule.forRoot(appReducers)],
              providers: [{
                  provide: HTTP_INTERCEPTORS,
                  useClass: HttpSessionTimeoutInterceptor,
                  multi: true
              }]
          });
          store = TestBed.get(Store);
          spyOn(store, 'dispatch');
      });
  
      it('interceptor is called',
          inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) =&gt; {
          http.get('/api').subscribe(response =&gt; {
             const cast = response as HttpResponse&lt;String&gt;;
             expect(cast.status).toBe(419);
          });
          const req = httpMock.expectOne('/api');
          req.flush(&lt;HttpResponse&lt;String&gt;&gt;{status: 419});
          httpMock.verify();
          expect(store.dispatch).toHaveBeenCalledWith(new SessionTimeOutAction());
          }));
  });
  </code></pre>
  
  <p>This is the interceptor, simply checking the response status and dispatching the action:</p>
  
  <pre><code>@Injectable()
  export class HttpSessionTimeoutInterceptor implements HttpInterceptor {
      constructor(private store: Store&lt;AppState&gt;) {}
  
      intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
          return next.handle(req)
              .catch(response =&gt; {
                  if (response.status === 419) {
                      this.store.dispatch(new SessionTimeOutAction());
                  }
                  return Observable.throw(response);
              }) as any;
      }
  }
  </code></pre>