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!”错误的一般步骤。根据您的具体代码和测试设置,您可能需要进行一些适应性调整。

相关内容

热门资讯

透视推荐!pokemmo脚本手... 透视推荐!pokemmo脚本手机版(透视)wepoker有用吗,教程烘培(今日头条)-哔哩哔哩1、起...
pokermaster破解版!... pokermaster破解版!wepoker提高好牌率(透视)app-确实揭幕是真的挂1、下载好we...
透视开挂!菠萝辅助器免费版的特... 透视开挂!菠萝辅助器免费版的特点(透视)智星德州辅助译码插件靠谱吗,教程模块(有挂技术)-哔哩哔哩1...
wpk软件是真的吗!红龙pok... wpk软件是真的吗!红龙poker辅助器免费观看(透视)教程-果然详情是真的挂1、红龙poker辅助...
hhpoker软件靠谱吗!hh... hhpoker软件靠谱吗!hhpoker辅助靠谱吗(透视)工具-原来开挂存在有挂1、首先打开hhpo...
透视详细!wepoker代打辅... 您好,wpk透视怎么安装这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...
wepoker辅助器如何使用!... wepoker辅助器如何使用!德州hhpoker是真的吗(透视)软件-切实分享是真的挂小薇(辅助器软...
透视曝光!wepoker透视挂... 透视曝光!wepoker透视挂底牌(透视)fishpoker透视,教程绝活(有挂技术)-哔哩哔哩1、...
wepoker公共底牌!wep... wepoker公共底牌!wepoker怎么看底牌(透视)挂-都是详情真的是有挂小薇(辅助器软件下载)...
wepoker开辅助能查到吗!... wepoker开辅助能查到吗!pokemmo辅助器(透视)器-其实解密真的有挂1)wepoker开辅...