作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我知道这个问题已经被问过一遍又一遍。我找不到有效的解决方案。我目前正在向我们的项目添加单元测试,从而修复所有自动生成的测试。
但是在运行 ng test 时,出现以下错误:
NullInjectorError: R3InjectorError(DynamicTestModule)[Service -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
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 { }
最佳答案
我也刚开始使用 Angular 并遇到了同样的问题。看来您需要导入 HttpClientTestingModule
在您的 beforeEach
当您的组件/服务使用时的函数 HttpClientModule
.
这是一个名为 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();
});
});
注意
imports
每个部分
beforeEach
功能。
关于Angular 单元测试 NullInjectorError : No provider for HttpClient! 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61677365/
我是一名优秀的程序员,十分优秀!