Unit Tests for Interceptor
Explore how to unit test Angular Auth Interceptors by configuring the test environment, making HTTP requests, and verifying request modifications. This lesson guides you through setting up HttpClientTestingModule and using HttpTestingController to assert that the interceptor correctly adds authorization headers to outgoing requests.
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_INTERCEPTORSand our newAuthInterceptorService.
- Update the
providersadding our interceptor.
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. ...