Angular 6 - NullInjectorError: ユニットテストに HttpClient のプロバイダーがありません 質問する

Angular 6 - NullInjectorError: ユニットテストに HttpClient のプロバイダーがありません 質問する

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 ドキュメント上記と同じことをするだけです。

ベストアンサー1

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();
       });

    });

おすすめ記事