【问题标题】:StaticInjectorError exception for user defined HttpInterceptor用户定义的 HttpInterceptor 的 StaticInjectorError 异常
【发布时间】:2021-11-16 22:12:02
【问题描述】:

运行 ng 测试后,出现以下错误。

NullInjectorError: StaticInjectorError[RequestInterceptor]: NullInjectorError: 没有 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();
  });
});

有人可以告诉我为什么会得到这个吗?

【问题讨论】:

    标签: angular angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    只需将RequestInterceptor 添加到提供者即可:

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

    【讨论】:

    • 非常感谢@Dariusz。这对我有用
    • 很高兴帮助@VineelPellella,您可以将此线程标记为已解决:)
    猜你喜欢
    • 2016-10-07
    • 1970-01-01
    • 2012-10-16
    • 2020-01-26
    • 2016-09-10
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多