Unit testing HttpInterceptor from Angular 4

unit test interceptor angular 6
angular http interceptor
angular unit test http error response
unit test interceptor java
angular mock httpclient
angular testing flush
token interceptor angular 8
unit test for service angular 6

Can you tell me how to test the HttpInterceptor provided by the Angular 4. I have created an interceptor as per the examples but not sure how to test it. Below is my interceptor and I want to test if the custom headers are added and when response status is 401 window.location.href is done.

export class MyInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const headers = new HttpHeaders();
        this.addHeader(headers); // This will add headers

        const changedReq = req.clone({ headers: headers });
        return next.handle(req)
            .catch(err => {
                if (err instanceof HttpErrorResponse) {
                    switch (err.status) {
                        case 302:
                        case 401:
                            window.location.href = "http//google.com";
                            break;             
                        default:
                            throw new Error(this.getErrorMessage(err));
                    }
                }

                return Observable.throw(err);
            });
    }

I got stuck testing a similar thing, but thanks to Alisa's article Intercepting HTTP Requests I got it to work

    import {TestBed, inject} from '@angular/core/testing';
    import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
    import {HTTP_INTERCEPTORS, HttpClient} from '@angular/common/http';

    import {LangInterceptorService} from './lang-interceptor.service';

    describe('Lang-interceptor.service', () => {
       beforeEach(() => TestBed.configureTestingModule({
             imports: [HttpClientTestingModule],
             providers: [{
                         provide: HTTP_INTERCEPTORS,
                         useClass: LangInterceptorService,
                         multi: true
              }]
       }));

       describe('intercept HTTP requests', () => {
            it('should add Accept-Language to Headers', inject([HttpClient, HttpTestingController],
              (http: HttpClient, mock: HttpTestingController) => {

                   http.get('/api').subscribe(response => expect(response).toBeTruthy());
                   const request = mock.expectOne(req => (req.headers.has('Accept-Language') && req.headers.get('Accept-Language') === 'ar'));

                   request.flush({data: 'test'});
                   mock.verify();
             }));
        });

        afterEach(inject([HttpTestingController], (mock: HttpTestingController) => {
             mock.verify();
        }));
    });

Testing Angular Http Interceptors ← Alligator.io, Angular HttpInterceptors can be used to modify Http requests, this article looks at testing these This article looks at testing this integration. Interceptors are Building Maps in Angular using Leaflet, Part 4: The Shape Service. Testing Angular Http Interceptors. HttpInterceptors allow us to modify HTTP requests within our application. A common use case is to add an Authorization header to each request. This article looks at testing this integration. Interceptors are part of Angular's HttpClient module, which was introduced with Angular 4.3.

I'm a bit late to the post, but I figured out a way of testing the interceptors outside of Angular's context. This means that you don't have to mock HTTP calls, you only test the intercept function like any Javascript function.

Let's say your interceptor only does that, which is displaying a log if the error status is 500 :

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next
    .handle(req)
    .catch((err: HttpErrorResponse) => {
      if(err.status === 500) { console.log('Server error'); }
    });
}

Then, in your service, you can mock the parameters of your function like so :

const err: any = { status: 500 };
const next: any = {
  handle: (request: HttpRequest<any>) => ({
    catch: (callback: Function) => callback(err)
  })
};

With that, you can write a test for your interceptor :

it('should write a console log with error status equal to 500', () => {
  spyOn(console, 'log');

  service.intercept({} as any, next);

  expect(console.log).toHaveBeenCalled();
});

And voilà !

Intercepting Http Requests-- Using And Testing Angular's HttpClient , Tagged with angular, testing, javascript, programming. Alisa Aug 28 '17 Updated on Aug 26, 2018 ・4 min read The scope of this tutorial is only using the HttpClientModule and the associated unit tests for making http calls. So we can create our own interceptor by implementing Angular's HttpInterceptor interface. In this article, we will use Jasmine and Karma to perform unit tests in Angular 4. Jasmine This testing framework supports a software development practice which is called Behavior Driven

Just make any call and mock the response with .error() method of HttpTestingController and it should work.

describe('Error interceptor', function () {
let http: HttpTestingController;
  let httpClient: HttpClient;

  beforeEach(() => {
    const testBed = TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: MyInterceptor,
          multi: true
        }
      ],
    });

 http = testBed.get(HttpTestingController);
 httpClient = testBed.get(HttpClient);
 });

  it('should catch 401', function (done) {
    httpClient.get('/error').subscribe(() => {}, () => {
      // Perform test
      done();
    });

    http.expectOne('/error').error(new ErrorEvent('Unauthorized error'), {
      status: 401
    });
    http.verify();
  });

});

