Angular单元测试NullInjectorError:没有HttpClient的提供程序!错误



我知道这个问题被问了一遍又一遍。我找不到一个有效的解决方案。我目前正在将单元测试添加到我们的项目中,从而修复所有自动生成的测试。

但是当运行ng测试时,我得到以下错误:

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();
});
});

这是我的"服务测试模块">

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 { }

我也检查过,"进口"总是在"供应商"之前,但仍然没有运气。

我还阅读了(并测试了(所有关于这个主题的Github和Stackoverflow帖子,但由于我在那里运气不佳,我再次问这个问题。

提前感谢

我刚开始使用Angular,遇到了同样的问题。当组件/服务使用HttpClientModule时,似乎需要在beforeEach函数中导入HttpClientTestingModule

以下是一个名为SituationService的服务示例

import { TestBed } from '@angular/core/testing';
import { SituationService } from './situation.service';
import {HttpClientTestingModule} from '@angular/common/http/testing';

describe('SituationService', () => {
let service: SituationService;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
]});

TestBed.configureTestingModule({});
service = TestBed.inject(SituationService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});

以下是一个名为Situation的组件的示例

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SituationComponent } from './situation.component';
import {HttpClientTestingModule} from '@angular/common/http/testing';
describe('SituationComponent', () => {
let component: SituationComponent;
let fixture: ComponentFixture<SituationComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ SituationComponent ],
imports: [
HttpClientTestingModule
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SituationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

请注意每个beforeEach函数中的imports部分。

尝试将HttpClientModule添加到提供者

相关内容

最新更新