Angular 5服务无法通过以下单元测试(NullInjectorError:HttpClient没有提供者!) [英] Angular 5 service failing to pass unit tests with (NullInjectorError: No provider for HttpClient!)

查看:338
本文介绍了Angular 5服务无法通过以下单元测试(NullInjectorError:HttpClient没有提供者!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I keep getting the following errors when running unit tests

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中,该服务在浏览器中有效.

I don't understand what is going wrong as I have included HttpClient into api.service.ts, the service works in the browser.

这在名为MapComponent的组件中直接调用,在HomeComponent内部调用.

This is directly called in a component called MapComponent, and that is called inside 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.

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

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

In your .service.spec.ts file add

  imports: [
        HttpClientTestingModule,
    ],

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

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.

这篇关于Angular 5服务无法通过以下单元测试(NullInjectorError:HttpClient没有提供者!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