Angular 6-NullInjectorError:在单元测试中没有HttpClient的提供程序

Kin*_*ere 9 karma-jasmine angular angular-test

我正在导入和HttpClient在服务中使用,如下所示:

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

@Injectable({
    providedIn: 'root',
})
export class MyService {
    constructor(private http: HttpClient) { }

    getData() {
        return this.http.get("url...");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我ng test单元测试运行时,以及那些测试使用该服务时,出现了以下错误:

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

HTTP上Angular 6文档只是说了做我上面的事情。

use*_*622 14

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';
import { myService } from './myservice';


describe('myService', () => {

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

       it('should be created', () => {
        const service: myService = TestBed.get(myService);
        expect(service).toBeTruthy();
       });

       it('should have getData function', () => {
        const service: myService = TestBed.get(myService);
        expect(service.getData).toBeTruthy();
       });

    });
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我只需要在configureTestingModule方法中的imports数组中添加HttpClientTestingModule即可。 (4认同)
  • 描述该解决方案添加的内容以及它为何有效,将会很有帮助。没有言语,我被迫在OP的帖子和这个答案之间进行视觉差异。 (3认同)
  • 这有助于从 '@angular/common/http' 导入 {HttpClientModule};没有必要,因为测试类实际上并不使用它。 (2认同)