Angular 6 - NullInjectorError:单元测试中没有 HttpClient 的提供者

问题描述 投票:0回答:4

我正在服务中导入并使用

HttpClient
,如下所示:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root',
})
export class MyService {
    constructor(private http: HttpClient) { }

    getData() {
        return this.http.get("url...");
    }
}

但是,当我为我的

单元测试
运行ng test时,并且当这些测试使用该服务时,我收到错误:

Error: StaticInjectorError(DynamicTestModule)[HttpClient]: 
  StaticInjectorError(Platform: core)[HttpClient]: 
    NullInjectorError: No provider for HttpClient!

HTTP 上的 Angular 6 文档 只是说要执行我上面所做的操作。

angular karma-jasmine angular-test
4个回答
155
投票
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';
import { myService } from './myservice';


describe('myService', () => {

      beforeEach(() => TestBed.configureTestingModule({
        imports: [HttpClientTestingModule], 
        providers: [myService]
      }));

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

       it('should have getData function', () => {
        const service: myService = TestBed.get(myService);
        expect(service.getData).toBeTruthy();
       });

    });

2
投票
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { myService } from './myservice';

describe('HeaderService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [ HttpClientTestingModule ],
    providers: [myService]
  }));
});

0
投票

角度 18+ 的注意事项

情况已经改变,您现在需要使用

provideHttpClientTesting()

HttpClientTestingModule 已被弃用。

现在应该可以工作了:

TestBed.configureTestingModule({
  providers: [ provideHttpClient(), provideHttpClientTesting() ],
...
}).compileComponents();

-1
投票

您应该将 HttpClient 添加到声明组件的模块的导入中

@NgModule({
  declarations: [
    MyComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: []
})
export class AppModule { }

更新:

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
必须包含在单元测试中

OP 问题不遵循单元测试指南。 HttpClientTestingModule 必须在 beforeEach 中导入

  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule], 
    providers: [dataService]  
  }));

基本上,HttpClientTestingModule 被注入到 dataService 中用于单元测试目的,以防止 StaticInjectorError

© www.soinside.com 2019 - 2024. All rights reserved.