【问题标题】:NullInjectorError: StaticInjectorError(DynamicTestModule)[HttpClient -> HttpHandler]: StaticInjectorError(Platform: core)[HttpClient ->NullInjectorError:StaticInjectorError(DynamicTestModule)[HttpClient -> HttpHandler]:StaticInjectorError(平台:核心)[HttpClient ->
【发布时间】:2021-10-25 14:22:49
【问题描述】:

这是我升级到angular 12 后测试时遇到的错误。

NullInjectorError: StaticInjectorError(DynamicTestModule)[HttpClient -> HttpHandler]: StaticInjectorError(平台:核心)[HttpClient -> HttpHandler]: NullInjectorError: 没有 HttpHandler 的提供者!

我尝试将 HttpClientModule 添加到 TestBed.configureTestingModule

的导入数组中

甚至我的项目也有服务器端渲染。

请帮帮我,我已经尝试了所有可用的解决方案,但仍然遇到同样的错误

【问题讨论】:

    标签: angular


    【解决方案1】:

    您需要将HttpClientTestingModule 添加到测试文件的导入中。

    因此您的规范文件可能看起来与此类似

    import { HttpClientTestingModule } from '@angular/common/http/testing';
    import { TestBed } from '@angular/core/testing';
    
    import { FftService } from './fft.service';
    
    describe('FftService', () => {
      let service: FftService;
    
      beforeEach(() => { 
        TestBed.configureTestingModule({
          imports: [HttpClientTestingModule],
        });
        service = TestBed.inject(FftService);
      });
    
      test('should be created', () => {
        expect(service).toBeTruthy();
      });
    });
    

    如果您还想测试 API,请不要忘记导入 HttpTestingController

    带有控制器的规范文件可能如下所示

    import { TestBed, getTestBed } from '@angular/core/testing';
    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
    import { InfoService } from './info.service';
    import { InfoBackend } from '@sharedModels';
    import { first } from 'rxjs/operators';
    describe('InfoService', () => {
      let injector: TestBed;
      let service: InfoService;
      let httpMock: HttpTestingController;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [HttpClientTestingModule],
          providers: [InfoService],
        });
        injector = getTestBed();
        service = injector.inject(InfoService);
        httpMock = injector.inject(HttpTestingController);
      });
    test('Endpoint test',()=> {// do testing here})
    });
    

    【讨论】:

    • @ankitsingh 你能创建堆栈闪电战或类似代码或提供代码吗?这样我就帮不上什么忙了
    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2018-05-29
    相关资源
    最近更新 更多