我正在服务中导入并使用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 HTTP文档只是建议执行我上面所做的操作。
HttpClientModule
。你的测试会创建自己的模块。如果你没有在那里导入HttpClientModule
(或者HttpClientTestingModule
),HttpClient
就无法工作,因为Angular不知道它的存在。即使你在比如AppModule
中添加了HttpClientModule
也没有用。它需要在TestBed.configureTestingModule
中。如果你有一个SharedModule
,也可以导入它,只要HttpClientModule
在其中被exports
了。但是测试会变慢,因为SharedModule
中可能包含不必要的东西。 - Kevin DoyonHttpClientTestingModule
就好了。 - Kingamere