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