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

前端 未结 3 690
予麋鹿
予麋鹿 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 14:49

    simply add it like this,

      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [
            HttpClientModule,
          ],
        }).compileComponents();
      });
    
    0 讨论(0)
  • 2021-01-31 15:01

    Try wrapping your inject in an async, like below:

    import { TestBed, async, inject } from '@angular/core/testing';
    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
    import { ApiService } from './api.service';
    
    describe('ApiService', () => {
        beforeEach(() => {
          ...
        });    
    
      it(`should create`, async(inject([HttpTestingController, ApiService],
        (httpClient: HttpTestingController, apiService: ApiService) => {
          expect(apiService).toBeTruthy();
      })));
    
    });
    

    Don't forget to import async from @angular/core/testing.

    I have had good success with this. It's the only different from your unit tests and mine where I use HttpClientTestingModule.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题