我正在如下服务中导入和使用 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!
Angular 6 documentation on HTTP只是说要做我上面做的事。
最佳答案
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();
});
});
关于 Angular 6 - NullInjectorError : No provider for HttpClient in unit tests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769401/