Angular 6-NullInjectorError:单元测试中没有HttpClient的提供程序
我正在以下服务中导入和使用Angular 6-NullInjectorError:单元测试中没有HttpClient的提供程序,angular,karma-jasmine,angular-test,Angular,Karma Jasmine,Angular Test,我正在以下服务中导入和使用HttpClient: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class MyService { constructor(private http: HttpClient) { } getData() {
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测试
时,当这些测试使用服务时,我得到错误:
错误:StaticInjectorError(DynamicTestModule)[HttpClient]:
StaticInjectorError(平台:核心)[HttpClient]:
NullInjectorError:HttpClient没有提供程序代码>
刚才说要做我上面所做的。您应该将HttpClient添加到模块的导入中,在导入中声明您的组件
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();
});
});
@NgModule({
declarations: [
MyComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: []
})
export class AppModule { }
单元测试的代码是什么?这很重要。@KevinDoyon的可能重复不,我的问题是关于单元测试失败,而不是其他方面。这正是重复的内容:)您可能没有将HttpClientModule
导入到您的测试中。您的测试创建自己的模块。如果不在那里导入HttpClientModule
(或HttpClientTestingModule
),则HttpClient
将无法工作,因为Angular不知道它。将HttpClientModule
添加到AppModule
中并不重要。它需要在测试床中。配置测试模块
。如果您有SharedModule
,也可以导入SharedModule
,只要HttpClientModule
在exports
中即可。但是测试会比较慢,因为SharedModule
将包含不需要的stuff@KevinDoyon你说得对,谢谢,我只需要导入HttpClientTestingModule
。谢谢,我只需要将HttpClientTestingModule
添加到configureTestingModule
方法中的imports
数组中。是的,我只想发布它,但我说让它充满,我很高兴它能帮助我工作,我想在主测试中添加模块,但它必须添加到服务的测试中,这有助于从'@angular/common/http'导入{HttpClientModule};没有必要,因为测试类实际上没有使用它。谢谢!这对我在第九章中起了作用。从“@angular/common/http/testing”导入{HttpClientTestingModule,HttpTestingController};beforeach(()=>TestBed.configureTestingModule({imports:[HttpClientTestingModule],providers:[myService]}));用户要求进行单元测试。。。不在服务中使用它
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]
}));
});