Home > Software engineering >  StaticInjectorError exception for user defined HttpInterceptor
StaticInjectorError exception for user defined HttpInterceptor

Time:09-24

After running the ng test I am getting the below error.

NullInjectorError: StaticInjectorError[RequestInterceptor]: NullInjectorError: No provider for RequestInterceptor!

RequestInterceptor

import { HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class RequestInterceptor implements HttpInterceptor
{

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> 
  {
    let clonedRequest = request.clone();
    if(!request.url.endsWith('/login'))
    {
      const jwtToken = sessionStorage.getItem("Jwt_Token");
      clonedRequest = request.clone({
        headers: new HttpHeaders({
          "Authorization": "Bearer "   jwtToken,
          'Content-Type':  'application/json'
        })
      }) 
    }
    return next.handle(clonedRequest.clone());
  }
}

request-interceptor.spec.ts

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';

import { RequestInterceptor} from './request-interceptor';

describe('RequestInterceptorService', () => {
  
  beforeEach(() => TestBed.configureTestingModule({
    declarations: [],
    imports: [HttpClientModule, FormsModule, RouterTestingModule]
  }));

  it('should be created', () => {
    const service: RequestInterceptor = TestBed.get(RequestInterceptor);
    expect(service).toBeTruthy();
  });
});

Can someone please let me know why I am getting this?

CodePudding user response:

Just add RequestInterceptor to providers :

  beforeEach(() => TestBed.configureTestingModule({
    declarations: [],
    providers: [RequestInterceptor],
    imports: [HttpClientModule, FormsModule, RouterTestingModule]
  }));
  • Related