Angular 6 - NullInjectorError : No provider for HttpClient in unit tests

标签 angular karma-jasmine 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...");
    }
}

但是,当我为我的单元测试 运行ng test 时,当这些测试使用该服务时,我收到错误:

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

Angular 6 documentation on HTTP只是说要做我上面做的事。

最佳答案

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

    });

关于 Angular 6 - NullInjectorError : No provider for HttpClient in unit tests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769401/

相关文章:

angular - 如何使用 Jasmine 在 Angular 单元测试中模拟 window.screen.width

Angular 2+ 服务测试。服务导入在 ng 测试运行时未定义

angular - 在字符串 "TypeError: Cannot create property ' 上获取错误 'control' 验证程序“

javascript - 单元测试 AngularJS Controller ,同时遵循最佳实践

javascript - 获取从 (keypress) angular2 按下哪个键

javascript - Jasmine 单元测试的方法称为

Angular Testing 错误 - this._formBuilder.group 不是函数

angular - 在 Angular 单元测试中使用回车键提交表单

node.js - 如何在 Ionic 2 中为在本地主机中运行的 Node 服务器发送发布请求?

css - 在 Angular 2 中使用 Sass