运行单元测试时,我不断收到以下错误

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!

最佳答案

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

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

  imports: [
        HttpClientTestingModule,
    ],

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

10-06 04:45
查看更多