【发布时间】:2020-05-08 10:47:08
【问题描述】:
我知道这个问题被问了一遍又一遍。我找不到可行的解决方案。我目前正在向我们的项目添加单元测试,从而修复所有自动生成的。
但是在运行 ng test 时,出现以下错误:
NullInjectorError: R3InjectorError(DynamicTestModule)[Service -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
注意 -> HttpClient -> HttpClient。
当我第一次看到这个时,我认为这一定是一个循环依赖问题。这导致我创建了一个测试测试模块,我将其导入到我的 TestBed 中。
这是一个失败的示例测试。
import { TestBed } from '@angular/core/testing';
import { SearchListService } from './search-list.service';
import { ServiceTestingModule } from '@app/testing/service.testing.module';
import { ZhwKnowledgeJourneyService } from '@bkh/services/zhw-knowledge-journey.service';
describe('ZhwKnowledgeJourneyService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [ServiceTestingModule],
providers: [SearchListService]
}));
it('should be created', () => {
const service: ZhwKnowledgeJourneyService = TestBed.inject(ZhwKnowledgeJourneyService);
expect(service).toBeTruthy();
});
});
这是我的“ServiceTestingModule”
import { NgModule } from '@angular/core';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
CommonModule,
HttpClientModule,
HttpClientTestingModule,
],
declarations: [],
providers: [],
exports: [HttpClientModule, HttpClientTestingModule]
})
export class ServiceTestingModule { }
我也检查过,“imports”总是在“providers”之前,但仍然没有运气。
我还阅读了(并测试了)关于该主题的所有 Github 和 Stackoverflow 帖子,但由于我在那里没有运气,我再次问这个问题。
提前致谢
【问题讨论】:
-
尝试在测试中导入
HttpClientTestingModule,不要与HttpClientModule混淆 -
@MikeS。正如您在我的代码中看到的,我已经这样做了。或者你会改变什么?我也尝试直接导入这个模块。但没有运气。
标签: angular typescript httpclient