Angular 5 service failing to pass unit tests with (NullInjectorError: No provider for HttpClient!)

前端 未结 3 698
予麋鹿
予麋鹿 2021-01-31 14:18

I keep getting the following errors when running unit tests

Error: StaticInjectorError(DynamicTestModule)[ApiService -> HttpClient]: 
      StaticInjectorErro         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 15:11

    The reason for "NullInjectorError: No provider for HttpClient!" are unresolved dependencies. In this case the lack of a HttpClientModule.

    In your .service.spec.ts file add

      imports: [
            HttpClientTestingModule,
        ],
    

    You might notice that I wrote HttpClientTestingModule instead of HttpClientModule. The reason is that we don't want to send actual http requests, but rather use a Mock API of the test framework.

提交回复
热议问题