Angular 6服务在单元测试中无法通过(NullInjectorError:没有HttpClient的提供者!)
创始人
2024-10-16 08:01:05
0

要解决“NullInjectorError: No provider for HttpClient!”错误,您可以按照以下步骤进行操作:

  1. 确保您在使用HttpClient之前已经导入了HttpClientModule:
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [HttpClientModule],
  ...
})
export class AppModule { }
  1. 在您的服务(或组件)的测试文件中,添加HttpClientTestingModule:
import { HttpClientTestingModule } from '@angular/common/http/testing';

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    ...
  })
  .compileComponents();
}));
  1. 如果您在测试前需要使用HTTP请求进行设置,请使用HttpTestingController来拦截请求并提供响应。例如:
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('YourService', () => {
  let service: YourService;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [YourService]
    });

    service = TestBed.get(YourService);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('should make a GET request', () => {
    const testData = { message: 'test' };

    service.getData().subscribe(data => {
      expect(data).toEqual(testData);
    });

    const req = httpTestingController.expectOne('your-url');
    expect(req.request.method).toEqual('GET');

    req.flush(testData);
  });

});

以上是解决“NullInjectorError: No provider for HttpClient!”错误的一般步骤。根据您的具体代码和测试设置,您可能需要进行一些适应性调整。

相关内容

热门资讯

六分钟辅助!wepoker私人... 六分钟辅助!wepoker私人局可以透视,德普之星透视辅助软件激活码,教材教程(有挂教程)1)德普之...
第二分钟辅助!wepoker好... 第二分钟辅助!wepoker好友助力码,wepoker透视辅助下载,指引教程(有挂助手)1、wepo...
六分钟辅助!wpk模拟器,hh... 六分钟辅助!wpk模拟器,hhpoker的辅助是真的吗,策略教程(新版有挂)1、hhpoker的辅助...
9分钟辅助!微扑克微乐辅助,w... 9分钟辅助!微扑克微乐辅助,wepoker私人局辅助器怎么用,指引教程(有挂方略)1、用户打开应用后...
第1分钟辅助!wepoker免... 第1分钟辅助!wepoker免费脚本咨询,hhpoker有没有作弊挂,举措教程(有挂实锤)1、起透看...
第十分钟辅助!cloudpok... 第十分钟辅助!cloudpoker作弊,wepoker模拟器哪个好用,大纲教程(了解有挂)1.wep...
第5分钟辅助!fishpoke... 第5分钟辅助!fishpoker透视,epoker透视,妙招教程(真是有挂)1、金币登录送、破产送、...
第九分钟辅助!wpk有那种辅助... 第九分钟辅助!wpk有那种辅助吗,wepoker私人局规律,窍门教程(有挂教学)亲,关键说明,wep...
第2分钟辅助!wepoker私... 第2分钟辅助!wepoker私人局辅助,wepoker作弊视频,举措教程(有挂技巧)1、第2分钟辅助...
第6分钟辅助!德普之星辅助器,... 第6分钟辅助!德普之星辅助器,德州透视插件,资料教程(有挂总结)1、在德普之星辅助器插件功能辅助器技...