我正在服务中导入并使用
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 文档 只是说要执行我上面所做的操作。
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();
});
});
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]
}));
});
角度 18+ 的注意事项
情况已经改变,您现在需要使用
provideHttpClientTesting()
。
HttpClientTestingModule 已被弃用。
现在应该可以工作了:
TestBed.configureTestingModule({
providers: [ provideHttpClient(), provideHttpClientTesting() ],
...
}).compileComponents();
您应该将 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