我正在服务中导入并使用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...");
    }
}

然而,当我为我的unit tests运行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相关问答推荐

在状态更新后是否会再次触发ngrx效果?

如何用Effect()识别正确的Angular 信号?

带逻辑的组件decorator 中的Angular 主机侦听器属性

带有服务依赖的Angular测试类

如何在构造函数中测试MatDialog.Open

Rxjs重置执行后的可观察延迟并重新调度Angular

使选项卡与父零部件成一定Angular 激活

NGX- colored颜色 Select 器安装出错

Angular :为什么我得到了一个可观察到的共鸣

Angular将文件作为字符串读取给dxf解析器

MonoTypeOperatorFunction不可分配给OperatorFunction类型的参数

是否可以在Angular(12+)中迭代指定的范围而不是整个数组

无法在 app.component.html 中呈现自定义组件

由于ngcc操作失败,Angular扩展可能无法正常工作

执行ng generate environments时出错时需要合集和原理图

如何在 form.value 中禁用复选框

Rxjs Observable:仅为第一个订阅者获取 HTTP 数据,为其余订阅者获取缓存数据

角项目更新

如何每隔一段时间发出 HTTP 请求?

如何在 Angular CLI 的构建时插入内部版本号或时间戳