Unit Tests for Interceptor
Let's write unit tests for auth interceptor.
We'll cover the following...
Let’s add our Auth Interceptor’s component-level tests. Here is our updated code:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>LetsGetLunch</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html>
Before we test the interceptor, add the interceptor to AppModule
. While our interceptor is still a service, it’s different in many ways, and implementing it and adding it to our app before testing it may improve the test’s clarity.
- Update the imports by importing both
HTTP_INTERCEPTORS
and our newAuthInterceptorService
.
// src/app/app.module.tsimport { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';import { AuthInterceptorService } from './interceptors/auth-interceptor.service';
- Update the
providers
adding our interceptor.
// src/app/app.module.tsproviders: [{provide: HTTP_INTERCEPTORS,useClass: AuthInterceptorService,multi: true}]
Remember in the previous lesson, when we removed the providedIn
property in the @Injectable
decorator of our interceptor? We did that to manually provide the interceptor here instead.
Interceptors in Angular are optional dependencies of HttpClient
and, because of that, we must provide them in the same place as the HttpClient
. Because HttpClientModule
is imported in AppModule
HttpClient
, it is provided in our app’s root injector. This means that we must provide our interceptors here as well.
It isn’t uncommon for applications to have more than one interceptor, either. For that reason, we’ve registered our interceptor, adding the multi: true
option informing Angular that ...