How to write Unit Test Cases for Angular HTTP Interceptor ?, Angular + Jasmine + Karma (Unit Test Case). Before writing unit test cases lets understand what is HTTP Interceptor and What are its practical  The HttpClientModule, which debuted in Angular 4.3, is an easy to use API. It automatically expects json as its default response type, builds in the ability to intercept both requests and responses, and makes testing a breeze.

Interceptor testing is similar to Testing of Angular service. And TestBed is going to provide all you need to test them.

beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                {
                    provide: HTTP_INTERCEPTORS,
                    useClass: MyInterceptor,
                    multi: true
                }]
        });
    });


describe('making http calls', () => {
        it('adding header test', inject([HttpClient, YourMock], (http: HttpClient, httpMock: YourMock) => {

            http.get('/data').subscribe(
                response => {
                    expect(response).toBeTruthy();
                }
            );

            expect(response.status).toEqual('401');
        }));
    });

Mocking your service will give you data which you want to duplicate during test.

How to Mock a Backend in Angular using HttpInterceptor, Like the name implies HttpInterceptor is used to intercept HTTP calls we want to put up a fast server for testing out our Angular app behavior. Angular unit test – testing retryWhen in HttpInterceptor. Source Url Angular unit test – testing retryWhen in HttpInterceptor. Share this: Twitter; Facebook; More

I wanted to get the response from the request modified by the interceptor, so I used the callback method of the handle object.

Test:

it("should set header authorization", async(() => {
    const token: string = "token_value";        

    let response: HttpResponse<any>;

    const next: any = {
      handle: responseHandle => {
        response = responseHandle;
      }
    };

    const request: HttpRequest<any> = new HttpRequest<any>("GET", `${API_URL}`);

    tokenInterceptor.intercept(request, next);

    expect(response.headers.get("Authorization")).toEqual(token);
}));

I also used a service mock that generates the token to control the value I wanted to validate.

Angular 7/8 HttpClient Interceptors: Mocking HTTP Requests , Using an Angular HTTP Interceptor This is also useful for unit testing. the Angular Interceptor; Step 4 - Registering the HTTP Interceptor  Step 3 - Creating the Angular Interceptor; Step 4 - Registering the HTTP Interceptor ; Step 5 - Configuring TypeScript to Import Local JSON files; Step 6 - Intercepting URLs and Returning Mocked JSON Data; Step 7 - Testing your HTTP Interceptor; Step 1 - Preparing your Angular Project. You should by now have an Angular project ready. Step 2 - Setting up Angular HttpClient

Unit testing HttpInterceptor from Angular 4 - angular - html, Can you tell me how to test the HttpInterceptor provided by the Angular 4. I have created an interceptor as per the examples but not sure how to test it. Below is  The content here applies to Angular 4.3+ Basic Setup. To implement an interceptor, you’ll want to create a class that’s injectable and that implements HttpInterceptor. The class should define an intercept method to correctly implement HttpInterceptor.

How to write unit tests for Angular code that uses the HttpClient?, One of the interesting additions that came about with the HttpClient in Angular is the HttpClientTestingModule. Using that module, one can fully (unit)test a  Most interceptors transform the outgoing request before passing it to the next interceptor in the chain, by calling next.handle (transformedReq) . An interceptor may transform the response event stream as well, by applying additional RxJS operators on the stream returned by next.handle ().

Angular Fundamentals, In the last lesson of this section, I'll show you how to unit test a custom HTTP interceptor. Create a Feature Component. Add In-app Navigation. Get Data from a Server. This guide offers tips and techniques for unit and integration testing Angular applications. The guide presents tests of a sample application created with the Angular CLI. This sample application is much like the one created in the Tour of Heroes tutorial .

Comments
  • Hi, i don't understand where does it come the variable service. did you injected it? do you have a full example?
  • Hi ! No I didn't inject it, I used TestBed.get(YourService). But you can inject it if you want, that's not an issue ! I don't know the best practice, I just know that I prefer using TestBed.get(YourService) rather than the inject() function.
  • I don't believe this would be useful as the point of the interceptor is to be used in angular's context. I considered doing this at first to help separate concerns but realistically I want to ensure that my interceptor works in angular as expected. Consider angular changes how interceptors work in vNext. This test would still pass, but the application wouldn't work as expected.
  • Depends on what your conception of a unit test is. For me, the intercept method of the interceptor is supposed to do something (in this case, log). So you can unit test it, outside of Angular's context. And if you want to test that, for instance, the headers are appended to your request, you can start by testing that headers are indeed appended in this isolated test, plus test that your requests, made by your services, go with the correct headers.
  • Thanks but I don't understand what is yourMock in this case. I want to make http.get call and want to check if the interceptor added the headers and want to mock the response.
  • you can skip that. its not required if you are not mocking anything.