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

前端 未结 3 692
予麋鹿
予麋鹿 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: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.

提交回复
热议问题