Angular 5服务无法通过单元测试(NullInjectorError:没有HttpClient的提供程序!)

时间:2018-02-01 22:13:16

标签: angular unit-testing typescript angular5

运行单元测试时,我一直遇到以下错误

Error: StaticInjectorError(DynamicTestModule)[ApiService -> HttpClient]: 
      StaticInjectorError(Platform: core)[ApiService -> HttpClient]: 
        NullInjectorError: No provider for HttpClient!

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ApiService {

  constructor(private http: HttpClient) { }
  url = './assets/data.json';

  get() {
    return this.http.get(this.url);
  }
}

api.service.spec.ts

import { TestBed, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { ApiService } from './api.service';

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

  it('should get users', inject([HttpTestingController, ApiService],
      (httpMock: HttpTestingController, apiService: ApiService) => {
        expect(apiService).toBeTruthy();
      }
    )
  );
});

由于我将HttpClient包含在api.service.ts中,我不明白出了什么问题,该服务在浏览器中有效。

这在名为MapComponent的组件中直接调用,并在HomeComponent中调用。

Chrome 63.0.3239 (Mac OS X 10.13.3) HomeComponent expect opened to be false FAILED
    Error: StaticInjectorError(DynamicTestModule)[ApiService -> HttpClient]: 
      StaticInjectorError(Platform: core)[ApiService -> HttpClient]: 
        NullInjectorError: No provider for HttpClient!

4 个答案:

答案 0 :(得分:26)

"NullInjectorError: No provider for HttpClient!"的原因是未解决的依赖关系。在这种情况下,缺少HttpClientModule

在.service.spec.ts文件中添加

  imports: [
        HttpClientTestingModule,
    ],

您可能会注意到我写的是 HttpClientTestingModule 而不是HttpClientModule。原因是我们不想发送实际的http请求,而是使用测试框架的Mock API。

答案 1 :(得分:7)

尝试将inject包裹在async中,如下所示:

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();
  })));

});

请勿忘记从async导入@angular/core/testing

我在这方面取得了很大的成功。它与您的单元测试唯一不同,我使用的是HttpClientTestingModule

答案 2 :(得分:1)

我导入了 HttpClientModule and HttpClientTestingModule 个模块来解决我的问题。

import { HttpClientTestingModule } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';

  imports: [
        HttpClientModule,
        HttpClientTestingModule
      ]

答案 3 :(得分:0)

像这样简单地添加它,

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientModule,
      ],
    }).compileComponents();
  });